SlideShare a Scribd company logo
1 of 18
Goal: to grok this code
class Post < ActiveRecord::Base <= class extension mixin
 belongs_to :user               <= macro
end

my_post = Post.new
my_post.name = 'Chile L‘          <= employs #method_missing
my_post.subject = 'traveling in thailand'
my_post.content = 'sometimes you can almost not tell the
difference'
my_post.save!
Coming from a compiled
language, runtime execution is
  foreign, all code is executed
               code

    Post.respond_to? Name


      Ruby is a dynamic language
Classes are also like namespaces
               too.
class MyClass

 puts ‘Hello World’

end

# => Hello World
Eigenclasses
Singleton method variations on
     the MyClass instance
  class MyClass
   def MyClass.my_method; end
   def self.my_method; end

   class << self
    def my_method; end
   end
  end
class << Object
 puts self
 def my_method                     Different
  puts ‘hi’
 end
end

class Object           class << Object is adding methods to the eigenclass of Object.
                       This method is now available to all objects as if it were a class
 def self.meth2
  puts self            method.
  puts ‘there’
 end
                       However, opening the Object class and adding methods to self
 class << self         shows the current object is the instance Foo.
  def meth3
    puts self
    puts ‘hahaha’
  end
 end
end
Foo = Class.new
Foo.my_method
Foo.meth2
Foo.meth3
# => #<Class:Object>
# => hi
# => Foo
# => there
# => Foo
# => hahaha
Including the module in the Eigenclass of
     class C to create class methods
   module M
    def my_method
     puts ‘hi’
    end
   end

   class C
    class << self
     include M
    end
   end

   C.my_method      # => hi
Using extend to add class methods to C
      module M
       def my_method
         puts ‘hi’
       end
      end
      class C
       extend M
      end

      C.my_method      # => hi
Class methods are singletons of
          the class object, that means they
                 are in the eigenclass
class C             Self, therefore the current object, is
 puts self          changed by opening up the
 class << self      eigenclass
   puts self
   def my_method
    puts ‘hi’
   end
 end
end
C.my_method # => C
               # => #<Class:C>
               # => hi
Examining self…

class Foo           Self, the current object, is changed
 puts self          by opening up the eigenclass and
 class << self      we are now adding my_method to
   puts self        the Foo instance, but this is
   def my_method    equivalent to Foo.my_method
    puts ‘hi’
   end
 end
end
Foo.my_method # => Foo
                 # => #<Class:Foo>
                 # => hi
Hook methods or
   callbacks
Hooking

Module#included exists solely
as a callback and the default
implementation is empty.
Hook methods - Module#included
  module Mod1
   class << self
    def included(othermod)
      puts "Mod1 was mixed into #{othermod}"
    end
   end
  end

  class MyClass
   include Mod1
  end
  # => Mod1 was mixed into MyClass
Hook methods - Module#include
(must call super if you override, to actually include
                     the module)
    module Mod1; end
    module Mod2; end

    class MyClass
     def self.include(*modules)
      puts “#{modules} included”
      super
     end
     include Mod1
     include Mod2
    end
    # => [Mod1] included
    # => [Mod2] included
Putting stuff together…
module Associations                     This is obviously very dumbed down, but
                                         now we can start to see some things in
  def self.included(base)                action.
   base.extend(ClassMethods)
  end                                    We have defined the module
                                         Associations which includes a submodule
  module ClassMethods                    ClassMethods which will hold class
    def belongs_to                       methods.
     “I am in the ClassMethods module”
    end                                Overriding included now acts on the
  end                                  including class which is base in this case.
 end                                   This class is sometimes called the
                                       inclusor. The extend method adds the
 class Base                            ClassMethods to the inclusor’s
  include Associations                 eigenclass.
 end
                                       Now the Base class can include the
class Post < Base                      Associations module and our model can
 belongs_to                            inherit from Base
end
                                       One more step…
module ActiveRecord
 module Associations

  def self.included(base)
   base.extend(ClassMethods)
  end

  module ClassMethods
   def belongs_to
    “I am in the ClassMethods module”
   end
  end
 end

 class Base
  include Associations
 end
end

class Post < ActiveRecord::Base
 belongs_to
end

Add an ActiveRecord Namespace and we have something
resembling the original
Ghost Methods
class Post                                  #method_missing
 def initialize                             catches the call to
  @attributes = {}
                                            name=() or returns
 end
 def method_missing(name, *args)            the value when it
  attribute = name.to_s                     gets a method
  if attribute =~ /=$/                      without an ‘=‘
    @attributes[attribute.chop] = args[0]
  else                                      It chops off the
    @attributes[attribute]
                                            equals sign to get
  end
 end                                        the attribute name
