Class: ValueFetcher
- Inherits:
-
Object
- Object
- 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.
16 17 18 19 20 21 22 23 24 |
# File 'lib/serializer/value_fetcher.rb', line 16 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
10 11 12 |
# File 'lib/serializer/value_fetcher.rb', line 10 def self.fetch(attribute, object, serializer) new(attribute, object, serializer).fetch end |
Instance Method Details
#array? ⇒ Boolean
56 57 58 |
# File 'lib/serializer/value_fetcher.rb', line 56 def array? ARRAYS.any? { |match| value.class.to_s.end_with?(match) } end |
#fetch ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/serializer/value_fetcher.rb', line 26 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
43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/serializer/value_fetcher.rb', line 43 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 |