Module: Dynattribs::ClassMethods

Defined in:
lib/dynattribs.rb

Instance Method Summary collapse

Instance Method Details

#dynamic_attr_accessor(*args) ⇒ Object

takes two or more arguments, first arg is the name of the database field that backs the dynamic fields data hash. the other arguments are used to create getter/setter methods of the arguments name.



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/dynattribs.rb', line 63

def dynamic_attr_accessor(*args)
   
  # the first element in the array is the name of the field
  # used to store the json encoded dynamic attribute data
  dynamic_attributes_backing_field_name = args.shift
  # create a method to access this extra data field name
  self.class_eval("def dynamic_attributes_backing_field_name;'#{dynamic_attributes_backing_field_name}';end") if !dynamic_attributes_backing_field_name.empty?

  # iterate through the rest of the arguments and create
  # a getter and setter method of each of the desired dynamic attributes
  args.each do |arg|
    # getter - creates a wrapper for the get_dynamic_attr method
    self.class_eval("def #{arg};get_dynamic_attr('#{arg}');end")

    # setter - creates a wrapper for the set_dynamic_attr method
    self.class_eval("def #{arg}=(val);set_dynamic_attr('#{arg}', val); end")
  end
end