end                                         and then sets the
my_post = Post.new                          hash value
my_post.name = ‘Chile L’

More Related Content

What's hot (20)

Object oriented programming in php
Object oriented programming in phpObject oriented programming in php
Object oriented programming in php
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introduction
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Php oop presentation
Php   oop presentationPhp   oop presentation
Php oop presentation
 
Python advance
Python advancePython advance
Python advance
 
Inheritance in java
Inheritance in java Inheritance in java
Inheritance in java
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 
PHP Classes and OOPS Concept
PHP Classes and OOPS ConceptPHP Classes and OOPS Concept
PHP Classes and OOPS Concept
 
Demystifying oop
Demystifying oopDemystifying oop
Demystifying oop
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
 

Viewers also liked

02 elements of vectors
02 elements of vectors02 elements of vectors
02 elements of vectorsKrishna Gali
 
Infografia danzastipicas
Infografia danzastipicasInfografia danzastipicas
Infografia danzastipicaskellyazanero
 
Infografia danzastipicas
Infografia danzastipicasInfografia danzastipicas
Infografia danzastipicaskellyazanero
 
General Psych, Ch. 7
General Psych, Ch. 7General Psych, Ch. 7
General Psych, Ch. 7SayBrea
 

Viewers also liked (7)

02 elements of vectors
02 elements of vectors02 elements of vectors
02 elements of vectors
 
Danzastipicas (1)
Danzastipicas (1)Danzastipicas (1)
Danzastipicas (1)
 
Blogujeme vo wordpresse
Blogujeme vo wordpresseBlogujeme vo wordpresse
Blogujeme vo wordpresse
 
Infografia danzastipicas
Infografia danzastipicasInfografia danzastipicas
Infografia danzastipicas
 
Zmeňte svet slovom
Zmeňte svet slovomZmeňte svet slovom
Zmeňte svet slovom
 
Infografia danzastipicas
Infografia danzastipicasInfografia danzastipicas
Infografia danzastipicas
 
General Psych, Ch. 7
General Psych, Ch. 7General Psych, Ch. 7
General Psych, Ch. 7
 

Similar to Understanding Ruby Classes and Modules

Metaprogramming 101
Metaprogramming 101Metaprogramming 101
Metaprogramming 101Nando Vieira
 
Object_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdfObject_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdfGammingWorld2
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby MetaprogrammingWei Jen Lu
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in RubyConFoo
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogrammingjoshbuddy
 
The Dark Art of Rails Plugins (2008)
The Dark Art of Rails Plugins (2008)The Dark Art of Rails Plugins (2008)
The Dark Art of Rails Plugins (2008)lazyatom
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Threeamiable_indian
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby MetaprogrammingNando Vieira
 
Classboxes, nested methods, and real private methods
Classboxes, nested methods, and real private methodsClassboxes, nested methods, and real private methods
Classboxes, nested methods, and real private methodsShugo Maeda
 
Ruby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for rubyRuby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for rubyTushar Pal
 
Reusable Ruby • Rt 9 Ruby Group • Jun 2012
Reusable Ruby • Rt 9 Ruby Group • Jun 2012Reusable Ruby • Rt 9 Ruby Group • Jun 2012
Reusable Ruby • Rt 9 Ruby Group • Jun 2012skinandbones
 
Introduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection APIIntroduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection APINiranjan Sarade
 
Extending Rails with Plugins (2007)
Extending Rails with Plugins (2007)Extending Rails with Plugins (2007)
Extending Rails with Plugins (2007)lazyatom
 
Application package
Application packageApplication package
Application packageJAYAARC
 
Metaprogramming Rails
Metaprogramming RailsMetaprogramming Rails
Metaprogramming RailsJustus Eapen
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming Raghunath A
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptxrani marri
 

Similar to Understanding Ruby Classes and Modules (20)

Ruby object model
Ruby object modelRuby object model
Ruby object model
 
Metaprogramming 101
Metaprogramming 101Metaprogramming 101
Metaprogramming 101
 
Object_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdfObject_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdf
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
The Dark Art of Rails Plugins (2008)
The Dark Art of Rails Plugins (2008)The Dark Art of Rails Plugins (2008)
The Dark Art of Rails Plugins (2008)
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
 
Classboxes, nested methods, and real private methods
Classboxes, nested methods, and real private methodsClassboxes, nested methods, and real private methods
Classboxes, nested methods, and real private methods
 
