SlideShare a Scribd company logo
ROR lab. DD-1
   - The 1st round -



Active Support
Core Extensions
     March 16, 2013

     Hyoseong Choi
Active Support

• Ruby on Rails components
 • actionmailer
 • actionpack
 • activerecord
 • activesupport ...
Active Support

• Ruby on Rails components
 • actionmailer
 • actionpack
 • activerecord
 • activesupport ...
Active Support

• Ruby language extensions
• Utility classes
• Other transversal stuff
Core Extensions
  Stand-Alone Active Support
   require 'active_support'


  “blank?” method
  Cherry-picking
  require 'active_support/core_ext/object/blank'


  Grouped Core Extensions
  require 'active_support/core_ext/object'


  All Core Extensions
  require 'active_support/core_ext'


  All Active Support
  require 'active_support/all'
Core Extensions
  Active Support within ROR Application

   Default
   require 'active_support/all'




   Barebone setting with Cherry-pickings
   config.active_support.bare = true
Ext. to All Objects
• blank?
    ‣ nil and false                         0 and 0.0

    ‣ whitespaces : spaces, tabs, newlines
    ‣ empty arrays and hashes                  !
                                            blank
    ‣ empty? true

• present?
                        active_support/core_ext/object/
    ‣ !blank?                      blank.rb
Ext. to All Objects
• presence
  host = config[:host].presence || 'localhost'




                             active_support/core_ext/object/
                                        blank.rb
Ext. to All Objects
• duplicable?
  "".duplicable?     # => true
  false.duplicable?  # => false



 Singletons : nil, false, true, symobls, numbers,
 and class and module objects



                             active_support/core_ext/object/
                                      duplicable.rb
Ext. to All Objects
• try
  def log_info(sql, name, ms)
    if @logger.try(:debug?)
      name = '%s (%.1fms)' % [name || 'SQL', ms]
      @logger.debug(format_log_entry(name, sql.squeeze(' ')))
    end
  end


  @person.try { |p| "#{p.first_name} #{p.last_name}" }



• try!
                          active_support/core_ext/object/try.rb
Ext. to All Objects
• singleton_class
  nil => NilClass
  true => TrueClass
  false => FalseClass




                        active_support/core_ext/kernel/
                              singleton_class.rb
o us
    ym s


             Singleton Class?
  on as
an cl




       •     When you add a method to a specific object, Ruby inserts
             a new anonymous class into the inheritance hierarchy as
             a container to hold these types of methods.



                                                               foobar = [ ]
                                                               def foobar.say
                                                                 “Hello”
                                                               end




      http://www.devalot.com/articles/2008/09/ruby-singleton
o us
    ym s


             Singleton Class?
  on as
an cl




      foobar = Array.new                           module Foo
                                                     def foo
      def foobar.size                                  "Hello World!"
        "Hello World!"                               end
      end                                          end
      foobar.size # => "Hello World!"
      foobar.class # => Array                      foobar = []
      bizbat = Array.new                           foobar.extend(Foo)
      bizbat.size # => 0                           foobar.singleton_methods # => ["foo"]




      foobar = []                                  foobar = []

      class << foobar                              foobar.instance_eval <<EOT
        def foo                                      def foo
          "Hello World!"                               "Hello World!"
        end                                          end
      end                                          EOT

      foobar.singleton_methods # => ["foo"]        foobar.singleton_methods # => ["foo"]




      http://www.devalot.com/articles/2008/09/ruby-singleton
o us
    ym s


             Singleton Class?
  on as
an cl




      • Practical Uses of Singleton Classes
             class Foo
                                                class
               def self.one () 1 end
                                                method
               class << self
                 def two () 2 end               class
               end                              method

               def three () 3 end

               self.singleton_methods # => ["two", "one"]
               self.class             # => Class
               self                   # => Foo
             end




      http://www.devalot.com/articles/2008/09/ruby-singleton
Ext. to All Objects
• class_eval(*args, &block)
 class Proc
   def bind(object)
     block, time = self, Time.now
     object.class_eval do
       method_name = "__bind_#{time.to_i}_#{time.usec}"
       define_method(method_name, &block)
       method = instance_method(method_name)
       remove_method(method_name)
       method
     end.bind(object)
   end
 end



                              active_support/core_ext/kernel/
                                    singleton_class.rb
Ext. to All Objects
    •   acts_like?(duck)           same interface?




      def acts_like_string?
      end



      some_klass.acts_like?(:string)


  or ple
