Sha256: 1b42afe85e9d8c9980f932163b84d58f8b233f19ce83574aa4c1a720b76bb72d

Contents?: true

Size: 1.28 KB

Versions: 3

Compression:

Stored size: 1.28 KB

Contents

require 'datev/field'

module Datev
  class Base
    class << self
      attr_accessor :fields
    end

    attr_accessor :attributes

    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

    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

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

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
datev-0.2.2 lib/datev/base.rb
datev-0.2.1 lib/datev/base.rb
datev-0.2.0 lib/datev/base.rb