Tuesday 30 October 2012

Adding object dinamically to a class.

Ruby's a great programming language everybody know. The breakthrough in Ruby is adding objects dynamically in a class, it's really amazing. Why? It's possible to create a simple interface with high complexity. For example, it's really viable create a car only adding parts in the object. How did you do this? Using 'self.class.send(:define_method, name, &block)'. This code will add a instance method (name) and code method (&block). Actually, if you pass a object via &block, your new method will behave like a object and your master class will be clean and it don't need implement nothing. I'm not quite sure about design pattern name, although I like this. Example:
class Car 
 def add_wheel(wheel)
  add_object("wheel"){wheel}
 end 
 
 def add_part(name, obj)
  add_object(name){obj}
 end 
 
 private
 
 def add_object(name, &block)
  self.class.send(:define_method, name, &block)
 end   
end

class Wheel
 def initialize(size)
  @size = size
 end 
 
 def size
  puts "Wheel size #{@size}"
 end 
end 

class CarPaint
 def initialize(colour)
  @colour = colour
 end 
 
 def is_metallic_color?
  true
 end
 
 def colour
  puts "Colour #{@colour}"
 end
end 

my_car = Car.new
my_car.add_wheel(Wheel.new(17))

my_car.wheel.size
my_car.add_part("colour", CarPaint.new("red"))

puts my_car.colour.is_metallic_color?
my_car.colour.colour

No comments:

Post a Comment