f m
e xa     acts_like_date? (Date class)
      acts_like_time? (Time class)


                                        active_support/core_ext/object/
                                                 acts_likes.rb
Ext. to All Objects
    • to_param(=> to_s)             a value for :id placeholder



     class User
                      overwriting
       def to_param
         "#{id}-#{name.parameterize}"
       end
     end




➧    user_path(@user) # => "/users/357-john-smith"



    => The return value should not be escaped!
                                  active_support/core_ext/object/
                                            to_param.rb
Ext. to All Objects
    •   to_query              a value for :id placeholder



    class User
      def to_param
        "#{id}-#{name.parameterize}"
      end
    end




➧   current_user.to_query('user') # => user=357-john-smith



    => escaped!
                                 active_support/core_ext/object/
                                           to_query.rb
Ext. to All Objects
               es
                    ca

•
                         pe
    to_query                  d



account.to_query('company[name]')
# => "company%5Bname%5D=Johnson+%26+Johnson"


[3.4, -45.6].to_query('sample')
# => "sample%5B%5D=3.4&sample%5B%5D=-45.6"


{:c => 3, :b => 2, :a => 1}.to_query
# => "a=1&b=2&c=3"


{:id => 89, :name => "John Smith"}.to_query('user')
# => "user%5Bid%5D=89&user%5Bname%5D=John+Smith"


         active_support/core_ext/object/
                   to_query.rb
Ext. to All Objects
• with_options
 class Account < ActiveRecord::Base
   has_many :customers, :dependent =>   :destroy
   has_many :products,  :dependent =>   :destroy
   has_many :invoices,  :dependent =>   :destroy
   has_many :expenses,  :dependent =>   :destroy
 end


 class Account < ActiveRecord::Base
   with_options :dependent => :destroy do |assoc|
     assoc.has_many :customers
     assoc.has_many :products
     assoc.has_many :invoices
     assoc.has_many :expenses
   end
 end


          active_support/core_ext/object/
                  with_options.rb
Ext. to All Objects
     • with_options
I18n.with_options locale: user.locale, scope: "newsletter" do |i18n|
  subject i18n.t(:subject)
  body    i18n.t(:body, user_name: user.name)
end
                      interpolation
                           key


# app/views/home/index.html.erb
<%=t 'greet_username', :user => "Bill", :message => "Goodbye" %>
 
# config/locales/en.yml
en:
  greet_username: "%{message}, %{user}!"


             http://guides.rubyonrails.org/i18n.html

                active_support/core_ext/object/
                        with_options.rb
Ext. to All Objects
 • with_options
en:
                     scope of
  activerecord:        i18n
    models:
      user: Dude
    attributes:
      user:
        login: "Handle"
      # will translate User attribute "login" as "Handle"

                                       config/locales/en.yml



          http://guides.rubyonrails.org/i18n.html

             active_support/core_ext/object/
                     with_options.rb
Ext. to All Objects
• Instance Variables
 class C
   def initialize(x, y)
     @x, @y = x, y
   end
 end
  
 C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}




          active_support/core_ext/object/
               instance_variable.rb
E
                      Ext. to All Objects
                      • Silencing Warnings, Streams, and Exceptions
           B OS
   E   R
$V


  silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }
                                                                         si
                                                                            le
                                                                         st nc
                                                                           re in
                       silence_stream(STDOUT) do                              am g
                                                                                s
                         # STDOUT is silent here
                       end
                                                        su ev
                                                          bp en
                                                            ro i
                                                              ce n
                                                                ss
                       quietly { system 'bundle install' }         es
                                                                                    si
                                                                                  ex le
                                                                                    ce nc
                                                                                       pt in
                       # If the user is locked the increment is lost, no big deal.       io g
                       suppress(ActiveRecord::StaleObjectError) do                         ns
                         current_user.increment! :visits
                       end

                                 active_support/core_ext/kernel/
                                          reporting.rb
Ext. to All Objects
• in?
 1.in?(1,2)            #   =>   true
 1.in?([1,2])          #   =>   true
 "lo".in?("hello")     #   =>   true
 25.in?(30..50)        #   =>   false
 1.in?(1)              #   =>   ArgumentError




• include? (array method)
 [1,2].include? 1         # => true
 "hello".include? "lo"    # => true
 (30..50).include? 25     # => false



          active_support/core_ext/object/
                   inclusion.rb
ROR Lab.

More Related Content

What's hot (20)

