The implementation below is very handy when you are you are not really concerned about a number or a quality of arguments you are setting (maybe you are prototyping ? consuming 3rd party API ?)
Pretty Straightforward, here is the code :
class MPB def initialize(*args) args[0].each do |key,value| singleton_class.class_eval { attr_accessor "#{key}" } eval("@#{key} = "#{value}"") # alternatively you can use this helper: instance_variable_set("@#{key}", value) end end end mpb = MPB.new(author: 'Anatoly', title: 'How to dynamically initialize args',body: "Read More!") p mpb # => #<MPB:0x00007f81fc0af250 @author="Anatoly", @title="How to dynamically initialize args", @body="Read More!">
Quick Explanation what am I doing here:
initialize()
allows us to receive *args
, which fives us a Hash
from arguments that you are passing to it. I go through this hash and create instance variable of every hash key, then I assign value to this hash key. Totally dynamic. I also create attribute_accessor
on a fly so I could read and write to any of those instance variables.
Note: There are edge cases not covered here, do make sure it works for your particular situation, but I think this is a good start.
Cheers,
Anatoly
Thanks for installing the Bottom of every post plugin by Corey Salzano. Contact me if you need custom WordPress plugins or website design.