Module: Attrocity::ModuleMethods
- Defined in:
- lib/attrocity.rb
Instance Method Summary collapse
- #attribute(name, coercer:, default: nil, from: name) ⇒ Object
- #attribute_set ⇒ Object
- #coercer_args(args) ⇒ Object
- #mapper(mapping, default) ⇒ Object
- #model_attribute(name, model:) ⇒ Object
- #model_attribute_set ⇒ Object
- #model_from_mapped_data(data) ⇒ Object
Instance Method Details
#attribute(name, coercer:, default: nil, from: name) ⇒ Object
39 40 41 42 |
# 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 ⇒ Object
67 68 69 |
# File 'lib/attrocity.rb', line 67 def attribute_set @attribute_set ||= AttributeTemplateSet.new end |
#coercer_args(args) ⇒ Object
44 45 46 47 48 49 50 51 |
# 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) ⇒ Object
59 60 61 62 63 64 65 |
# 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:) ⇒ Object
53 54 55 56 57 |
# 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 ⇒ Object
71 72 73 |
# File 'lib/attrocity.rb', line 71 def model_attribute_set @model_attribute_set ||= ModelAttributeSet.new end |
#model_from_mapped_data(data) ⇒ Object
75 76 77 78 79 80 81 82 83 84 85 86 |
# 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 |