Ruby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for rubyRuby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for ruby
 
Reusable Ruby • Rt 9 Ruby Group • Jun 2012
Reusable Ruby • Rt 9 Ruby Group • Jun 2012Reusable Ruby • Rt 9 Ruby Group • Jun 2012
Reusable Ruby • Rt 9 Ruby Group • Jun 2012
 
Module Magic
Module MagicModule Magic
Module Magic
 
13 ruby modules
13 ruby modules13 ruby modules
13 ruby modules
 
Introduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection APIIntroduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection API
 
Extending Rails with Plugins (2007)
Extending Rails with Plugins (2007)Extending Rails with Plugins (2007)
Extending Rails with Plugins (2007)
 
Application package
Application packageApplication package
Application package
 
Metaprogramming Rails
Metaprogramming RailsMetaprogramming Rails
Metaprogramming Rails
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
 

Recently uploaded

No.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in KarachiNo.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in KarachiAmil Baba Mangal Maseeh
 
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in KarachiNo.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in KarachiAmil Baba Mangal Maseeh
 
Unity is Strength 2024 Peace Haggadah + Song List.pdf
Unity is Strength 2024 Peace Haggadah + Song List.pdfUnity is Strength 2024 Peace Haggadah + Song List.pdf
Unity is Strength 2024 Peace Haggadah + Song List.pdfRebeccaSealfon
 
Sawwaf Calendar, 2024
Sawwaf Calendar, 2024Sawwaf Calendar, 2024
Sawwaf Calendar, 2024Bassem Matta
 
Understanding Jainism Beliefs and Information.pptx
Understanding Jainism Beliefs and Information.pptxUnderstanding Jainism Beliefs and Information.pptx
Understanding Jainism Beliefs and Information.pptxjainismworldseo
 
Culture Clash_Bioethical Concerns_Slideshare Version.pptx
Culture Clash_Bioethical Concerns_Slideshare Version.pptxCulture Clash_Bioethical Concerns_Slideshare Version.pptx
Culture Clash_Bioethical Concerns_Slideshare Version.pptxStephen Palm
 
Tremble song lyrics Powerpoint church music
Tremble song lyrics Powerpoint church musicTremble song lyrics Powerpoint church music
Tremble song lyrics Powerpoint church musicmaynjc
 
原版1:1复刻莫纳什大学毕业证Monash毕业证留信学历认证
原版1:1复刻莫纳什大学毕业证Monash毕业证留信学历认证原版1:1复刻莫纳什大学毕业证Monash毕业证留信学历认证
原版1:1复刻莫纳什大学毕业证Monash毕业证留信学历认证jdkhjh
 
Seerah un nabi Muhammad Quiz Part-1.pdf
Seerah un nabi  Muhammad Quiz Part-1.pdfSeerah un nabi  Muhammad Quiz Part-1.pdf
Seerah un nabi Muhammad Quiz Part-1.pdfAnsariB1
 
Study of the Psalms Chapter 1 verse 1 - wanderean
Study of the Psalms Chapter 1 verse 1 - wandereanStudy of the Psalms Chapter 1 verse 1 - wanderean
Study of the Psalms Chapter 1 verse 1 - wandereanmaricelcanoynuay
 
Asli amil baba in Karachi Pakistan and best astrologer Black magic specialist
Asli amil baba in Karachi Pakistan and best astrologer Black magic specialistAsli amil baba in Karachi Pakistan and best astrologer Black magic specialist
Asli amil baba in Karachi Pakistan and best astrologer Black magic specialistAmil Baba Mangal Maseeh
 
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in KarachiNo.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in KarachiAmil Baba Mangal Maseeh
 
Deerfoot Church of Christ Bulletin 4 21 24
Deerfoot Church of Christ Bulletin 4 21 24Deerfoot Church of Christ Bulletin 4 21 24
Deerfoot Church of Christ Bulletin 4 21 24deerfootcoc
 
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in KarachiNo.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in KarachiAmil Baba Mangal Maseeh
 
The Chronological Life of Christ part 097 (Reality Check Luke 13 1-9).pptx
The Chronological Life of Christ part 097 (Reality Check Luke 13 1-9).pptxThe Chronological Life of Christ part 097 (Reality Check Luke 13 1-9).pptx
The Chronological Life of Christ part 097 (Reality Check Luke 13 1-9).pptxNetwork Bible Fellowship
 
Amil baba in uk amil baba in Australia amil baba in canada
Amil baba in uk amil baba in Australia amil baba in canadaAmil baba in uk amil baba in Australia amil baba in canada
Amil baba in uk amil baba in Australia amil baba in canadaamil baba kala jadu
 
