SlideShare uma empresa Scribd logo
1 de 21
Baixar para ler offline
Active Support
Core Extensions (2)
ROR lab. DD-1
- The 2nd round -
April 13, 2013
Hyoseong Choi
Ext. to Module
• alias_method_chain
active_support/core_ext/module/
aliasing.rb
• “alias chaining”? ➧ wrapping
http://erniemiller.org/2011/02/03/when-to-use-alias_method_chain/
ActionController::TestCase.class_eval do
  def process_with_stringified_params(...)
    params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
    process_without_stringified_params(action,
params, session, flash, http_method)
  end
  alias_method_chain :process, :stringified_params
end
Ext. to Module
• alias_attribute
active_support/core_ext/module/
aliasing.rb
class User < ActiveRecord::Base
  # let me refer to the email column as "login",
  # possibly meaningful for authentication code
  alias_attribute :login, :email
end
Ext. to Module
• attr_accessor_with_default
active_support/core_ext/module/
attr_accessor_with_default.rb
class Url
  attr_accessor_with_default :port, 80
end
 
Url.new.port # => 80
class User
  attr_accessor :name, :surname
  attr_accessor_with_default(:full_name) do
    [name, surname].compact.join(" ")
  end
end
 
u = User.new
u.name = 'Xavier'
u.surname = 'Noria'
u.full_name # => "Xavier Noria"
not
cached
Ext. to Module
• attr_internal or attr_internal_accessor
active_support/core_ext/module/
attr_internal.rb
# library
class ThirdPartyLibrary::Crawler
  attr_internal :log_level
end
 
# client code
class MyCrawler < ThirdPartyLibrary::Crawler
  attr_accessor :log_level
end
@_log_level
Module.attr_internal_naming_format = “@_%s”
sprintf-like format
Ext. to Module
• attr_internal or attr_internal_accessor
active_support/core_ext/module/
attr_internal.rb
module ActionView
  class Base
    attr_internal :captures
    attr_internal :request, :layout
    attr_internal :controller, :template
  end
end
Ext. to Module
• mattr_accessor
active_support/core_ext/module/
attr_accessors.rb
module ActiveSupport
  module Dependencies
    mattr_accessor :warnings_on_first_load
    mattr_accessor :history
    mattr_accessor :loaded
    mattr_accessor :mechanism
    mattr_accessor :load_paths
    mattr_accessor :load_once_paths
    mattr_accessor :autoloaded_constants
    mattr_accessor :explicitly_unloadable_constants
    mattr_accessor :logger
    mattr_accessor :log_activity
    mattr_accessor :constant_watch_stack
    mattr_accessor :constant_watch_stack_mutex
  end
end
• cattr_accessor
Ext. to Module
• Parents
active_support/core_ext/module/
introspection.rb
•parent
•parent_name
•parents
Ext. to Module
• Parents
active_support/core_ext/module/
introspection.rb
module X
  module Y
    module Z
    end
  end
end
M = X::Y::Z
 
X::Y::Z.parent # => X::Y
M.parent       # => X::Y
• parent
Ext. to Module
• Parents
active_support/core_ext/module/
introspection.rb
• parent_name
module X
  module Y
    module Z
    end
  end
end
M = X::Y::Z
 
X::Y::Z.parent_name # => "X::Y"
M.parent_name       # => "X::Y"
Ext. to Module
• Parents
active_support/core_ext/module/
introspection.rb
• parents
module X
  module Y
    module Z
    end
  end
end
M = X::Y::Z
 
X::Y::Z.parents # => [X::Y, X, Object]
M.parents       # => [X::Y, X, Object]
Ext. to Module
• local_constants
module X
  X1 = 1
  X2 = 2
  module Y
    Y1 = :y1
    X1 = :overrides_X1_above
  end
end
 
X.local_constants    # => ["X2", "X1", "Y"], assumes Ruby 1.8
X::Y.local_constants # => ["X1", "Y1"], assumes Ruby 1.8
active_support/core_ext/module/
introspection.rb
• local_constant_names ⟶ always, strings
as symbols in Ruby 1.9
deprecated!!!
Ext. to Module
• const_defined? /_get /_set
Math.const_defined? "PI" #=> true
IO.const_defined? :SYNC #=> true
IO.const_defined? :SYNC, false #=> false
active_support/core_ext/module/
introspection.rb
Math.const_get(:PI) #=> 3.14159265358979
Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0)
#=> 3.14285714285714
Math::HIGH_SCHOOL_PI - Math::PI
#=> 0.00126448926734968
standard ruby methods
bare constant names
Ext. to Module
• const_defined? /_get /_set
module Foo
class Bar
VAL = 10
end
class Baz < Bar; end
end
Object.const_get 'Foo::Baz::VAL' # => 10
Object.const_get 'Foo::Baz::VAL', false # => NameError
active_support/core_ext/module/
introspection.rb
standard ruby methods
bare constant names
flag for inherit
Ext. to Module
• qualified_const_defined? /_get /_set
module M
  X = 1
