Module: HashAccessor::ClassMethods

Defined in:
lib/hash_accessor/class_methods.rb

Instance Method Summary collapse

Instance Method Details

#hash_accessor(hash_name, method_name, options = {}) ⇒ Object

valid options: :default - if undefined, this plugin will create an empty instance of the defined type or null :type - defaults to :string. Can also be :integer, :float, :boolean, or :array

for arrays only: :collects - only runs on arrays. Calls the lambda method on each item in the array before saving :reject_blanks - removes all blank elements after the collect method



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/hash_accessor/class_methods.rb', line 17

def hash_accessor(hash_name, method_name, options = {})
  begin
    method_name = method_name.to_sym

    # Define getter
    define_method(method_name) do
      send("#{hash_name}=", {}) if send(hash_name).blank?
      if send(hash_name)[method_name].nil?
        send(hash_name)[method_name] = hash_accessor_default(options)
      end
      send(hash_name)[method_name]
    end

    # Define setter
    define_method("#{method_name}=") do |new_val|
      send("#{hash_name}=", {}) if send(hash_name).blank?
      method_modifier = hash_accessor_method_modifier(method_name, options)
      new_val = method_modifier.call(new_val)
      if send(hash_name)[method_name] != new_val
        instance_variable_set("@#{method_name}_changed", true)
      end
      send(hash_name)[method_name] = new_val
    end

    # Define changed?
    define_method("#{method_name}_changed?") do
      !!instance_variable_get("@#{method_name}_changed")
    end

    # Define special boolean accessor
    if options[:type]==:boolean or options[:type]==:bool
      define_method("#{method_name}?") do
        !!send(method_name)
      end
    end

  rescue Exception => e
    puts "\n\nError adding hash_accessor:\n#{e.message}\n#{e.backtrace}\n\n"
  end
end