Unity is Strength 2024 Peace Haggadah_For Digital Viewing.pdf
Unity is Strength 2024 Peace Haggadah_For Digital Viewing.pdfUnity is Strength 2024 Peace Haggadah_For Digital Viewing.pdf
Unity is Strength 2024 Peace Haggadah_For Digital Viewing.pdfRebeccaSealfon
 

Recently uploaded (20)

No.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in KarachiNo.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
 
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in KarachiNo.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
 
St. Louise de Marillac: Animator of the Confraternities of Charity
St. Louise de Marillac: Animator of the Confraternities of CharitySt. Louise de Marillac: Animator of the Confraternities of Charity
St. Louise de Marillac: Animator of the Confraternities of Charity
 
Unity is Strength 2024 Peace Haggadah + Song List.pdf
Unity is Strength 2024 Peace Haggadah + Song List.pdfUnity is Strength 2024 Peace Haggadah + Song List.pdf
Unity is Strength 2024 Peace Haggadah + Song List.pdf
 
Sawwaf Calendar, 2024
Sawwaf Calendar, 2024Sawwaf Calendar, 2024
Sawwaf Calendar, 2024
 
Understanding Jainism Beliefs and Information.pptx
Understanding Jainism Beliefs and Information.pptxUnderstanding Jainism Beliefs and Information.pptx
Understanding Jainism Beliefs and Information.pptx
 
Culture Clash_Bioethical Concerns_Slideshare Version.pptx
Culture Clash_Bioethical Concerns_Slideshare Version.pptxCulture Clash_Bioethical Concerns_Slideshare Version.pptx
Culture Clash_Bioethical Concerns_Slideshare Version.pptx
 
🔝9953056974 🔝young Delhi Escort service Vinay Nagar
🔝9953056974 🔝young Delhi Escort service Vinay Nagar🔝9953056974 🔝young Delhi Escort service Vinay Nagar
🔝9953056974 🔝young Delhi Escort service Vinay Nagar
 
Tremble song lyrics Powerpoint church music
Tremble song lyrics Powerpoint church musicTremble song lyrics Powerpoint church music
Tremble song lyrics Powerpoint church music
 
原版1:1复刻莫纳什大学毕业证Monash毕业证留信学历认证
原版1:1复刻莫纳什大学毕业证Monash毕业证留信学历认证原版1:1复刻莫纳什大学毕业证Monash毕业证留信学历认证
原版1:1复刻莫纳什大学毕业证Monash毕业证留信学历认证
 
Seerah un nabi Muhammad Quiz Part-1.pdf
Seerah un nabi  Muhammad Quiz Part-1.pdfSeerah un nabi  Muhammad Quiz Part-1.pdf
Seerah un nabi Muhammad Quiz Part-1.pdf
 
Study of the Psalms Chapter 1 verse 1 - wanderean
Study of the Psalms Chapter 1 verse 1 - wandereanStudy of the Psalms Chapter 1 verse 1 - wanderean
Study of the Psalms Chapter 1 verse 1 - wanderean
 
Asli amil baba in Karachi Pakistan and best astrologer Black magic specialist
Asli amil baba in Karachi Pakistan and best astrologer Black magic specialistAsli amil baba in Karachi Pakistan and best astrologer Black magic specialist
Asli amil baba in Karachi Pakistan and best astrologer Black magic specialist
 
young Whatsapp Call Girls in Adarsh Nagar🔝 9953056974 🔝 escort service
young Whatsapp Call Girls in Adarsh Nagar🔝 9953056974 🔝 escort serviceyoung Whatsapp Call Girls in Adarsh Nagar🔝 9953056974 🔝 escort service
young Whatsapp Call Girls in Adarsh Nagar🔝 9953056974 🔝 escort service
 
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in KarachiNo.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
 
Deerfoot Church of Christ Bulletin 4 21 24
Deerfoot Church of Christ Bulletin 4 21 24Deerfoot Church of Christ Bulletin 4 21 24
Deerfoot Church of Christ Bulletin 4 21 24
 
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in KarachiNo.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
No.1 Amil baba in Pakistan amil baba in Lahore amil baba in Karachi
 
The Chronological Life of Christ part 097 (Reality Check Luke 13 1-9).pptx
The Chronological Life of Christ part 097 (Reality Check Luke 13 1-9).pptxThe Chronological Life of Christ part 097 (Reality Check Luke 13 1-9).pptx
The Chronological Life of Christ part 097 (Reality Check Luke 13 1-9).pptx
 
