Class: ActiveRepresenter::Base
- Inherits:
-
Object
- Object
- ActiveRepresenter::Base
- Includes:
- ActiveModel::Attributes, ActiveModel::Model
- Defined in:
- lib/active_representer/base.rb
Class Method Summary collapse
- .attr_collection(name, **options) ⇒ Object
- .attr_field(name, type = Type::Value.new, **options) ⇒ Object
- .attribute_names ⇒ Object
- .collection_names ⇒ Object
- .guess_representrer_name(name) ⇒ Object
- .wrap(wrapped) ⇒ Object
Class Method Details
.attr_collection(name, **options) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/active_representer/base.rb', line 41 def attr_collection(name, **) unless name.is_a?(Symbol) || name.is_a?(String) raise ArgumentError.new("collection's name must be a Symbol or a String") end representer_name = \ [:representer_name] ? [:representer_name] : guess_representrer_name(name.to_s) raise ArgumentError.new("representer_name must be a String") unless representer_name.is_a?(String) begin representer = representer_name.constantize collections[name.to_sym] = representer rescue NameError => e collections[name.to_sym] = nil end class_eval do attr_reader name.to_sym end end |
.attr_field(name, type = Type::Value.new, **options) ⇒ Object
37 38 39 |
# File 'lib/active_representer/base.rb', line 37 def attr_field(name, type = Type::Value.new, **) attribute(name, type, **) end |
.attribute_names ⇒ Object
63 64 65 |
# File 'lib/active_representer/base.rb', line 63 def attribute_names attribute_types.keys - ["wrapped"] end |
.collection_names ⇒ Object
59 60 61 |
# File 'lib/active_representer/base.rb', line 59 def collection_names collections.keys end |
.guess_representrer_name(name) ⇒ Object
67 68 69 |
# File 'lib/active_representer/base.rb', line 67 def guess_representrer_name(name) "#{name.singularize.camelize}Representer" end |
.wrap(wrapped) ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/active_representer/base.rb', line 17 def wrap(wrapped) instance = new instance.wrapped = wrapped collection_names.each do |collection_name| next if wrapped[collection_name].nil? representer_klass = collections[collection_name] collection_value = \ if representer_klass wrapped[collection_name].map { |item| representer_klass.wrap(item) } else wrapped[collection_name] end instance.instance_variable_set("@#{collection_name}", collection_value) end attribute_names.each do |attribute_name| instance.send("#{attribute_name}=", wrapped.send(attribute_name)) end instance end |