Skip to content

Instantly share code, notes, and snippets.

@ashmoran
Created October 16, 2010 18:30
Show Gist options
  • Select an option

  • Save ashmoran/630124 to your computer and use it in GitHub Desktop.

Select an option

Save ashmoran/630124 to your computer and use it in GitHub Desktop.
Example of metaprogramming to create an entire class dynamically without `Kernel.eval`
def make_me_an_animal_class(name, property)
klass = Class.new
klass.class_eval do
define_method(:initialize) do |attribute|
instance_variable_set("@#{property}", attribute)
end
define_method(property) do
instance_variable_get("@#{property}")
end
end
Object.const_set(name, klass)
klass
end
make_me_an_animal_class("Dog", "age")
make_me_an_animal_class("Cow", "name")
dog = Dog.new(3)
puts dog.age
puts dog.instance_variable_get("@age")
cow = Cow.new("Daisy")
puts cow.name
puts cow.instance_variable_get("@name")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment