Class: Seri::Serializer::ValueFetcher
- Inherits:
-
Object
- Object
- Seri::Serializer::ValueFetcher
- Defined in:
- lib/serializer/value_fetcher.rb
Defined Under Namespace
Classes: SerializerError
Class Method Summary collapse
Instance Method Summary collapse
- #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.
12 13 14 15 16 17 18 19 20 |
# File 'lib/serializer/value_fetcher.rb', line 12 def initialize(attribute, object, serializer) @attribute = attribute @values = [ StaticValue.new(attribute), SerializedValue.new(attribute, serializer), HashValue.new(attribute, object), SerializedValue.new(attribute, object) ] end |
Class Method Details
.fetch(attribute, object, serializer) ⇒ Object
6 7 8 |
# File 'lib/serializer/value_fetcher.rb', line 6 def self.fetch(attribute, object, serializer) new(attribute, object, serializer).fetch end |
Instance Method Details
#fetch ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/serializer/value_fetcher.rb', line 22 def fetch serializer = @attribute.serializer return value unless serializer if value.is_a?(Enumerable) && !value.is_a?(Hash) 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
39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/serializer/value_fetcher.rb', line 39 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 |