SlideShare une entreprise Scribd logo
1  sur  26
Télécharger pour lire hors ligne
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.

Contenu connexe

Tendances

あたかも自然言語を書くようにコーディングしてみる
あたかも自然言語を書くようにコーディングしてみるあたかも自然言語を書くようにコーディングしてみる
あたかも自然言語を書くようにコーディングしてみるKazuya Numata
 
Zope component architechture
Zope component architechtureZope component architechture
Zope component architechtureAnatoly Bubenkov
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design PatternsPham Huy Tung
 
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina ZakharenkoElegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina ZakharenkoNina Zakharenko
 
Python for text processing
Python for text processingPython for text processing
Python for text processingXiang Li
 
AutoIt for the rest of us - handout
AutoIt for the rest of us - handoutAutoIt for the rest of us - handout
AutoIt for the rest of us - handoutBecky Yoose
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almostQuinton Sheppard
 
1st CI&T Lightning Talks: Writing better code with Object Calisthenics
1st CI&T Lightning Talks: Writing better code with Object Calisthenics1st CI&T Lightning Talks: Writing better code with Object Calisthenics
1st CI&T Lightning Talks: Writing better code with Object CalisthenicsLucas Arruda
 
Objective-C & iPhone for .NET Developers
Objective-C & iPhone for .NET DevelopersObjective-C & iPhone for .NET Developers
Objective-C & iPhone for .NET DevelopersBen Scheirman
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersGiovanni924
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: PrototypesVernon Kesner
 
Moose workshop
Moose workshopMoose workshop
Moose workshopYnon Perek
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScriptTodd Anglin
 

Tendances (20)

あたかも自然言語を書くようにコーディングしてみる
あたかも自然言語を書くようにコーディングしてみるあたかも自然言語を書くようにコーディングしてみる
あたかも自然言語を書くようにコーディングしてみる
 
Dsl
DslDsl
Dsl
 
Zope component architechture
Zope component architechtureZope component architechture
Zope component architechture
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina ZakharenkoElegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
 
Python introduction
Python introductionPython introduction
Python introduction
 
Python for text processing
Python for text processingPython for text processing
Python for text processing
 
AutoIt for the rest of us - handout
AutoIt for the rest of us - handoutAutoIt for the rest of us - handout
AutoIt for the rest of us - handout
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
1st CI&T Lightning Talks: Writing better code with Object Calisthenics
1st CI&T Lightning Talks: Writing better code with Object Calisthenics1st CI&T Lightning Talks: Writing better code with Object Calisthenics
1st CI&T Lightning Talks: Writing better code with Object Calisthenics
 
Objective-C & iPhone for .NET Developers
Objective-C & iPhone for .NET DevelopersObjective-C & iPhone for .NET Developers
Objective-C & iPhone for .NET Developers
 
Xtext Eclipse Con
Xtext Eclipse ConXtext Eclipse Con
Xtext Eclipse Con
 
Designing Ruby APIs
Designing Ruby APIsDesigning Ruby APIs
Designing Ruby APIs
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
 
Python classes objects
Python classes objectsPython classes objects
Python classes objects
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: Prototypes
 
Moose
MooseMoose
Moose
 
Moose workshop
Moose workshopMoose workshop
Moose workshop
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
Python Metaclasses
Python MetaclassesPython Metaclasses
Python Metaclasses
 

En vedette

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

En vedette (8)

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

Similaire à Active Support Core Extensions (1)

Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosEdgar Suarez
 
Ruby 2: some new things
Ruby 2: some new thingsRuby 2: some new things
Ruby 2: some new thingsDavid Black
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Coxlachie
 
Linux Shell Scripting Craftsmanship
Linux Shell Scripting CraftsmanshipLinux Shell Scripting Craftsmanship
Linux Shell Scripting Craftsmanshipbokonen
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Henry S
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)mircodotta
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma IntroduçãoÍgor Bonadio
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Wen-Tien Chang
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Tudor Dragan
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentationManav Prasad
 
Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?Mario Camou Riveroll
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Railselliando dias
 
Ruby, muito mais que reflexivo
Ruby, muito mais que reflexivoRuby, muito mais que reflexivo
Ruby, muito mais que reflexivoFabio Kung
 
Metaprogramming + Ds Ls
Metaprogramming + Ds LsMetaprogramming + Ds Ls
Metaprogramming + Ds LsArrrrCamp
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends旻琦 潘
 

Similaire à Active Support Core Extensions (1) (20)

Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
Ruby 2: some new things
Ruby 2: some new thingsRuby 2: some new things
Ruby 2: some new things
 
Ruby tricks2
Ruby tricks2Ruby tricks2
Ruby tricks2
 
Ruby
RubyRuby
Ruby
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
 
Language supports it
Language supports itLanguage supports it
Language supports it
 
Linux Shell Scripting Craftsmanship
Linux Shell Scripting CraftsmanshipLinux Shell Scripting Craftsmanship
Linux Shell Scripting Craftsmanship
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma Introdução
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
 
Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
 
Ruby, muito mais que reflexivo
Ruby, muito mais que reflexivoRuby, muito mais que reflexivo
Ruby, muito mais que reflexivo
 
Metaprogramming + Ds Ls
Metaprogramming + Ds LsMetaprogramming + Ds Ls
Metaprogramming + Ds Ls
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 

Plus de RORLAB

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

Plus de RORLAB (20)

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

Dernier

BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 

Dernier (20)

BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 

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