DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Prototype-based Ruby

01.27.2007
| 3378 views |
  • submit to reddit
        

# From: http://programming.reddit.com/info/ob4m/comments/cobr4
# Author: Brian Mitchell
# cf. http://t-a-w.blogspot.com/2006/10/prototype-based-ruby.html

Proto = Class.new(Class)    # Beware: magic.
def Proto.clone
  Class.new(self)
end

# Demo
a = Proto.clone
def a.f
  puts 42
end
a.f                     #=> 42

b = a.clone
b.f                     #=> 42
def b.f
  puts 43
end
a.f                      #=> 42
b.f                      #=> 43

def a.g
  "Hello differential inheritance"
end

bool_val = (a.g == b.g)
p bool_val                #=> true



# From: http://www.ruby-forum.com/topic/94696
# cf. http://tech.rufy.com/2006/06/classes-are-just-prototype-pattern.html

AnimalSounds = Module.new

AnimalSounds.class_eval %q!
def createSound(attr_name)
class_eval <<-EOS
   #def self.#{attr_name};  puts "class method '#{attr_name}' called"; end 
   def self.#{attr_name}(arg = nil) 
      str = "class method '#{attr_name}' of class #{self.inspect} called"
      arg ? (puts str + " with " + arg.to_s) : (puts str)
   end
EOS
end!


puts
p AnimalSounds
p AnimalSounds.class
p AnimalSounds.class.superclass
p AnimalSounds.class.ancestors
p AnimalSounds.singleton_methods
puts


Pet = Object.clone.extend(AnimalSounds)    
Pet.createSound("meow")                    # create a class method
Pet.meow                                   
Pet.meow("argument")      

p Pet
p Pet.class
p Pet.class.superclass
p Pet.class.ancestors
p Pet.singleton_methods
puts


fido = Pet.clone           
fido.meow           
fido.meow("argument")
fido.createSound("woof")    
fido.woof
fido.woof("argument")
puts


fido2 = fido.clone                        
fido2.woof
fido2.woof("argument")
fido2.createSound("woof2")                 
fido2.woof2
fido2.woof2("argument")

puts
p Pet.singleton_methods
p fido.singleton_methods
p fido2.singleton_methods
puts