end
 
module N
  class C
    include M
  end
end
active_support/core_ext/module/
qualified_const.rb
new extended methods
N.qualified_const_defined?("C::X", false)
N.qualified_const_defined?("C::X", true) 
N.qualified_const_defined?("C::X")       
relative to their receiver
qualified constant names
Ext. to Module
• synchronize
class Counter
  @@mutex = Mutex.new
  attr_reader :value
 
  def initialize
    @value = 0
  end
 
  def incr
    @value += 1 # non-atomic
  end
  synchronize :incr, :with => '@@mutex'
end
active_support/core_ext/module/
synchronization.rb
DEPRECATION WARNING: synchronize
is deprecated and will be
removed from Rails 4.0.
Ext. to Module
• reachable?
module M
end
 
M.reachable? # => true
orphan = Object.send(:remove_const, :M)
 
# The module object is orphan now but it still has a name.
orphan.name # => "M"
 
# You cannot reach it via the constant M because it does not even exist.
orphan.reachable? # => false
 
# Let's define a module called "M" again.
module M
end
 
# The constant M exists now again, and it stores a module
# object called "M", but it is a new instance.
orphan.reachable? # => false
active_support/core_ext/module/
reachable.rb
The constant M exists now,
and it stores a module object called "M"
Ext. to Module
• anonymous?
module M
end
M.name # => "M"
 
N = Module.new
N.name # => "N"
 
Module.new.name # => "" in 1.8, nil in 1.9
M.anonymous? # => false
 
Module.new.anonymous? # => true
m = Object.send(:remove_const, :M)
 
m.reachable? # => false
m.anonymous? # => false
active_support/core_ext/module/
anonymous.rb
Ext. to Module
• delegate
class User < ActiveRecord::Base
  has_one :profile
end
class User < ActiveRecord::Base
  has_one :profile
 
  def name
    profile.name
  end
end
class User < ActiveRecord::Base
  has_one :profile
 
  delegate :name, :to => :profile
end
delegate :name, :age, :address, :twitter, :to => :profile
delegate :name, :to => :profile, :allow_nil => true
delegate :street, :to => :address, :prefix => true
delegate :size, :to => :attachment, :prefix => :avatar
active_support/core_ext/module/
delegation.rb
Ext. to Module
• redefine_method
redefine_method("#{reflection.name}=") do |new_value|
  association = association_instance_get(reflection.name)
 
  if association.nil? || association.target != new_value
    association = association_proxy_class.new(self, reflection)
  end
 
  association.replace(new_value)
  association_instance_set(reflection.name, new_value.nil? ?
nil : association)
end
active_support/core_ext/module/
remove_method.rb
ROR Lab.
감사합니다.

Mais conteúdo relacionado

Mais procurados

Chp3(pointers ref)
Chp3(pointers ref)Chp3(pointers ref)
Chp3(pointers ref)Mohd Effandi
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2Prerna Sharma
 
Reading and writting
Reading and writtingReading and writting
Reading and writtingandreeamolnar
 
Double pointer (pointer to pointer)
Double pointer (pointer to pointer)Double pointer (pointer to pointer)
Double pointer (pointer to pointer)sangrampatil81
 
Programming in C Session 1
Programming in C Session 1Programming in C Session 1
Programming in C Session 1Prerna Sharma
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5thConnex
 
Thumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - JavazThumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - JavazAlexey Remnev
 
Ch6 pointers (latest)
Ch6 pointers (latest)Ch6 pointers (latest)
Ch6 pointers (latest)Hattori Sidek
 
Internet Technology and its Applications
Internet Technology and its ApplicationsInternet Technology and its Applications
Internet Technology and its Applicationsamichoksi
 
PVS-Studio delved into the FreeBSD kernel
PVS-Studio delved into the FreeBSD kernelPVS-Studio delved into the FreeBSD kernel
PVS-Studio delved into the FreeBSD kernelPVS-Studio
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++Ilio Catallo
 

Mais procurados (20)

Pointers
PointersPointers
Pointers
 
Chp3(pointers ref)
Chp3(pointers ref)Chp3(pointers ref)
Chp3(pointers ref)
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
 
Pointers
PointersPointers
Pointers
 
