Skip to content

Instantly share code, notes, and snippets.

@alekpopovic
Forked from davidbella/person.rb
Created November 18, 2023 19:12
Show Gist options
  • Save alekpopovic/563e95fdd8817771a1a8a89ffb9c523b to your computer and use it in GitHub Desktop.
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
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