Ruby on Rails 3 Active Support & Help Method

Active Support Code

Adding Active Support Features

# Adding Active Support functions in active_support/core_ext/object/blank.rb
# Supporting the blank? extension for all Objects
require 'active_support/core_ext/object/blank'

# Load all extensions available to Object
require 'active_support/core_ext/object'

Loading all core extensions

require 'active_support/core_ext'

Loading all active support

require 'active_support/all'

Rails Extension on Ruby Object

Rails Object Extension Summary Description
blank? nil, false, whitespace string, empty array, empty hash. Note 0 is not blank?
present? !blank?
presence Return the object or nil if blank?
duplicable? Is this a singleton object?
obj1.try(:m1) Return obj1.m1 if defined else nil
singleton_class Return the singleton class
class_eval Evaluate code block
class1.acts_like?(:string) Check if it provides same interface as String
to_param Return a query string or URL representation of the object: default to to_s
to_query Return a query string representation
instance_variable_names Return all instance variable name as string
instance_values Return instance name as string and it's value in a Hash
silence_warnings { code block } Silence a code block warnings
enable_warnings { code block } Enable a code block warnings
suppress(SomeError) do ... end Capture the exceptions and return silently
require_library_or_gem('mysql2') Try load it as a library. If failed, loaded it as gems

with_options example

A shortcut to make multiple method calls that share the same options

To simplify calls that shared the same options

class Client < ActiveRecord::Base
  has_many :contacts, :dependent => :destroy
  has_many :vendors, :dependent => :destroy
end

Use with_options

 class Client < ActiveRecord::Base
  with_options :dependent => :destroy do |o|
    o.has_many :contacts
    o.has_many :vendors
   end
end

copy_instance_variables_from

Copy d2 to d1 with the exception of variables listed in the second parameter

class MyCopy
  def initialize(a, b)
    @a, @b = a, b
  end
 end

d1 = MyCopy.new(0, 1)
d2 = MyCopy.new(2, 3)

# Exclude the copy of @y
d1.copy_instance_variables_from(d2, [:@y])

Rails Extension on Ruby Module

Rails Module Extension Summary Description
alias_method_chain Provide method chaining alias
alias_attribute Create attribut alias
attr_accessor_with_default Extend attr_accessor with a default value
attr_internal Ruby attribute avoiding name collision
mattr_accessor Ruby cattr_* extension avoiding name collision
parent Parent modules
parent_name Parent modules text string
parents Return parents in an array
local_constants Return all local constants in an array
synchronize Declare a method to be synchronized
reachable? Whether a named module is reachable
anonymous? Whether a module is anonymous
instance_method_names Return instance method names as string
method_names Return method names as string
redefine_method Redefine a method even if it exists

delegate

Declare method delegation:

Delegate the name, address method call to the profile object's method of the same name

class Account < ActiveRecord::Base
  has_one :profile
end

class Account < ActiveRecord::Base
  has_one :profile

  delegate :name, :address :to => :profile
end

Return nil if the delegated method is not found

delegate :name, :to => :profile, :allow_nil => true

Delegate to the object's class

delegate :name, :to => 'self.class'

Delegate to Rails constant

delegate :configure, :to => :Rails

Turn on prefix, the target method will be vendor_name

delegate :name, :to => :vendor, :prefix => true

Rails Extensions to Ruby Class

Rails Module Extension Summary Description
class_attribute Declares class attributes
cattr_reader, cattr_writer, and cattr_accessor attr_ accessor equivalent for classes
class_inheritable_reader, class_inheritable_writer class_inheritable_accessor Class Inheritable Attributes
subclasses Return subclasses
descendants Return class descendants

Rails Extensions to Ruby String

Rails Module Extension Summary Description
html_safe Assert s string is HTML safe. Un-safe string will not be changed by calling html_safe. But append an un-safe string to a safe string will automatic escape the appended string
html_safe? Is the string safe
raw Do not make String safe in a Rails view
squish Trim spaces and additional space
truncate Truncate string and add optional ellipsis at the end
% string Key based substitution
starts_with? and ends_with? Starts with or end with a string
strip_heredoc Strips indentation in heredocs
at Return character at position
from Return string from
to Return string to
first Access string with first element having index = 1
last Access string from the end
pluralize Pluralize a word
singularize Singularize a word
camelize Camelize a phase
underscore Underscore a phase
titleize Titleize a phase
dasherize Dasherize a phase
demodulize Return rightmost module name
parameterize Return pretty URL
tableize Underscore followed by pluralize
classify Inverse of tableize
constantize Resolve constant expression
humanize Make phase more readable
foreign_key Convert phase to a foreign key format
ord ASCII value of character
getbyte Get first byte character
to_date, to_time, to_datetime convert string to String date format