Ch5 array nota
Ch5 array notaCh5 array nota
Ch5 array nota
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Reading and writting
Reading and writtingReading and writting
Reading and writting
 
Double pointer (pointer to pointer)
Double pointer (pointer to pointer)Double pointer (pointer to pointer)
Double pointer (pointer to pointer)
 
Programming in C Session 1
Programming in C Session 1Programming in C Session 1
Programming in C Session 1
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
 
Thumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - JavazThumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - Javaz
 
Structures-2
Structures-2Structures-2
Structures-2
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Python Intro-Functions
Python Intro-FunctionsPython Intro-Functions
Python Intro-Functions
 
JavaFXScript
JavaFXScriptJavaFXScript
JavaFXScript
 
Ch6 pointers (latest)
Ch6 pointers (latest)Ch6 pointers (latest)
Ch6 pointers (latest)
 
Internet Technology and its Applications
Internet Technology and its ApplicationsInternet Technology and its Applications
Internet Technology and its Applications
 
PVS-Studio delved into the FreeBSD kernel
PVS-Studio delved into the FreeBSD kernelPVS-Studio delved into the FreeBSD kernel
PVS-Studio delved into the FreeBSD kernel
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++
 

Destaque

Routing 2, Season 1
Routing 2, Season 1Routing 2, Season 1
Routing 2, Season 1RORLAB
 
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
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)RORLAB
 
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
 
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
 
Presentation on Index Number
Presentation on Index NumberPresentation on Index Number
Presentation on Index NumberAsraf Hossain
 
Chapter 11 index number
Chapter 11  index numberChapter 11  index number
Chapter 11 index numberatiqah ayie
 
Love And Life Sayings
Love And Life SayingsLove And Life Sayings
Love And Life Sayingsjuvie Bravo
 
12 Most Profound Quotes from Facebooks CEO Mark Zuckerberg
12 Most Profound Quotes from Facebooks CEO Mark Zuckerberg12 Most Profound Quotes from Facebooks CEO Mark Zuckerberg
12 Most Profound Quotes from Facebooks CEO Mark ZuckerbergEkaterina Walter
 
Brexit, Trump, referendum: lezioni dalla politica del 2016
Brexit, Trump, referendum: lezioni dalla politica del 2016Brexit, Trump, referendum: lezioni dalla politica del 2016
Brexit, Trump, referendum: lezioni dalla politica del 2016Proforma
 
5 tools for an awesome presentation-By Samid Razzak
5 tools for an awesome presentation-By Samid Razzak5 tools for an awesome presentation-By Samid Razzak
5 tools for an awesome presentation-By Samid RazzakMd. Samid Razzak
 

Destaque (20)

Routing 2, Season 1
Routing 2, Season 1Routing 2, Season 1
Routing 2, Season 1
 
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
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (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
 
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
 
Index number
Index numberIndex number
Index number
 
Presentation on Index Number
Presentation on Index NumberPresentation on Index Number
Presentation on Index Number
 
Index Numbers
Index NumbersIndex Numbers
Index Numbers
 
Happiness
HappinessHappiness
Happiness
 
Chapter 11 index number
Chapter 11  index numberChapter 11  index number
Chapter 11 index number
 
Love And Life Sayings
Love And Life SayingsLove And Life Sayings
Love And Life Sayings
 
Index Number
Index NumberIndex Number
Index Number
 
12 Most Profound Quotes from Facebooks CEO Mark Zuckerberg
12 Most Profound Quotes from Facebooks CEO Mark Zuckerberg12 Most Profound Quotes from Facebooks CEO Mark Zuckerberg
12 Most Profound Quotes from Facebooks CEO Mark Zuckerberg
 
Brexit, Trump, referendum: lezioni dalla politica del 2016
Brexit, Trump, referendum: lezioni dalla politica del 2016Brexit, Trump, referendum: lezioni dalla politica del 2016
Brexit, Trump, referendum: lezioni dalla politica del 2016
 
DNA sequencing
DNA sequencingDNA sequencing
DNA sequencing
 
5 tools for an awesome presentation-By Samid Razzak
5 tools for an awesome presentation-By Samid Razzak5 tools for an awesome presentation-By Samid Razzak
5 tools for an awesome presentation-By Samid Razzak
 
5 Ways To Surprise Your Audience (and keep their attention)
5 Ways To Surprise Your Audience (and keep their attention)5 Ways To Surprise Your Audience (and keep their attention)
5 Ways To Surprise Your Audience (and keep their attention)
 

Semelhante a Active Support Core Extension (2)

Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plusSayed Ahmed
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Sayed Ahmed
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Pythondn
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethodsdreampuf
 
PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2Graham Dumpleton
 
Intermediate SQL with Ecto - LoneStar ElixirConf 2018
Intermediate SQL with Ecto - LoneStar ElixirConf 2018Intermediate SQL with Ecto - LoneStar ElixirConf 2018
Intermediate SQL with Ecto - LoneStar ElixirConf 2018wreckoning
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsSolution4Future
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
Where's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord MigrationsWhere's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord MigrationsEleanor McHugh
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptxAshwini Raut
 
Machine learning on source code
Machine learning on source codeMachine learning on source code
Machine learning on source codesource{d}
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weiboshaokun
 

Semelhante a Active Support Core Extension (2) (20)

Django Good Practices
Django Good PracticesDjango Good Practices
Django Good Practices
 
C#2
C#2C#2
C#2
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plus
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)
 
