-
-
Save alekpopovic/563e95fdd8817771a1a8a89ffb9c523b to your computer and use it in GitHub Desktop.
Ruby: Dynamic meta-programming to create attr_accessor like methods on the fly
This file contains 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
class Person | |
def initialize(attributes) | |
attributes.each do |attribute_name, attribute_value| | |
##### Method one ##### | |
# Works just great, but uses something scary like eval | |
# self.class.class_eval {attr_accessor attribute_name} | |
# self.instance_variable_set("@#{attribute_name}", attribute_value) | |
##### Method two ##### | |
# Manually creates methods for both getter and setter and then | |
# sends a message to the new setter with the attribute_value | |
self.class.send(:define_method, "#{attribute_name}=".to_sym) do |value| | |
instance_variable_set("@" + attribute_name.to_s, value) | |
end | |
self.class.send(:define_method, attribute_name.to_sym) do | |
instance_variable_get("@" + attribute_name.to_s) | |
end | |
self.send("#{attribute_name}=".to_sym, attribute_value) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment