Some Core Rails Helper for Ruby

Posted on August 10, 2011

3


The Core Extensions are ActiveSupport’s collection of extensions to Ruby’s core
classes and modules. They are basic design patterns solving problems that are
encountered often in Ruby. These methods are one level below the Rails API; they
are the internal functions that Rails uses.

Class:Array–>
————————————————————————————————————————————-

Conversions
core_ext/array/conversions.rb
• Array#to_sentence joins the array’s elements and converts to a string:
%w(Larry Curly Moe).to_sentence # => “Larry, Curly, and Moe”

• Array#to_s(:db) collects an array of ActiveRecord objects (or other objects that
respond to the id method) into a SQL-friendly string.

• Array#to_xml converts an array of ActiveRecord objects into XML. This is usually used
to implement REST-style web services. It relies on the contained objects’ implementation
of to_xml (such as ActiveRecord::XmlSerialization.to_xml).
render :xml => Product.find(:all).to_xml
Note that render(:xml => …) and render(:json => …) are new synonyms for
render(:text => …) that change the response’s MIME type appropriately.
————————————————————————————————————————————-

————————————————————————————————————————————-

Grouping
core_ext/array/grouping.rb
• Array#in_groups_of(size, fill_with) groups elements of an array into fixed-size groups:
(1..8).to_a.in_groups_of(3) # => [[1, 2, 3], [4, 5, 6], [7, 8, nil]]
(1..8).to_a.in_groups_of(3, 0) # => [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
(1..8).to_a.in_groups_of(3, false) # => [[1, 2, 3], [4, 5, 6], [7, 8]]

• Array#split splits an array on a value or the result of a block:
(1..8).to_a.split(4) # => [[1, 2, 3], [5, 6, 7, 8]]
(1..8).to_a.split {|i| i == 2} # => [[1], [3, 4, 5, 6, 7, 8]]

————————————————————————————————————————————-

————————————————————————————————————————————-

Option processing

core_ext/array/extract_options.rb

• Array#extract_options! removes and returns the last array item if it is a hash; otherwise,
it returns an empty hash. This supports the common pattern of using a hash as
the last argument to provide keyword arguments to a method:
def example(*args)
options = args.extract_options!
“#{args.inspect} :: #{options.inspect}”
end
example 1 # => “[1] :: {}”
example 1, 2 # => “[1, 2] :: {}”
example 1, 2, :a => 3 # => “[1, 2] :: {:a=>3}”

————————————————————————————————————————————-

————————————————————————————————————————————-
Random selection
core_ext/array/random_access.rb
• Array#rand returns an element selected at random from the array:
(1..10).map{ (1..10).to_a.rand } # => [2, 7, 7, 7, 7, 1, 10, 10, 2, 5]
————————————————————————————————————————————-

Advertisements
Posted in: Rails app, Ruby