Amil baba in uk amil baba in Australia amil baba in canada
Amil baba in uk amil baba in Australia amil baba in canadaAmil baba in uk amil baba in Australia amil baba in canada
Amil baba in uk amil baba in Australia amil baba in canada
 
Unity is Strength 2024 Peace Haggadah_For Digital Viewing.pdf
Unity is Strength 2024 Peace Haggadah_For Digital Viewing.pdfUnity is Strength 2024 Peace Haggadah_For Digital Viewing.pdf
Unity is Strength 2024 Peace Haggadah_For Digital Viewing.pdf
 

Understanding Ruby Classes and Modules

  • 1. Goal: to grok this code class Post < ActiveRecord::Base <= class extension mixin belongs_to :user <= macro end my_post = Post.new my_post.name = 'Chile L‘ <= employs #method_missing my_post.subject = 'traveling in thailand' my_post.content = 'sometimes you can almost not tell the difference' my_post.save!
  • 2. Coming from a compiled language, runtime execution is foreign, all code is executed code Post.respond_to? Name Ruby is a dynamic language
  • 3. Classes are also like namespaces too. class MyClass puts ‘Hello World’ end # => Hello World
  • 5. Singleton method variations on the MyClass instance class MyClass def MyClass.my_method; end def self.my_method; end class << self def my_method; end end end
  • 6. class << Object puts self def my_method Different puts ‘hi’ end end class Object class << Object is adding methods to the eigenclass of Object. This method is now available to all objects as if it were a class def self.meth2 puts self method. puts ‘there’ end However, opening the Object class and adding methods to self class << self shows the current object is the instance Foo. def meth3 puts self puts ‘hahaha’ end end end Foo = Class.new Foo.my_method Foo.meth2 Foo.meth3 # => #<Class:Object> # => hi # => Foo # => there # => Foo # => hahaha
  • 7. Including the module in the Eigenclass of class C to create class methods module M def my_method puts ‘hi’ end end class C class << self include M end end C.my_method # => hi
  • 8. Using extend to add class methods to C module M def my_method puts ‘hi’ end end class C extend M end C.my_method # => hi
  • 9. Class methods are singletons of the class object, that means they are in the eigenclass class C Self, therefore the current object, is puts self changed by opening up the class << self eigenclass puts self def my_method puts ‘hi’ end end end C.my_method # => C # => #<Class:C> # => hi
  • 10. Examining self… class Foo Self, the current object, is changed puts self by opening up the eigenclass and class << self we are now adding my_method to puts self the Foo instance, but this is def my_method equivalent to Foo.my_method puts ‘hi’ end end end Foo.my_method # => Foo # => #<Class:Foo> # => hi
  • 11. Hook methods or callbacks
  • 12. Hooking Module#included exists solely as a callback and the default implementation is empty.
  • 13. Hook methods - Module#included module Mod1 class << self def included(othermod) puts "Mod1 was mixed into #{othermod}" end end end class MyClass include Mod1 end # => Mod1 was mixed into MyClass
  • 14. Hook methods - Module#include (must call super if you override, to actually include the module) module Mod1; end module Mod2; end class MyClass def self.include(*modules) puts “#{modules} included” super end include Mod1 include Mod2 end # => [Mod1] included # => [Mod2] included
  • 16. module Associations This is obviously very dumbed down, but now we can start to see some things in def self.included(base) action. base.extend(ClassMethods) end We have defined the module Associations which includes a submodule module ClassMethods ClassMethods which will hold class def belongs_to methods. “I am in the ClassMethods module” end Overriding included now acts on the end including class which is base in this case. end This class is sometimes called the inclusor. The extend method adds the class Base ClassMethods to the inclusor’s include Associations eigenclass. end Now the Base class can include the class Post < Base Associations module and our model can belongs_to inherit from Base end One more step…
  • 17. module ActiveRecord module Associations def self.included(base) base.extend(ClassMethods) end module ClassMethods def belongs_to “I am in the ClassMethods module” end end end class Base include Associations end end class Post < ActiveRecord::Base belongs_to end Add an ActiveRecord Namespace and we have something resembling the original
  • 18. Ghost Methods class Post #method_missing def initialize catches the call to @attributes = {} name=() or returns end def method_missing(name, *args) the value when it attribute = name.to_s gets a method if attribute =~ /=$/ without an ‘=‘ @attributes[attribute.chop] = args[0] else It chops off the @attributes[attribute] equals sign to get end end the attribute name end and then sets the my_post = Post.new hash value my_post.name = ‘Chile L’