Class: Zinc::Model

Inherits:
Object
  • Object
show all
Defined in:
lib/zinc/model.rb

Instance Method Summary collapse

Constructor Details

#initialize(hash, exclude: {}) ⇒ Model

Returns a new instance of Model.



3
4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/zinc/model.rb', line 3

def initialize(hash, exclude: {})
  hash.each do |key, value|
    if exclude.include?(key)
      next
    end

    if respond_to?("#{key}=")
      send("#{key}=", value)
    else
      Zinc.logger.warn "Invalid attribute #{key} specified for #{self.class.name}"
    end
  end
end

Instance Method Details

#to_hashObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/zinc/model.rb', line 17

def to_hash
  instance_variables.map do |instance_variable|
    key   = instance_variable_name(instance_variable)
    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