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

(Tuis.) #1
JSON

Inflector | 59

Inflector inflections.rb,inflector.rb


TheInflectormodule provides a set of simple transformations on English words to facili-
tate ActiveRecord’s manipulations of class and table names. Following the policy of
“convention over configuration,” for example, a model class namedMessagewould corre-
spond to a table name ofmessages.


The core ofInflectoris the pluralization rules, contained ininflections.rb. The default set
of rules is fairly broad, but additional rules can be added easily inconfig/initializers/
inflections.rb or a similar configuration file, after the framework loads:
Inflector.inflections do |inflect|
inflect.plural /^(ox)$/i, '\1\2en'
inflect.singular /^(ox)en/i, '\1'


inflect.irregular 'octopus', 'octopi'

inflect.uncountable "equipment"
end

Inflector.inflectionsyields a singleton instance of the inflections object. Rules are
prepended to the list of inflections, so these rules will override the default as long as they
are loaded after the Rails framework. Another consequence of the load order is that the
rules should be ordered from most general to most specific within a block; the last appro-
priate inflection rule seen will be used.


The regular expression captures and backreferences ensure that initial capitals are handled
correctly; the initial letters (upper- or lowercase) are captured with a case-insensitive regex
and substituted into the replacement. Theirregularanduncountablerules take care of that
work for us:


"ox".pluralize # => "oxen"
"Ox".pluralize # => "Oxen"
"Octopus".pluralize # => "Octopi"
"Equipment".pluralize # => "Equipment"

Inflector’s module methods, which actually perform the transformations, are proxied
from the core extensions toStringandInteger; they are usually not called directly on the
Inflectormodule object.*See the respective sections in the Core Extensions documenta-
tion later in the chapter for more information.


JSON json.rb,json/encoders.rb,json/encoders/core.rb


JSON (JavaScript Object Notation, pronounced “Jason”) is a lightweight subset of Java-
Script’s notation for literal objects (hash tables) used for data interchange on the Web.
ActiveSupport::JSONprovides encoders for most basic Ruby data types. The encoders are
proxied by theObject#to_json method, added by Core Extensions.
(1..5).to_json # => "[1, 2, 3, 4, 5]"
{:a => 1, :b => [2, 3]}.to_json # => "{b: [2, 3], a: 1}"


*"thing".pluralize reads better thanInflector.pluralize("thing").

Free download pdf