Intro to Rails 4
Intro to Rails 4Intro to Rails 4
Intro to Rails 4
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2
 
Intermediate SQL with Ecto - LoneStar ElixirConf 2018
Intermediate SQL with Ecto - LoneStar ElixirConf 2018Intermediate SQL with Ecto - LoneStar ElixirConf 2018
Intermediate SQL with Ecto - LoneStar ElixirConf 2018
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
Where's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord MigrationsWhere's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord Migrations
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
 
Python - OOP Programming
Python - OOP ProgrammingPython - OOP Programming
Python - OOP Programming
 
Machine learning on source code
Machine learning on source codeMachine learning on source code
Machine learning on source code
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 

Mais 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
 
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
 
Action Controller Overview, Season 1
Action Controller Overview, Season 1Action Controller Overview, Season 1
Action Controller Overview, Season 1RORLAB
 

Mais 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)
 
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
 
Action Controller Overview, Season 1
Action Controller Overview, Season 1Action Controller Overview, Season 1
Action Controller Overview, Season 1
 

Último

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
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
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
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
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
 
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
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Último (20)

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
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
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
 
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
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
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
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
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
 
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
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 

Active Support Core Extension (2)

  • 1. Active Support Core Extensions (2) ROR lab. DD-1 - The 2nd round - April 13, 2013 Hyoseong Choi
  • 2. Ext. to Module • alias_method_chain active_support/core_ext/module/ aliasing.rb • “alias chaining”? ➧ wrapping http://erniemiller.org/2011/02/03/when-to-use-alias_method_chain/ ActionController::TestCase.class_eval do   def process_with_stringified_params(...)     params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]     process_without_stringified_params(action, params, session, flash, http_method)   end   alias_method_chain :process, :stringified_params end
  • 3. Ext. to Module • alias_attribute active_support/core_ext/module/ aliasing.rb class User < ActiveRecord::Base   # let me refer to the email column as "login",   # possibly meaningful for authentication code   alias_attribute :login, :email end
  • 4. Ext. to Module • attr_accessor_with_default active_support/core_ext/module/ attr_accessor_with_default.rb class Url   attr_accessor_with_default :port, 80 end   Url.new.port # => 80 class User   attr_accessor :name, :surname   attr_accessor_with_default(:full_name) do     [name, surname].compact.join(" ")   end end   u = User.new u.name = 'Xavier' u.surname = 'Noria' u.full_name # => "Xavier Noria" not cached
  • 5. Ext. to Module • attr_internal or attr_internal_accessor active_support/core_ext/module/ attr_internal.rb # library class ThirdPartyLibrary::Crawler   attr_internal :log_level end   # client code class MyCrawler < ThirdPartyLibrary::Crawler   attr_accessor :log_level end @_log_level Module.attr_internal_naming_format = “@_%s” sprintf-like format
  • 6. Ext. to Module • attr_internal or attr_internal_accessor active_support/core_ext/module/ attr_internal.rb module ActionView   class Base     attr_internal :captures     attr_internal :request, :layout     attr_internal :controller, :template   end end
  • 7. Ext. to Module • mattr_accessor active_support/core_ext/module/ attr_accessors.rb module ActiveSupport   module Dependencies     mattr_accessor :warnings_on_first_load     mattr_accessor :history     mattr_accessor :loaded     mattr_accessor :mechanism     mattr_accessor :load_paths     mattr_accessor :load_once_paths     mattr_accessor :autoloaded_constants     mattr_accessor :explicitly_unloadable_constants     mattr_accessor :logger     mattr_accessor :log_activity     mattr_accessor :constant_watch_stack     mattr_accessor :constant_watch_stack_mutex   end end • cattr_accessor
  • 8. Ext. to Module • Parents active_support/core_ext/module/ introspection.rb •parent •parent_name •parents
  • 9. Ext. to Module • Parents active_support/core_ext/module/ introspection.rb module X   module Y     module Z     end   end end M = X::Y::Z   X::Y::Z.parent # => X::Y M.parent       # => X::Y • parent
  • 10. Ext. to Module • Parents active_support/core_ext/module/ introspection.rb • parent_name module X   module Y     module Z     end   end end M = X::Y::Z   X::Y::Z.parent_name # => "X::Y" M.parent_name       # => "X::Y"
  • 11. Ext. to Module • Parents active_support/core_ext/module/ introspection.rb • parents module X   module Y     module Z     end   end end M = X::Y::Z   X::Y::Z.parents # => [X::Y, X, Object] M.parents       # => [X::Y, X, Object]
  • 12. Ext. to Module • local_constants module X   X1 = 1   X2 = 2   module Y     Y1 = :y1     X1 = :overrides_X1_above   end end   X.local_constants    # => ["X2", "X1", "Y"], assumes Ruby 1.8 X::Y.local_constants # => ["X1", "Y1"], assumes Ruby 1.8 active_support/core_ext/module/ introspection.rb • local_constant_names ⟶ always, strings as symbols in Ruby 1.9 deprecated!!!
  • 13. Ext. to Module • const_defined? /_get /_set Math.const_defined? "PI" #=> true IO.const_defined? :SYNC #=> true IO.const_defined? :SYNC, false #=> false active_support/core_ext/module/ introspection.rb Math.const_get(:PI) #=> 3.14159265358979 Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0) #=> 3.14285714285714 Math::HIGH_SCHOOL_PI - Math::PI #=> 0.00126448926734968 standard ruby methods bare constant names
  • 14. Ext. to Module • const_defined? /_get /_set module Foo class Bar VAL = 10 end class Baz < Bar; end end Object.const_get 'Foo::Baz::VAL' # => 10 Object.const_get 'Foo::Baz::VAL', false # => NameError active_support/core_ext/module/ introspection.rb standard ruby methods bare constant names flag for inherit
  • 15. Ext. to Module • qualified_const_defined? /_get /_set module M   X = 1 end   module N   class C     include M   end end active_support/core_ext/module/ qualified_const.rb new extended methods N.qualified_const_defined?("C::X", false) N.qualified_const_defined?("C::X", true)  N.qualified_const_defined?("C::X")        relative to their receiver qualified constant names
  • 16. Ext. to Module • synchronize class Counter   @@mutex = Mutex.new   attr_reader :value     def initialize     @value = 0   end     def incr     @value += 1 # non-atomic   end   synchronize :incr, :with => '@@mutex' end active_support/core_ext/module/ synchronization.rb DEPRECATION WARNING: synchronize is deprecated and will be removed from Rails 4.0.
  • 17. Ext. to Module • reachable? module M end   M.reachable? # => true orphan = Object.send(:remove_const, :M)   # The module object is orphan now but it still has a name. orphan.name # => "M"   # You cannot reach it via the constant M because it does not even exist. orphan.reachable? # => false   # Let's define a module called "M" again. module M end   # The constant M exists now again, and it stores a module # object called "M", but it is a new instance. orphan.reachable? # => false active_support/core_ext/module/ reachable.rb The constant M exists now, and it stores a module object called "M"
  • 18. Ext. to Module • anonymous? module M end M.name # => "M"   N = Module.new N.name # => "N"   Module.new.name # => "" in 1.8, nil in 1.9 M.anonymous? # => false   Module.new.anonymous? # => true m = Object.send(:remove_const, :M)   m.reachable? # => false m.anonymous? # => false active_support/core_ext/module/ anonymous.rb
  • 19. Ext. to Module • delegate class User < ActiveRecord::Base   has_one :profile end class User < ActiveRecord::Base   has_one :profile     def name     profile.name   end end class User < ActiveRecord::Base   has_one :profile     delegate :name, :to => :profile end delegate :name, :age, :address, :twitter, :to => :profile delegate :name, :to => :profile, :allow_nil => true delegate :street, :to => :address, :prefix => true delegate :size, :to => :attachment, :prefix => :avatar active_support/core_ext/module/ delegation.rb
  • 20. Ext. to Module • redefine_method redefine_method("#{reflection.name}=") do |new_value|   association = association_instance_get(reflection.name)     if association.nil? || association.target != new_value     association = association_proxy_class.new(self, reflection)   end     association.replace(new_value)   association_instance_set(reflection.name, new_value.nil? ? nil : association) end active_support/core_ext/module/ remove_method.rb
  • 22.