Sunday, February 1, 2015

Setter and Getter method without using attr_accessor with DRY codes


Ruby code with custom Getter and Setter methods without using "attr_accessor" method


class Klass

  def methods(*mtds)

    mtds.each do |mtd|

      self.class.class_eval("def #{mtd}; @#{mtd}; end")

      self.class.class_eval("def #{mtd}=(val); @#{mtd}=val;end")
   end

  end
end


eg.:

obj = Klass.new

obj.methods 'mtd1','mtd2'


obj.mtd1 = "test1"
obj.mtd2 = 'test2'

o/p:
puts obj.mtd1 = test1
puts obj.mtd2 = test2


No comments:

Post a Comment