Class: Axn::Core::FieldResolvers::Extract

Inherits:
Object
  • Object
show all
Defined in:
lib/axn/core/field_resolvers/extract.rb

Instance Method Summary collapse

Constructor Details

#initialize(field:, provided_data:, options: {}) ⇒ Extract

Returns a new instance of Extract.



9
10
11
12
13
# File 'lib/axn/core/field_resolvers/extract.rb', line 9

def initialize(field:, provided_data:, options: {})
  @field = field
  @options = options
  @provided_data = provided_data
end

Instance Method Details

#callObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/axn/core/field_resolvers/extract.rb', line 15

def call
  # Hash-like (named-key) sources: read the key. Checked BEFORE the method branch so a key
  # whose name collides with a Hash/Enumerable method (e.g. `zip`, `count`, `first`) is read
  # as a key rather than dispatched as a method call. Arrays respond to #dig too, but only
  # with integer indices, so they stay on the reader path (e.g. `items.count`).
  if provided_data.respond_to?(:dig) && !provided_data.is_a?(Array)
    base = provided_data.respond_to?(:with_indifferent_access) ? provided_data.with_indifferent_access : provided_data
    return base.dig(*field.to_s.split("."))
  end

  # Object/Array sources: use the reader method.
  return provided_data.public_send(field) if provided_data.respond_to?(field)

  raise "Unclear how to extract #{field} from #{provided_data.inspect}"
end