Class: Datev::Base
- Inherits:
-
Object
- Object
- Datev::Base
- Defined in:
- lib/datev/base.rb
Class Attribute Summary collapse
-
.fields ⇒ Object
Returns the value of attribute fields.
Instance Attribute Summary collapse
-
#attributes ⇒ Object
Returns the value of attribute attributes.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(attributes) ⇒ Base
constructor
A new instance of Base.
- #to_a ⇒ Object
Constructor Details
#initialize(attributes) ⇒ Base
Returns a new instance of Base.
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, ={}) 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, ) 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 |