Created
October 16, 2010 18:30
-
-
Save ashmoran/630124 to your computer and use it in GitHub Desktop.
Example of metaprogramming to create an entire class dynamically without `Kernel.eval`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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