KEY
あたかも自然言語を書くようにコーディングしてみる
Kazuya Numata
 
KEY
Dsl
phoet
 
PDF
Zope component architechture
Anatoly Bubenkov
 
PPTX
Javascript Common Design Patterns
Pham Huy Tung
 
PDF
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
Nina Zakharenko
 
PDF
Python introduction
Marcelo Araujo
 
PDF
Python for text processing
Xiang Li
 
PDF
AutoIt for the rest of us - handout
Becky Yoose
 
PPTX
Awesomeness of JavaScript…almost
Quinton Sheppard
 
PDF
1st CI&T Lightning Talks: Writing better code with Object Calisthenics
Lucas Arruda
 
KEY
Objective-C & iPhone for .NET Developers
Ben Scheirman
 
KEY
Xtext Eclipse Con
Sven Efftinge
 
PDF
Designing Ruby APIs
Wen-Tien Chang
 
PDF
Slides chapter3part1 ruby-forjavaprogrammers
Giovanni924
 
PDF
JS Level Up: Prototypes
Vernon Kesner
 
PDF
Moose workshop
Ynon Perek
 
PPTX
5 Tips for Better JavaScript
Todd Anglin
 
DOCX
Python Metaclasses
Nikunj Parekh
 
あたかも自然言語を書くようにコーディングしてみる
Kazuya Numata
 
Dsl
phoet
 
Zope component architechture
Anatoly Bubenkov
 
Javascript Common Design Patterns
Pham Huy Tung
 
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
Nina Zakharenko
 
Python introduction
Marcelo Araujo
 
Python for text processing
Xiang Li
 
AutoIt for the rest of us - handout
Becky Yoose
 
Awesomeness of JavaScript…almost
Quinton Sheppard
 
1st CI&T Lightning Talks: Writing better code with Object Calisthenics
Lucas Arruda
 
Objective-C & iPhone for .NET Developers
Ben Scheirman
 
Xtext Eclipse Con
Sven Efftinge
 
Designing Ruby APIs
Wen-Tien Chang
 
Slides chapter3part1 ruby-forjavaprogrammers
Giovanni924
 
JS Level Up: Prototypes
Vernon Kesner
 
Moose workshop
Ynon Perek
 
5 Tips for Better JavaScript
Todd Anglin
 
Python Metaclasses
Nikunj Parekh
 

Viewers also liked (8)

KEY
Routing 2, Season 1
RORLAB
 
PDF
Getting Started with Rails (2)
RORLAB
 
KEY
Getting started with Rails (3), Season 2
RORLAB
 
KEY
ActiveRecord Association (1), Season 2
RORLAB
 
KEY
Active Record Query Interface (1), Season 2
RORLAB
 
PDF
Active Record callbacks and Observers, Season 1
RORLAB
 
KEY
Getting started with Rails (4), Season 2
RORLAB
 
KEY
Active Record Validations, Season 1
RORLAB
 
Routing 2, Season 1
RORLAB
 
Getting Started with Rails (2)
RORLAB
 
Getting started with Rails (3), Season 2
RORLAB
 
ActiveRecord Association (1), Season 2
RORLAB
 
Active Record Query Interface (1), Season 2
RORLAB
 
Active Record callbacks and Observers, Season 1
RORLAB
 
Getting started with Rails (4), Season 2
RORLAB
 
Active Record Validations, Season 1
RORLAB
 
Ad

Similar to Active Support Core Extensions (1) (20)

PDF
Ruby 程式語言入門導覽
Wen-Tien Chang
 
PDF
Ruby object model at the Ruby drink-up of Sophia, January 2013
rivierarb
 
KEY
Refactor like a boss
gsterndale
 
PDF
Ruby 入門 第一次就上手
Wen-Tien Chang
 
KEY
Ruby objects
Reuven Lerner
 
KEY
Module Magic
James Gray
 
KEY
Why I choosed Ruby
Indrit Selimi
 
PPTX
Lightning talk
npalaniuk
 
PPT
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Anton Shemerey
 
PDF
Ruby tricks2
Michał Łomnicki
 
KEY
Rails by example
Angelo van der Sijpt
 
PDF
Ruby on Rails 中級者を目指して - 大場寧子
Yasuko Ohba
 
PDF
Ruby Intro {spection}
Christian KAKESA
 
KEY
An introduction to Ruby
Wes Oldenbeuving
 
PDF
Introduction to Ruby
Ranjith Siji
 
PDF
Ruby on Rails
bryanbibat
 
KEY
Introducing Ruby
James Thompson
 
PDF
Ruby Programming Language
Duda Dornelles
 
PDF
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
Tchelinux
 
PDF
Metaprogramming in Ruby
ConFoo
 
Ruby 程式語言入門導覽
Wen-Tien Chang
 
Ruby object model at the Ruby drink-up of Sophia, January 2013
rivierarb
 
Refactor like a boss
gsterndale
 
Ruby 入門 第一次就上手
Wen-Tien Chang
 
Ruby objects
Reuven Lerner
 
Module Magic
James Gray
 
Why I choosed Ruby
Indrit Selimi
 
Lightning talk
npalaniuk
 
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Anton Shemerey
 
Ruby tricks2
Michał Łomnicki
 
Rails by example
Angelo van der Sijpt
 
Ruby on Rails 中級者を目指して - 大場寧子
Yasuko Ohba
 
Ruby Intro {spection}
Christian KAKESA
 
An introduction to Ruby
Wes Oldenbeuving
 
Introduction to Ruby
Ranjith Siji
 
Ruby on Rails
bryanbibat
 
Introducing Ruby
James Thompson
 
Ruby Programming Language
Duda Dornelles
 
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
Tchelinux
 
Metaprogramming in Ruby
ConFoo
 
Ad

More from RORLAB (20)

PDF
Getting Started with Rails (4)
RORLAB
 
PDF
Getting Started with Rails (3)
RORLAB
 
PDF
Getting Started with Rails (1)
RORLAB
 
PDF
Self join in active record association
RORLAB
 
PDF
Asset Pipeline in Ruby on Rails
RORLAB
 
PDF
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
RORLAB
 
PDF
Active Support Core Extension (3)
RORLAB
 
PDF
Active Support Core Extension (2)
RORLAB
 
PDF
Action Controller Overview, Season 2
RORLAB
 
PDF
Action View Form Helpers - 2, Season 2
RORLAB
 
PDF
Action View Form Helpers - 1, Season 2
RORLAB
 
PDF
Layouts and Rendering in Rails, Season 2
RORLAB
 
PDF
ActiveRecord Query Interface (2), Season 2
RORLAB
 
KEY
Active Record Association (2), Season 2
RORLAB
 
KEY
ActiveRecord Callbacks & Observers, Season 2
RORLAB
 
KEY
ActiveRecord Validations, Season 2
RORLAB
 
KEY
Rails Database Migration, Season 2
RORLAB
 
KEY
Getting started with Rails (2), Season 2
RORLAB
 
KEY
Getting started with Rails (1), Season 2
RORLAB
 
KEY
Routing 1, Season 1
RORLAB
 
Getting Started with Rails (4)
RORLAB
 
Getting Started with Rails (3)
RORLAB
 
Getting Started with Rails (1)
RORLAB
 
Self join in active record association
RORLAB
 
Asset Pipeline in Ruby on Rails
RORLAB
 
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
RORLAB
 
Active Support Core Extension (3)
RORLAB
 
Active Support Core Extension (2)
RORLAB
 
Action Controller Overview, Season 2
RORLAB
 
Action View Form Helpers - 2, Season 2
RORLAB
 
Action View Form Helpers - 1, Season 2
RORLAB
 
Layouts and Rendering in Rails, Season 2
RORLAB
 
ActiveRecord Query Interface (2), Season 2
RORLAB
 
Active Record Association (2), Season 2
RORLAB
 
ActiveRecord Callbacks & Observers, Season 2
RORLAB
 
ActiveRecord Validations, Season 2
RORLAB
 
Rails Database Migration, Season 2
RORLAB
 
Getting started with Rails (2), Season 2
RORLAB
 
Getting started with Rails (1), Season 2
RORLAB
 
Routing 1, Season 1
RORLAB
 

Recently uploaded (20)

PPTX
Digital Professionalism and Interpersonal Competence
rutvikgediya1
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PPTX
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
PPTX
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
PPTX
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Rules and Regulations of Madhya Pradesh Library Part-I
SantoshKumarKori2
 
PPTX
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
PPTX
Translation_ Definition, Scope & Historical Development.pptx
DhatriParmar
 
PPTX
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
PPTX
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
PDF
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
DOCX
pgdei-UNIT -V Neurological Disorders & developmental disabilities
JELLA VISHNU DURGA PRASAD
 
