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
- #[](name) ⇒ Object
-
#initialize(attributes) ⇒ Base
constructor
A new instance of Base.
- #output(context = nil) ⇒ Object
Constructor Details
#initialize(attributes) ⇒ Base
Returns a new instance of Base.
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/datev/base.rb', line 26 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.field_by_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 = {}, &block) ⇒ Object
11 12 13 14 15 16 17 18 19 20 |
# File 'lib/datev/base.rb', line 11 def self.field(name, type, ={}, &block) self.fields ||= [] # Check if there is already a field with the same name if field_by_name(name) raise ArgumentError.new("Field '#{name}' already exists") end self.fields << Field.new(name, type, , &block) end |
.field_by_name(name) ⇒ Object
22 23 24 |
# File 'lib/datev/base.rb', line 22 def self.field_by_name(name) self.fields.find { |f| f.name == name } end |
Instance Method Details
#[](name) ⇒ Object
49 50 51 52 53 54 |
# File 'lib/datev/base.rb', line 49 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
56 57 58 59 60 61 |
# File 'lib/datev/base.rb', line 56 def output(context=nil) self.class.fields.map do |field| value = attributes[field.name] field.output(value, context) end end |