Active Support

Introduction

Active Support is a set of libraries that is used by all Rails components. It extends several core Ruby classes in useful ways.

blank? and present?


puts [ ].blank? #=> true
puts { 1 => 2}.blank? #=> false
puts " cat ".blank? #=> false
puts "".blank? #=> true
puts " ".blank? #=> true
puts nil.blank? #=> true

# present? is the opposite of blank?
puts nil.present? #=> false

to_xml, to_yaml, and to_json


user = User.find(1)
# Those methods are also available on Struct objects
puts user.to_xml
puts user.to_yaml
puts user.to_json # Creates a JavaScript hash

Hash.from_xml(xml_string) # => a Hash object

Symbol#to_proc


# Usually you write a map block like this
post_ids = posts.map { |post| post.id }

# But Rails implements Symbol#to_proc to provide this shortcut:
post_ids = posts.map(&:id)

Object#with_options


map.connect "/shop/summary" , :controller => "store",
  :action => "summary" 
map.connect "/titles/buy/:id" , :controller => "store",
  :action => "add_to_cart" 
  
map.with_options(:controller => "store") do |store_map|
  store_map.connect "/shop/summary", :action => "summary" 
  store_map.connect "/titles/buy/:id", :action => "add_to_cart" 
end

Enumerations


groups = posts.group_by {|post| post.author_id} #=> Hash with author ids as keys

us_states = State.find(:all) 
state_lookup = us_states.index_by {|state| state.short_name} #=> Hash with short name as keys

total_orders = Order.find(:all).sum {|order| order.value } 

total_orders = Order.find(:all).sum(&:value)

Enumerable#each_with_object


%w(foo bar).inject({}) { |str, hsh| hsh[str] = str.upcase; hsh } #=> {'foo' => 'FOO', 'bar' => 'BAR'}
%w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase } #=> {'foo' => 'FOO', 'bar' => 'BAR'}

# NOTE: does not work with immutable objects such as numbers
(1..5).each_with_object(1) { |value, memo| memo *= value } # => 1
(1..5).inject(1) { |value, memo| memo *= value; memo } # => 120

Strings


string = "Ruby on Rails" 
puts string.at(2) #=> 'b'
pust string.from(5) #=> 'on Rails'
puts string.to(3) #=> 'Ruby'
puts string.first(4) #=> 'Ruby'
puts string.last(4) #=> 'ails'
puts string.starts_with?("R") #=> true
puts string.ends_with?("Perl") #=> false
count = Hash.new(0) 
string.each_char {|ch| count[ch] += 1} 
"person".pluralize #=> people
"people".singularize #=> person
"first_name".humanize #=> First Name
"ruby on rails".titleize #=> Ruby On Rails

Numbers


20.bytes #=> 20
20.megabytes #=> 20971520

20.seconds
20.hours
20.months
20.years

20.minutes.ago
20.weeks.from_now
20.minutes.until("2007-12-01 12:00".to_time)

Time and Date


time = Time.parse("2007-01-01 13:00")
time.at_beginning_of_day
time.at_beginning_of_week
time.at_beginning_of_month

Hashes

UTF8


"åäö".size #=> 6

"åäö".chars.size #=> 3

"åäö".upcase #=> "åäö" 

"åäö".chars.upcase.inspect #=> <ActiveSupport::Multibyte::Chars:0x33589c0 @string="ÅÄÖ">

"åäö".chars.upcase.to_s #=> "ÅÄÖ"