PPTX
PROTIEN ENERGY MALNUTRITION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
PPTX
Introduction to Probability(basic) .pptx
purohitanuj034
 
PPTX
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
PPTX
YSPH VMOC Special Report - Measles Outbreak Southwest US 7-20-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
PPTX
I INCLUDED THIS TOPIC IS INTELLIGENCE DEFINITION, MEANING, INDIVIDUAL DIFFERE...
parmarjuli1412
 
PPTX
K-Circle-Weekly-Quiz12121212-May2025.pptx
Pankaj Rodey
 
PDF
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
Digital Professionalism and Interpersonal Competence
rutvikgediya1
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
Rules and Regulations of Madhya Pradesh Library Part-I
SantoshKumarKori2
 
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
Translation_ Definition, Scope & Historical Development.pptx
DhatriParmar
 
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
pgdei-UNIT -V Neurological Disorders & developmental disabilities
JELLA VISHNU DURGA PRASAD
 
PROTIEN ENERGY MALNUTRITION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
Introduction to Probability(basic) .pptx
purohitanuj034
 
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 7-20-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
I INCLUDED THIS TOPIC IS INTELLIGENCE DEFINITION, MEANING, INDIVIDUAL DIFFERE...
parmarjuli1412
 
K-Circle-Weekly-Quiz12121212-May2025.pptx
Pankaj Rodey
 
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 

Active Support Core Extensions (1)

  • 1. ROR lab. DD-1 - The 1st round - Active Support Core Extensions March 16, 2013 Hyoseong Choi
  • 2. Active Support • Ruby on Rails components • actionmailer • actionpack • activerecord • activesupport ...
  • 3. Active Support • Ruby on Rails components • actionmailer • actionpack • activerecord • activesupport ...
  • 4. Active Support • Ruby language extensions • Utility classes • Other transversal stuff
  • 5. Core Extensions Stand-Alone Active Support require 'active_support' “blank?” method Cherry-picking require 'active_support/core_ext/object/blank' Grouped Core Extensions require 'active_support/core_ext/object' All Core Extensions require 'active_support/core_ext' All Active Support require 'active_support/all'
  • 6. Core Extensions Active Support within ROR Application Default require 'active_support/all' Barebone setting with Cherry-pickings config.active_support.bare = true
  • 7. Ext. to All Objects • blank? ‣ nil and false 0 and 0.0 ‣ whitespaces : spaces, tabs, newlines ‣ empty arrays and hashes ! blank ‣ empty? true • present? active_support/core_ext/object/ ‣ !blank? blank.rb
  • 8. Ext. to All Objects • presence host = config[:host].presence || 'localhost' active_support/core_ext/object/ blank.rb
  • 9. Ext. to All Objects • duplicable? "".duplicable?     # => true false.duplicable?  # => false Singletons : nil, false, true, symobls, numbers, and class and module objects active_support/core_ext/object/ duplicable.rb
  • 10. Ext. to All Objects • try def log_info(sql, name, ms)   if @logger.try(:debug?)     name = '%s (%.1fms)' % [name || 'SQL', ms]     @logger.debug(format_log_entry(name, sql.squeeze(' ')))   end end @person.try { |p| "#{p.first_name} #{p.last_name}" } • try! active_support/core_ext/object/try.rb
  • 11. Ext. to All Objects • singleton_class nil => NilClass true => TrueClass false => FalseClass active_support/core_ext/kernel/ singleton_class.rb
  • 12. o us ym s Singleton Class? on as an cl • When you add a method to a specific object, Ruby inserts a new anonymous class into the inheritance hierarchy as a container to hold these types of methods. foobar = [ ] def foobar.say “Hello” end http://www.devalot.com/articles/2008/09/ruby-singleton
  • 13. o us ym s Singleton Class? on as an cl foobar = Array.new module Foo def foo def foobar.size "Hello World!" "Hello World!" end end end foobar.size # => "Hello World!" foobar.class # => Array foobar = [] bizbat = Array.new foobar.extend(Foo) bizbat.size # => 0 foobar.singleton_methods # => ["foo"] foobar = [] foobar = [] class << foobar foobar.instance_eval <<EOT def foo def foo "Hello World!" "Hello World!" end end end EOT foobar.singleton_methods # => ["foo"] foobar.singleton_methods # => ["foo"] http://www.devalot.com/articles/2008/09/ruby-singleton
  • 14. o us ym s Singleton Class? on as an cl • Practical Uses of Singleton Classes class Foo class def self.one () 1 end method class << self def two () 2 end class end method def three () 3 end self.singleton_methods # => ["two", "one"] self.class # => Class self # => Foo end http://www.devalot.com/articles/2008/09/ruby-singleton
  • 15. Ext. to All Objects • class_eval(*args, &block) class Proc   def bind(object)     block, time = self, Time.now     object.class_eval do       method_name = "__bind_#{time.to_i}_#{time.usec}"       define_method(method_name, &block)       method = instance_method(method_name)       remove_method(method_name)       method     end.bind(object)   end end active_support/core_ext/kernel/ singleton_class.rb
  • 16. Ext. to All Objects • acts_like?(duck) same interface? def acts_like_string? end some_klass.acts_like?(:string) or ple f m e xa acts_like_date? (Date class) acts_like_time? (Time class) active_support/core_ext/object/ acts_likes.rb
  • 17. Ext. to All Objects • to_param(=> to_s) a value for :id placeholder class User overwriting   def to_param     "#{id}-#{name.parameterize}"   end end ➧ user_path(@user) # => "/users/357-john-smith" => The return value should not be escaped! active_support/core_ext/object/ to_param.rb
  • 18. Ext. to All Objects • to_query a value for :id placeholder class User   def to_param     "#{id}-#{name.parameterize}"   end end ➧ current_user.to_query('user') # => user=357-john-smith => escaped! active_support/core_ext/object/ to_query.rb
  • 19. Ext. to All Objects es ca • pe to_query d account.to_query('company[name]') # => "company%5Bname%5D=Johnson+%26+Johnson" [3.4, -45.6].to_query('sample') # => "sample%5B%5D=3.4&sample%5B%5D=-45.6" {:c => 3, :b => 2, :a => 1}.to_query # => "a=1&b=2&c=3" {:id => 89, :name => "John Smith"}.to_query('user') # => "user%5Bid%5D=89&user%5Bname%5D=John+Smith" active_support/core_ext/object/ to_query.rb
  • 20. Ext. to All Objects • with_options class Account < ActiveRecord::Base   has_many :customers, :dependent => :destroy   has_many :products,  :dependent => :destroy   has_many :invoices,  :dependent => :destroy   has_many :expenses,  :dependent => :destroy end class Account < ActiveRecord::Base   with_options :dependent => :destroy do |assoc|     assoc.has_many :customers     assoc.has_many :products     assoc.has_many :invoices     assoc.has_many :expenses   end end active_support/core_ext/object/ with_options.rb
  • 21. Ext. to All Objects • with_options I18n.with_options locale: user.locale, scope: "newsletter" do |i18n|   subject i18n.t(:subject)   body    i18n.t(:body, user_name: user.name) end interpolation key # app/views/home/index.html.erb <%=t 'greet_username', :user => "Bill", :message => "Goodbye" %>   # config/locales/en.yml en:   greet_username: "%{message}, %{user}!" http://guides.rubyonrails.org/i18n.html active_support/core_ext/object/ with_options.rb
  • 22. Ext. to All Objects • with_options en: scope of   activerecord: i18n     models:       user: Dude     attributes:       user:         login: "Handle"       # will translate User attribute "login" as "Handle" config/locales/en.yml http://guides.rubyonrails.org/i18n.html active_support/core_ext/object/ with_options.rb
  • 23. Ext. to All Objects • Instance Variables class C   def initialize(x, y)     @x, @y = x, y   end end   C.new(0, 1).instance_values # => {"x" => 0, "y" => 1} active_support/core_ext/object/ instance_variable.rb
  • 24. E Ext. to All Objects • Silencing Warnings, Streams, and Exceptions B OS E R $V silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger } si le st nc re in silence_stream(STDOUT) do am g s   # STDOUT is silent here end su ev bp en ro i ce n ss quietly { system 'bundle install' } es si ex le ce nc pt in # If the user is locked the increment is lost, no big deal. io g suppress(ActiveRecord::StaleObjectError) do ns   current_user.increment! :visits end active_support/core_ext/kernel/ reporting.rb
  • 25. Ext. to All Objects • in? 1.in?(1,2)          # => true 1.in?([1,2])        # => true "lo".in?("hello")   # => true 25.in?(30..50)      # => false 1.in?(1)            # => ArgumentError • include? (array method) [1,2].include? 1         # => true "hello".include? "lo"    # => true (30..50).include? 25     # => false active_support/core_ext/object/ inclusion.rb