SlideShare a Scribd company logo
1 of 21
Download to read 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.
감사합니다.

More Related Content

What's hot

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
 

What's hot (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++
 

Viewers also liked

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
 

Viewers also liked (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)
 

Similar to 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
 

Similar to 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
 

More from 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
 

More from 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
 

Recently uploaded

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
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
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
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
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
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
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 

Recently uploaded (20)

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
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
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
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
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
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
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 

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.