Class: Infuser::Collections::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/infuser/collections/base.rb

Direct Known Subclasses

Address, Email, Fax, Phone

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data = {}) ⇒ Base

Returns a new instance of Base.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/infuser/collections/base.rb', line 32

def initialize data = {}
  initial_id = data.fetch(:id) { 0 }

  if initial_id > 0
    self.class.mappings[initial_id].each do |key, value|
      next if key == value

      define_singleton_method key do
        send value
      end

      define_singleton_method "#{key}=" do |*args|
        send "#{value}=", *args
      end
    end
  end

  data.each do |key, value|
    send "#{key}=", value
  end
end

Class Method Details

.define_mappings(map) ⇒ Object



5
6
7
8
9
10
# File 'lib/infuser/collections/base.rb', line 5

def self.define_mappings map
  @mappings = map
  @standardized_fields = map.values.map(&:values).flatten.uniq
  attr_accessor *standardized_fields
  attr_accessor :id
end

.inverted_mappingsObject



12
13
14
15
16
17
18
# File 'lib/infuser/collections/base.rb', line 12

def self.inverted_mappings
  @inverted_mappings ||= mappings.each_with_object({}) do |(key, value), hash|
    value.keys.each do |field|
      hash[field] = key
    end
  end
end

.mappingsObject



24
25
26
# File 'lib/infuser/collections/base.rb', line 24

def self.mappings
  @mappings
end

.schemaObject



20
21
22
# File 'lib/infuser/collections/base.rb', line 20

def self.schema
  inverted_mappings.keys
end

.standardized_fieldsObject



28
29
30
# File 'lib/infuser/collections/base.rb', line 28

def self.standardized_fields
  @standardized_fields
end

Instance Method Details

#attributesObject

Raises:



61
62
63
64
65
66
# File 'lib/infuser/collections/base.rb', line 61

def attributes
  raise(Infuser::ArgumentError, 'Cannot be called if item has no ID') if id.nil?
  self.class.mappings[id].each_with_object({}) do |(key, value), hash|
    hash[value] = send(value)
  end
end

#dataObject

Raises:



54
55
56
57
58
59
# File 'lib/infuser/collections/base.rb', line 54

def data
  raise(Infuser::ArgumentError, 'Cannot be called if item has no ID') if id.nil?
  self.class.mappings[id].each_with_object({}) do |(key, value), hash|
    hash[key] = send(value)
  end
end