Rails extension to Numeric Object

Rails Module Extension Summary Description
bytes, kilobytes, megabytes, gigabytes, terabytes, petabytes, exabytes 1.kilobytes = 1024
multiple_of? Whether it is a multiply
ordinalize Ordinalize a string like 1 => 1st
round round a string to certain significant figure

Rails extension to Enumerable

Rails Module Extension Summary Description
group_by Return an ordered hash
sum Sum of the enumerable
each_with_object Similar to the inject method of a collection class
index_by Generate a hash index by the key provided
many? Has more than 1
exclude? Not contain

Rails extension to Array

Rails Module Extension Summary Description
to Return sub-array up to
from Return sub-array from
sample Random access
extract_options! Extract last parameter as a Hash
to_sentence Convert to sentence
to_formatted_s Return a string in different format like one for Active Record
to_xml Return a XML
wrap Wrap argument into an array
in_groups_of, in_groups Group into sub-groups of array
split Split a array into sub-groups of array by application logic

Rails extension to Hash

Rails Module Extension Summary Description
to_xml Return a string in XML format
reverse_merge, reverse_merge! Merge 2 hashes. In key collision, the one in the method parameter wins
deep_merge, deep_merge! Merge 2 hashes. In key collision, merge the results and share the same key
diff Difference of 2 hashes
except, except! Return hash pair with certain keys
stringify_keys, stringify_keys! Turn the keys into string
symbolize_keys, symbolize_keys! Turn the keys into symbol
assert_valid_keys Assert if the hash has only keys contained in the parameter list
slice, slice! Slice a hash

Rails extension to Regexp

Rails Module Extension Summary Description
multiline? Allow expression to contain '.' to match a new line

Rails extension to Range

Rails Module Extension Summary Description
to_s To string in different format
step Make it invokable in a block
include? Extend Range#include? to include whether a range is within another range
overlaps? Check of 2 ranges are overlapping

Rails extension to Range

Rails Module Extension Summary Description
bind bind a method

Rails extension to Date

Rails Module Extension Summary Description
current Time in current timezone
prev_year, next_year Year manipulation
prev_month, next_month month manipulation
beginning_of_week, end_of_week Begin or end of week
next_week A day in next week
beginning_of_month, end_of_month Begin or end of month
beginning_of_quarter, end_of_quarter Begin or end of quarter
years_ago, years_since nth year ago or after
months_ago, months_since Month ago or since
advance Move forward or backward in days
change Change year, month or day
1.day, 3.hours, 1.week Add to a time
beginning_of_day, end_of_day timestamp of the begin or end of a day
ago, since nth seconds before or after

Rails extension to DateTime

Rails Module Extension Summary Description
Inherited all methods in Date  
seconds_since_midnight Number of seconds since mid-night
utc UTC time
utc? Is UTC timezone
advance Advance by year, month, day

Rails extension to Time

Rails Module Extension Summary Description
Inherited all methods in DateTime  

Rails extension to File

Rails Module Extension Summary Description
atomic_write Other reader cannot read it until the write is fully completed

Rails extension to Logger

Rails Module Extension Summary Description
around_[level] Around method to logger
silence Silence a code block logging at a specific level
datetime_format Modify the datetime format output

Rails extension to NameError

Rails Module Extension Summary Description
missing_name? Check if exception is caused by missing name

Rails extension to LoadError

Rails Module Extension Summary Description
is_missing? Is the exception raised because of certain file missing in Loading

Ruby on Rails Helper Method

Create a helper method

app/helpers/accounts_helper.rb
module AccountsHelper

   def echo
      "Welcome"
   end

end

Using helper method

In a View
  <%= echo %>
In a Controller
include AccountsHelper

class AccountsController < ApplicationController
  def index
    echo
...

To use "h", "html_escape", "u", "url_encode" methods in a controller

Controller
require "erb"
include ERB::Util

class AccountsController < ApplicationController
  def index
       result = h params[:something]

To define a helper method available to the whole application, add the method in

app/helpers/application_helper.rb

Out of the box Ruby on Rails Helper Classes

ActiveRecordHelper
AssetTagHelper
AtomFeedHelper and AtomFeedHelper::AtomFeedBuilder
BenchmarkHelper, CacheHelper, and CaptureHelper
DateHelper
DebugHelper
FormHelper, FormTagHelper, and FormOptionsHelper
JavaScriptHelper
NumberHelper
PrototypeHelper
RecordIdentificationHelper
SanitizeHelper
ScriptaculousHelper
TagHelper
TextHelper
UrlHelper

To use it in a controller

include ActionView::Helpers::UrlHelper
include ActionView::Helpers::TextHelper