Class: Datev::Base

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

Direct Known Subclasses

Booking, Header

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes) ⇒ Base

Returns a new instance of Base.

Raises:

  • (ArgumentError)


22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/datev/base.rb', line 22

def initialize(attributes)
  self.attributes = {}

  raise ArgumentError.new('Hash required') unless attributes.is_a?(Hash)

  # Check existing names and set value (if valid)
  attributes.each_pair do |name,value|
    unless field = self.class.fields.find { |f| f.name == name }
      raise ArgumentError.new("Field '#{name}' not found")
    end

    field.validate!(value)
    self.attributes[name] = value
  end

  # Check for missing values
  self.class.fields.select(&:required?).each do |field|
    if attributes[field.name].nil?
      raise ArgumentError.new("Value for field '#{field.name}' is required but missing")
    end
  end
end

Class Attribute Details

.fields ⇒ Object

Returns the value of attribute fields.



6
7
8
# File 'lib/datev/base.rb', line 6

def fields
  @fields
end

Instance Attribute Details

#attributes ⇒ Object

Returns the value of attribute attributes.



9
10
11
# File 'lib/datev/base.rb', line 9

def attributes
  @attributes
end

Class Method Details

.field(name, type, options = {}) ⇒ Object



11
12
13
14
15
16
17
18
19
20
# File 'lib/datev/base.rb', line 11

def self.field(name, type, options={})
  self.fields ||= []

  # Check if there is already a field with the same name
  if self.fields.find { |f| f.name == name }
    raise ArgumentError.new("Field '#{name}' already exists")
  end

  self.fields << Field.new(name, type, options)
end

Instance Method Details

#to_a ⇒ Object



45
46
47
48
49
50
# File 'lib/datev/base.rb', line 45

def to_a
  self.class.fields.map do |field|
    value = attributes[field.name]
    field.output(value)
  end
end