Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
Examples | 43

However, there are some disadvantages to writing what is essentially self-modifying
code:



  • Tracing is only available at the function level. More detailed tracing would
    require changing or patching the original code. Rails code tends to address this
    by making methods small and their names descriptive.

  • Stack traces do become more complicated when tracing is enabled. With trac-
    ing, a stack trace into thePerson#refreshmethod would have an extra level:
    #refresh_with_timing, then#refresh_without_timing (the original method).

  • This approach may break when using more than one application server, as the
    functions are aliased in-memory. The changes will not propagate between serv-
    ers, and will revert when the server process is restarted. However, this can actu-
    ally be a feature in production; typically, you will not want to profile all traffic in
    a high-traffic production environment, but only a subset of it.


Rails Routing Code


The Rails routing code is perhaps some of the most conceptually difficult code in
Rails. The code faces several constraints:



  • Path segments may capture multiple parts of the URL:
    — Controllers may be namespaced, so the route":controller/:action/:id"
    can match the URL"/store/product/edit/15", with the controller being
    "store/product".
    — Routes may containpath_infosegments that destructure multiple URL seg-
    ments: the route"page/*path_info"can match the URL"/page/products/
    top_products/15", with thepath_infosegment capturing the remainder of
    the URL.

  • Routes can be restricted by conditions that must be met in order for the route to
    match.

  • The routing system must be bidirectional; it is run forward to recognize routes
    and in reverse to generate them.

  • Route recognition must be fast because it is run once per HTT Prequest. Route
    generation must be lightning fast because it may be run tens of times per HTTP
    request (once per outgoing link) when generating a page.


Michael Koziarski’s new routing_optimisation code in Rails 2.0
(actionpack/lib/action_controller/routing_optimisation.rb) addresses the
complexity of Rails routing. This new code optimizes the simple case
of generation of named routes with no extra:requirements.
Free download pdf