require 'stockboy/attribute'
require 'stockboy/translations'
module Stockboy
class AttributeMap
include Enumerable
class DSL
def initialize(instance)
@attribute_map = instance
end
def method_missing(attr, *args)
@attribute_map.insert(attr, *args)
end
end
def initialize(rows={}, &block)
@map = rows
@unmapped = Hash.new
if block_given?
DSL.new(self).instance_eval(&block)
end
end
def [](key)
@map[key]
end
def insert(key, opts={})
to = key.to_sym
from = opts.fetch(:from, key)
from = from.to_s.freeze if from.is_a? Symbol
translators = Array(opts[:as]).map { |t| Translations.translator_for(to, t) }
ignore_condition = opts[:ignore]
define_singleton_method(key) { @map[key] }
@map[key] = Attribute.new(to, from, translators, ignore_condition)
end
def attribute_from(key)
find { |a| a.from == key } or @unmapped[key] ||= Attribute.new(nil, key, nil)
end
def each(*args, &block)
@map.values.each(*args, &block)
end
end
end