Created
October 10, 2013 13:37
-
-
Save davidbella/6918455 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 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
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
Thank you @davidbella! It's an excellent reference to dinamically handle json columns as regular attributes. I just posted an example here:
https://gist.github.com/pangui/28b45c3601395ef52df649a7ef84388b
The gist can also be adapted for Rails
ApplicationRecord
models viaActiveSupport::Concern