SlideShare ist ein Scribd-Unternehmen logo
1 von 26
Downloaden Sie, um offline zu lesen
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.

Weitere ähnliche Inhalte

Was ist angesagt?

あたかも自然言語を書くようにコーディングしてみる
あたかも自然言語を書くようにコーディングしてみるあたかも自然言語を書くようにコーディングしてみる
あたかも自然言語を書くようにコーディングしてみる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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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旻琦 潘
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 

Kürzlich hochgeladen (20)

Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 

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