Class: Datev::Base
- Inherits:
-
Object
- Object
- Datev::Base
- Defined in:
- lib/datev/base.rb
Class Attribute Summary collapse
-
.default_attributes ⇒ Object
Returns the value of attribute default_attributes.
-
.fields ⇒ Object
Returns the value of attribute fields.
Class Method Summary collapse
- .field(name, type, options = {}, &block) ⇒ Object
- .field_by_name(name) ⇒ Object
- .inherited(subclass) ⇒ Object
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.
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/datev/base.rb', line 28 def initialize(attributes) raise ArgumentError.new('Hash required') unless attributes.is_a?(Hash) @attributes = self.class.default_attributes || {} # 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) @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
.default_attributes ⇒ Object
Returns the value of attribute default_attributes.
4 5 6 |
# File 'lib/datev/base.rb', line 4 def default_attributes @default_attributes 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
12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/datev/base.rb', line 12 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 field_class = const_get("Datev::#{type.to_s.capitalize}Field") self.fields << field_class.new(name, , &block) end |
.field_by_name(name) ⇒ Object
24 25 26 |
# File 'lib/datev/base.rb', line 24 def self.field_by_name(name) self.fields.find { |f| f.name == name } end |
.inherited(subclass) ⇒ Object
6 7 8 9 |
# File 'lib/datev/base.rb', line 6 def inherited(subclass) subclass.fields = self.fields subclass.default_attributes = self.default_attributes end |
Instance Method Details
#[](name) ⇒ Object
51 52 53 54 55 56 |
# File 'lib/datev/base.rb', line 51 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
58 59 60 61 62 63 |
# File 'lib/datev/base.rb', line 58 def output(context=nil) self.class.fields.map do |field| value = @attributes[field.name] field.output(value, context) end end |