Class: TophatterMerchant::Resource

Inherits:
Object
  • Object
show all
Defined in:
lib/tophatter_merchant/resource.rb

Direct Known Subclasses

Metadata, Order, Product, Variation

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ Resource

Returns a new instance of Resource.



10
11
12
13
14
15
16
17
18
# File 'lib/tophatter_merchant/resource.rb', line 10

def initialize(hash)
  hash.each do |key, value|
    if respond_to?("#{key}=")
      send("#{key}=", value)
    else
      TophatterMerchant.logger.warn "Invalid attribute #{key} specified for #{self.class.name}"
    end
  end
end

Instance Method Details

#to_hashObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/tophatter_merchant/resource.rb', line 20

def to_hash
  instance_variables.map do |instance_variable|
    key   = instance_variable.to_s.delete('@')
    value = instance_variable_get(instance_variable)

    if value.is_a?(Array) && value.all? { |element| element.respond_to?(:to_hash) }
      value = value.map(&:to_hash)
    elsif value.respond_to?(:to_hash)
      value = value.to_hash
    end

    value ? [key, value] : nil
  end.compact.to_h
end