Class: HalInterpretation::Extractor

Inherits:
Object
  • Object
show all
Defined in:
lib/hal_interpretation/extractor.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ Extractor

opts - named args

:attr - name of attribute this object will extact.

:location - JSON path from which to get the value.

:extraction_proc - Callable that can extract the value when
  passed a HalClient::Representation of the item.

:coercion - proc to pass the extracted value through before
  storing it.


15
16
17
18
19
20
21
22
23
# File 'lib/hal_interpretation/extractor.rb', line 15

def initialize(opts)
  @attr = opts.fetch(:attr) { fail ArgumentError, "attr is required" }
  @location = opts.fetch(:location) { "/#{attr}" }
  @fetcher = opts.fetch(:extraction_proc) { Hana::Pointer.new(location).method(:eval) }
  @value_coercion = opts.fetch(:coercion) { IDENTITY }

  fail(ArgumentError, ":coercion must respond to #call") unless
    value_coercion.respond_to? :call
end

Instance Attribute Details

#attrObject (readonly)

Returns the value of attribute attr.



51
52
53
# File 'lib/hal_interpretation/extractor.rb', line 51

def attr
  @attr
end

#locationObject (readonly)

Returns the value of attribute location.



51
52
53
# File 'lib/hal_interpretation/extractor.rb', line 51

def location
  @location
end

Instance Method Details

#extract(opts) ⇒ Object

opts - named args

:from - The HalRepresentation from which to extract attribute.

:to - The model that we are extracting

:context - The context(usually a HalInterpreter) in which to
  execute the extraction

Returns any problems encountered.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/hal_interpretation/extractor.rb', line 34

def extract(opts)
  from = opts.fetch(:from) { fail ArgumentError, "from is required" }
  to = opts.fetch(:to) { fail ArgumentError, "to is required" }
  context = opts.fetch(:context, self)

  raw_val = context.instance_exec from, &fetcher
  return [] unless raw_val

  val = context.instance_exec raw_val, &value_coercion

  to.public_send "#{attr}=", val

  []
rescue => err
  [err.message]
end