Class: Datev::Base
- Inherits:
-
Object
show all
- Defined in:
- lib/datev/base.rb
Class Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(attributes) ⇒ Base
Returns a new instance of Base.
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
# File 'lib/datev/base.rb', line 37
def initialize(attributes)
raise ArgumentError.new('Hash required') unless attributes.is_a?(Hash)
@attributes = self.class.default_attributes || {}
attributes.each_pair do |name,value|
unless field = self.class.field_by_name(name)
raise ArgumentError.new("Field '#{name}' not found")
end
field.validate!(value)
@attributes[name] = value
end
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
.default_attributes ⇒ Object
7
8
9
10
11
12
13
|
# File 'lib/datev/base.rb', line 7
def default_attributes
if @default_attributes.is_a?(Proc)
@default_attributes.call
else
@default_attributes
end
end
|
.fields ⇒ Object
Returns the value of attribute fields.
4
5
6
|
# File 'lib/datev/base.rb', line 4
def fields
@fields
end
|
Class Method Details
.field(name, type, options = {}, &block) ⇒ Object
21
22
23
24
25
26
27
28
29
30
31
|
# File 'lib/datev/base.rb', line 21
def self.field(name, type, options={}, &block)
self.fields ||= []
if field_by_name(name)
raise ArgumentError.new("Field '#{name}' already exists")
end
field_class = const_get("Datev::#{type.to_s.capitalize}Field")
self.fields << field_class.new(name, options, &block)
end
|
.field_by_name(name) ⇒ Object
33
34
35
|
# File 'lib/datev/base.rb', line 33
def self.field_by_name(name)
self.fields.find { |f| f.name == name }
end
|
.inherited(subclass) ⇒ Object
15
16
17
18
|
# File 'lib/datev/base.rb', line 15
def inherited(subclass)
subclass.fields = self.fields
subclass.default_attributes = self.default_attributes
end
|
Instance Method Details
#[](name) ⇒ Object
60
61
62
63
64
65
|
# File 'lib/datev/base.rb', line 60
def [](name)
field = self.class.field_by_name(name)
raise ArgumentError.new("Field '#{name}' not found") unless field
@attributes[field.name]
end
|
#output(context = nil) ⇒ Object
67
68
69
70
71
72
|
# File 'lib/datev/base.rb', line 67
def output(context=nil)
self.class.fields.map do |field|
value = @attributes[field.name]
field.output(value, context)
end
end
|