The implementation under may be very to hand when you’re you aren’t actually enthusiastic about a host or a top quality of arguments you’re surroundings (possibly you’re prototyping ? eating third celebration API ?)
Lovely Easy, here’s the code :
elegance MPB def initialize(*args) args[0].every do |key,price| singleton_class.class_eval { attr_accessor "#{key}" } eval("@#{key} = "#{price}"") # then again you'll use this helper: instance_variable_set("@#{key}", price) finish finish finish mpb = MPB.new(creator: 'Anatoly', identify: 'Easy methods to dynamically initialize args',frame: "Learn Extra!") p mpb # => #<MPB:0x00007f81fc0af250 @creator="Anatoly", @identify="Easy methods to dynamically initialize args", @frame="Learn Extra!">
Fast Rationalization what am I doing right here:
initialize()
permits us to obtain *args
, which fives us a Hash
from arguments that you’re passing to it. I’m going via this hash and create example variable of each hash key, then I assign price to this hash key. Utterly dynamic. I additionally create attribute_accessor
on a fly so I may learn and write to any of the ones example variables.
Notice: There are edge circumstances now not lined right here, do be certain it really works in your specific scenario, however I feel it is a just right get started.
Cheers,
Anatoly
Thank you for putting in the Backside of each publish plugin by way of Corey Salzano. Touch me if you want customized WordPress plugins or site design.