module ClassWithAttributes::InstanceMethods

Public Class Methods

new(options = {}) click to toggle source
# 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

Public Instance Methods

attributes() click to toggle source
# File lib/check_mobi/shared/class_with_attributes.rb, line 52
def attributes
  self.class.instance_variable_get(:@attributes).map{|e| e[:name]}
end
to_hash() click to toggle source
# 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= {}) click to toggle source
# 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