Module: ClassWithAttributes::InstanceMethods

Defined in:
lib/check_mobi/shared/class_with_attributes.rb

Instance Method Summary collapse

Instance Method Details

#attributesObject



52
53
54
# File 'lib/check_mobi/shared/class_with_attributes.rb', line 52

def attributes
  self.class.instance_variable_get(:@attributes).map{|e| e[:name]}
end

#initialize(options = {}) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/check_mobi/shared/class_with_attributes.rb', line 56

def initialize(options = {})
  attributes = (self.class.instance_variable_get(:@attributes) || []).map{|e| [e[:name], e[:default].dup]}

  attributes.each do |name, val|
    if respond_to?("#{name}=") and options.include?(name)
      value =  options[name]
    else
      value = val
    end

    instance_variable_set("@#{name}", value)
  end

  after_initialize if respond_to?(:after_initialize, true)
end

#to_hashObject



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/check_mobi/shared/class_with_attributes.rb', line 77

def to_hash
  h = {}
  attributes.each do |attr|
    value = public_send(attr)
    if value.is_a? Array
      values = []
      value.each do |val|
        if val.respond_to?(:to_hash)
          values << val.to_hash
        else
          values << val
        end
      end
      h[attr] = values
    elsif value.respond_to?(:to_hash)
      h[attr] = value.to_hash
    else
      h[attr] = value
    end
  end

  return h
end

#update_attributes(options = {}) ⇒ Object



72
73
74
75
# File 'lib/check_mobi/shared/class_with_attributes.rb', line 72

def update_attributes(options= {})
  valid_options = options.select { |k,v| attributes.map(&:to_s).include?(k.to_s) }
  valid_options.each {|k,v| public_send("#{k}=", v) if respond_to?("#{k}=")}
end