Skip to content

Instantly share code, notes, and snippets.

@tansengming
Created October 28, 2009 06:17
Show Gist options
  • Select an option

  • Save tansengming/220292 to your computer and use it in GitHub Desktop.

Select an option

Save tansengming/220292 to your computer and use it in GitHub Desktop.
Where I show an iterative method of building an attr_reader type metaprogramming model
# Initial Rev
# machine.rb
class Machine
def initialize(name)
@name = name
end
def device
Lot.find_by_tester(@name).device
end
end
# 2nd Rev - Where we build a class method that will build
# an instance method.
# machine.rb
class Machine
def initialize(name)
@name = name
end
def self.associated_to(attr)
class_eval %Q*
def device
Lot.find_by_#{attr}(@name).device
end
*
end
associated_to :tester
end
# 3rd Rev - where we move all the methods out to a module.
# Note the gymnastics we need to go through to build
# class methods in the module.
# machine.rb
class Machine
include MakesAssociatedTo
associated_to :tester
end
# makes_associated_to.rb
module MakesAssociatedTo
def initialize(name)
@name = name
end
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def associated_to(attr)
class_eval %Q?
def device
Lot.find_by_#{attr}(@name).device
end
?
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment