Class: Serializer::ValueFetcher
- Inherits:
-
Object
- Object
- Serializer::ValueFetcher
- Defined in:
- lib/serializer/value_fetcher.rb
Defined Under Namespace
Classes: SerializerError
Constant Summary collapse
- ARRAYS =
%w[ Array ActiveRecord_AssociationRelation ActiveRecord_Associations_CollectionProxy ].freeze
Class Method Summary collapse
Instance Method Summary collapse
- #array? ⇒ Boolean
- #fetch ⇒ Object
-
#initialize(attribute, object, serializer) ⇒ ValueFetcher
constructor
A new instance of ValueFetcher.
-
#value ⇒ Object
Fetches a value from an attribute by checking if there’s a ..
Constructor Details
#initialize(attribute, object, serializer) ⇒ ValueFetcher
Returns a new instance of ValueFetcher.
17 18 19 20 21 22 23 24 25 |
# File 'lib/serializer/value_fetcher.rb', line 17 def initialize(attribute, object, serializer) @attribute = attribute @values = [ StaticValue.new(attribute), SerializedValue.new(attribute, serializer), HashValue.new(attribute, object), ObjectValue.new(attribute, object) ] end |
Class Method Details
.fetch(attribute, object, serializer) ⇒ Object
11 12 13 |
# File 'lib/serializer/value_fetcher.rb', line 11 def self.fetch(attribute, object, serializer) new(attribute, object, serializer).fetch end |
Instance Method Details
#array? ⇒ Boolean
57 58 59 |
# File 'lib/serializer/value_fetcher.rb', line 57 def array? ARRAYS.any? { |match| value.class.to_s.end_with?(match) } end |
#fetch ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/serializer/value_fetcher.rb', line 27 def fetch serializer = @attribute.serializer return value unless serializer if array? value.map { |item| serializer.new(item).to_h } else serializer.new(value).to_h end end |
#value ⇒ Object
Fetches a value from an attribute by checking if there’s a .. .. static value set, or a .. .. method defined in the serializer, or a .. .. method/attribute defined in the object or .. .. it raises an error
44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/serializer/value_fetcher.rb', line 44 def value @value ||= begin extracted_value = @values.detect(&:precondition?) if extracted_value.nil? raise SerializerError, "unknown attribute '#{@values[0].extraction_key}'" end extracted_value.value end end |