SlideShare una empresa de Scribd logo
1 de 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’

Más contenido relacionado

La actualidad más candente

La actualidad más candente (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
 

Destacado

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
 

Destacado (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 a 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 a 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
 

Último

Meaningful Pursuits: Pursuing Obedience_Ecclesiastes.pptx
Meaningful Pursuits: Pursuing Obedience_Ecclesiastes.pptxMeaningful Pursuits: Pursuing Obedience_Ecclesiastes.pptx
Meaningful Pursuits: Pursuing Obedience_Ecclesiastes.pptxStephen Palm
 
Gangaur Celebrations 2024 - Rajasthani Sewa Samaj Karimnagar, Telangana State...
Gangaur Celebrations 2024 - Rajasthani Sewa Samaj Karimnagar, Telangana State...Gangaur Celebrations 2024 - Rajasthani Sewa Samaj Karimnagar, Telangana State...
Gangaur Celebrations 2024 - Rajasthani Sewa Samaj Karimnagar, Telangana State...INDIAN YOUTH SECURED ORGANISATION
 
Deerfoot Church of Christ Bulletin 4 14 24
Deerfoot Church of Christ Bulletin 4 14 24Deerfoot Church of Christ Bulletin 4 14 24
Deerfoot Church of Christ Bulletin 4 14 24deerfootcoc
 
Ayodhya Temple saw its first Big Navratri Festival!
Ayodhya Temple saw its first Big Navratri Festival!Ayodhya Temple saw its first Big Navratri Festival!
Ayodhya Temple saw its first Big Navratri Festival!All in One Trendz
 
The-Clear-Quran,-A-Thematic-English-Translation-by-Dr-Mustafa-Khattab.pdf
The-Clear-Quran,-A-Thematic-English-Translation-by-Dr-Mustafa-Khattab.pdfThe-Clear-Quran,-A-Thematic-English-Translation-by-Dr-Mustafa-Khattab.pdf
The-Clear-Quran,-A-Thematic-English-Translation-by-Dr-Mustafa-Khattab.pdfSana Khan
 
PROPHECY-- The End Of My People Forever!
PROPHECY-- The End Of My People Forever!PROPHECY-- The End Of My People Forever!
PROPHECY-- The End Of My People Forever!spy7777777guy
 
PROPHECY-- The End Of My People Forever!
PROPHECY-- The End Of My People Forever!PROPHECY-- The End Of My People Forever!
PROPHECY-- The End Of My People Forever!spy7777777guy
 
A357 Hate can stir up strife, but love can cover up all mistakes. hate, love...
A357 Hate can stir up strife, but love can cover up all mistakes.  hate, love...A357 Hate can stir up strife, but love can cover up all mistakes.  hate, love...
A357 Hate can stir up strife, but love can cover up all mistakes. hate, love...franktsao4
 
A Tsunami Tragedy ~ Wise Reflections for Troubled Times (Eng. & Chi.).pptx
A Tsunami Tragedy ~ Wise Reflections for Troubled Times (Eng. & Chi.).pptxA Tsunami Tragedy ~ Wise Reflections for Troubled Times (Eng. & Chi.).pptx
A Tsunami Tragedy ~ Wise Reflections for Troubled Times (Eng. & Chi.).pptxOH TEIK BIN
 
Deerfoot Church of Christ Bulletin 3 31 24
Deerfoot Church of Christ Bulletin 3 31 24Deerfoot Church of Christ Bulletin 3 31 24
Deerfoot Church of Christ Bulletin 3 31 24deerfootcoc
 
Prach Autism AI - Artificial Intelligence
Prach Autism AI - Artificial IntelligencePrach Autism AI - Artificial Intelligence
Prach Autism AI - Artificial Intelligenceprachaibot
 
Interesting facts about Hindu Mythology.pptx
Interesting facts about Hindu Mythology.pptxInteresting facts about Hindu Mythology.pptx
Interesting facts about Hindu Mythology.pptxaskganesha.com
 
Monthly Khazina-e-Ruhaniyaat April’2024 (Vol.14, Issue 12)
Monthly Khazina-e-Ruhaniyaat April’2024 (Vol.14, Issue 12)Monthly Khazina-e-Ruhaniyaat April’2024 (Vol.14, Issue 12)
Monthly Khazina-e-Ruhaniyaat April’2024 (Vol.14, Issue 12)Darul Amal Chishtia
 
Deerfoot Church of Christ Bulletin 2 25 24
Deerfoot Church of Christ Bulletin 2 25 24Deerfoot Church of Christ Bulletin 2 25 24
Deerfoot Church of Christ Bulletin 2 25 24deerfootcoc
 
empathy map for students very useful.pptx
empathy map for students very useful.pptxempathy map for students very useful.pptx
empathy map for students very useful.pptxGeorgePhilips7
 
Secrets of Divine Love - A Spiritual Journey into the Heart of Islam - A. Helwa
Secrets of Divine Love - A Spiritual Journey into the Heart of Islam - A. HelwaSecrets of Divine Love - A Spiritual Journey into the Heart of Islam - A. Helwa
Secrets of Divine Love - A Spiritual Journey into the Heart of Islam - A. HelwaNodd Nittong
 
Codex Singularity: Search for the Prisca Sapientia
Codex Singularity: Search for the Prisca SapientiaCodex Singularity: Search for the Prisca Sapientia
Codex Singularity: Search for the Prisca Sapientiajfrenchau
 

Último (20)

Meaningful Pursuits: Pursuing Obedience_Ecclesiastes.pptx
Meaningful Pursuits: Pursuing Obedience_Ecclesiastes.pptxMeaningful Pursuits: Pursuing Obedience_Ecclesiastes.pptx
Meaningful Pursuits: Pursuing Obedience_Ecclesiastes.pptx
 
Gangaur Celebrations 2024 - Rajasthani Sewa Samaj Karimnagar, Telangana State...
Gangaur Celebrations 2024 - Rajasthani Sewa Samaj Karimnagar, Telangana State...Gangaur Celebrations 2024 - Rajasthani Sewa Samaj Karimnagar, Telangana State...
Gangaur Celebrations 2024 - Rajasthani Sewa Samaj Karimnagar, Telangana State...
 
Top 8 Krishna Bhajan Lyrics in English.pdf
Top 8 Krishna Bhajan Lyrics in English.pdfTop 8 Krishna Bhajan Lyrics in English.pdf
Top 8 Krishna Bhajan Lyrics in English.pdf
 
Deerfoot Church of Christ Bulletin 4 14 24
Deerfoot Church of Christ Bulletin 4 14 24Deerfoot Church of Christ Bulletin 4 14 24
Deerfoot Church of Christ Bulletin 4 14 24
 
Ayodhya Temple saw its first Big Navratri Festival!
Ayodhya Temple saw its first Big Navratri Festival!Ayodhya Temple saw its first Big Navratri Festival!
Ayodhya Temple saw its first Big Navratri Festival!
 
The-Clear-Quran,-A-Thematic-English-Translation-by-Dr-Mustafa-Khattab.pdf
The-Clear-Quran,-A-Thematic-English-Translation-by-Dr-Mustafa-Khattab.pdfThe-Clear-Quran,-A-Thematic-English-Translation-by-Dr-Mustafa-Khattab.pdf
The-Clear-Quran,-A-Thematic-English-Translation-by-Dr-Mustafa-Khattab.pdf
 
PROPHECY-- The End Of My People Forever!
PROPHECY-- The End Of My People Forever!PROPHECY-- The End Of My People Forever!
PROPHECY-- The End Of My People Forever!
 
PROPHECY-- The End Of My People Forever!
PROPHECY-- The End Of My People Forever!PROPHECY-- The End Of My People Forever!
PROPHECY-- The End Of My People Forever!
 
A357 Hate can stir up strife, but love can cover up all mistakes. hate, love...
A357 Hate can stir up strife, but love can cover up all mistakes.  hate, love...A357 Hate can stir up strife, but love can cover up all mistakes.  hate, love...
A357 Hate can stir up strife, but love can cover up all mistakes. hate, love...
 
A Tsunami Tragedy ~ Wise Reflections for Troubled Times (Eng. & Chi.).pptx
A Tsunami Tragedy ~ Wise Reflections for Troubled Times (Eng. & Chi.).pptxA Tsunami Tragedy ~ Wise Reflections for Troubled Times (Eng. & Chi.).pptx
A Tsunami Tragedy ~ Wise Reflections for Troubled Times (Eng. & Chi.).pptx
 
Deerfoot Church of Christ Bulletin 3 31 24
Deerfoot Church of Christ Bulletin 3 31 24Deerfoot Church of Christ Bulletin 3 31 24
Deerfoot Church of Christ Bulletin 3 31 24
 
Prach Autism AI - Artificial Intelligence
Prach Autism AI - Artificial IntelligencePrach Autism AI - Artificial Intelligence
Prach Autism AI - Artificial Intelligence
 
Interesting facts about Hindu Mythology.pptx
Interesting facts about Hindu Mythology.pptxInteresting facts about Hindu Mythology.pptx
Interesting facts about Hindu Mythology.pptx
 
Monthly Khazina-e-Ruhaniyaat April’2024 (Vol.14, Issue 12)
Monthly Khazina-e-Ruhaniyaat April’2024 (Vol.14, Issue 12)Monthly Khazina-e-Ruhaniyaat April’2024 (Vol.14, Issue 12)
Monthly Khazina-e-Ruhaniyaat April’2024 (Vol.14, Issue 12)
 
Deerfoot Church of Christ Bulletin 2 25 24
Deerfoot Church of Christ Bulletin 2 25 24Deerfoot Church of Christ Bulletin 2 25 24
Deerfoot Church of Christ Bulletin 2 25 24
 
empathy map for students very useful.pptx
empathy map for students very useful.pptxempathy map for students very useful.pptx
empathy map for students very useful.pptx
 
Secrets of Divine Love - A Spiritual Journey into the Heart of Islam - A. Helwa
Secrets of Divine Love - A Spiritual Journey into the Heart of Islam - A. HelwaSecrets of Divine Love - A Spiritual Journey into the Heart of Islam - A. Helwa
Secrets of Divine Love - A Spiritual Journey into the Heart of Islam - A. Helwa
 
English - The Dangers of Wine Alcohol.pptx
English - The Dangers of Wine Alcohol.pptxEnglish - The Dangers of Wine Alcohol.pptx
English - The Dangers of Wine Alcohol.pptx
 
Codex Singularity: Search for the Prisca Sapientia
Codex Singularity: Search for the Prisca SapientiaCodex Singularity: Search for the Prisca Sapientia
Codex Singularity: Search for the Prisca Sapientia
 
English - The Psalms of King Solomon.pdf
English - The Psalms of King Solomon.pdfEnglish - The Psalms of King Solomon.pdf
English - The Psalms of King Solomon.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’