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

(Tuis.) #1

Range


72 | Chapter 2: ActiveSupport and RailTies


Miscellaneous methods core_ext/object/misc.rb



  • Object#returninglets you perform some operations on an object and then return it. It
    is usually used to encapsulate some incidental operations on an object in a block:
    returning(Person.new) do |p|
    p.name = "Brad"
    end # => #<Person:0x1e33b4 @name="Brad">

  • Object#with_optionsprovides a way to factor out redundant options on multiple
    method calls. It is usually seen in routing code:
    map.with_options(:controller => "person") do |person|
    person.default "", :action => "index"
    person.details "/details/:id", :action => "details"
    end
    Thewith_optionscall yields an OptionMerger, which is a proxy that forwards all of its
    method calls to the context (which, in this example, is the original map). The options
    provided are merged into the method call’s last hash argument, so the effect of the
    person.default call is the same as:
    map.default "", :action => "index", :controller => "person"
    map.details "/details/:id", :action => "details", :controller => "person"
    There is no magic here that makes this specific to Rails routes; you can use this with
    any method that takes a hash of Rails-style keyword arguments as the last parameter.
    The proxy object passed into thewith_optionsblock delegates any unknown method
    calls to the target.


Range core_ext/range/include_range.rb,core_ext/range/overlaps.rb



  • Range#include? checks to see whether a range completely includes another range:
    (1..10).include?(3..5) # => true
    (1..10).include?(3..15) # => false

  • Range#overlaps? checks to see whether a range overlaps another range:


    (1..10).overlaps?(3..15) # => true
    (1..10).overlaps?(13..15) # => false






String


Inflector core_ext/string/inflections.rb


The methods in this file delegate to theInflector.



  • String#singularizeandString#pluralizedo what you would think. Corner cases are
    more or less supported; you can add custom rules that override the defaults.
    "wug".pluralize # => "wugs"
    "wugs".singularize # => "wug"
    "fish".pluralize # => "fish"

  • String#camelizeis used to convert file names to class names;String#underscoredoes
    the opposite.
    "action_controller/filters".camelize # => "ActionController::Filters"
    "ActionController::Filters".underscore # => "action_controller/filters"

Free download pdf