module Attrocity::ModuleMethods

Public Instance Methods

attribute(name, coercer:, default: nil, from: name) click to toggle source
# File lib/attrocity.rb, line 39
def attribute(name, coercer:, default: nil, from: name)
  coercer = CoercerRegistry.instance_for(*coercer_args(coercer))
  attribute_set << AttributeTemplate.new(name, coercer, mapper(from, default))
end
attribute_set() click to toggle source
# File lib/attrocity.rb, line 67
def attribute_set
  @attribute_set ||= AttributeTemplateSet.new
end
coercer_args(args) click to toggle source
# File lib/attrocity.rb, line 44
def coercer_args(args)
  if args.is_a?(Symbol)
    [args, {}]
  elsif args.is_a?(Hash)
    name = args.delete(:name)
    [name, args]
  end
end
mapper(mapping, default) click to toggle source
# File lib/attrocity.rb, line 59
def mapper(mapping, default)
  if mapping.respond_to?(:call)
    mapping
  else
    Attrocity.default_mapper.new(mapping, default)
  end
end
model_attribute(name, model:) click to toggle source
# File lib/attrocity.rb, line 53
def model_attribute(name, model:)
  ModelAttribute.new(name, model).tap do |model_attr|
    model_attribute_set << model_attr
  end
end
model_attribute_set() click to toggle source
# File lib/attrocity.rb, line 71
def model_attribute_set
  @model_attribute_set ||= ModelAttributeSet.new
end
model_from_mapped_data(data) click to toggle source
# File lib/attrocity.rb, line 75
def model_from_mapped_data(data)
  attrs = attribute_set.attributes
  self.new(
    Hash.new.tap do |h|
      data.each do |k,v|
        # TODO: Use more efficient enumerable method
        key = attrs.collect { |attr| attr.mapper_key_for(k) }.compact.first
        h[key] = v if key
      end
    end
  ).model
end