Class: ExtraLoop::JsonExtractor

Inherits:
ExtractorBase show all
Defined in:
lib/extraloop/json_extractor.rb

Instance Attribute Summary

Attributes inherited from ExtractorBase

#field_name

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ JsonExtractor

Returns a new instance of JsonExtractor.



4
5
6
7
# File 'lib/extraloop/json_extractor.rb', line 4

def initialize(*args)
  @path = args[2] && args[2].is_a?(Array) ? args[2] : nil
  super(*args)
end

Instance Method Details

#extract_field(node, record = nil) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/extraloop/json_extractor.rb', line 9

def extract_field(node, record=nil)
  output = node = node.is_a?(String) ? parse(node) : node
  output = node.get_in(@path) if @path
  output = node[@attribute.to_s] if @attribute
  output = @environment.run(output, record, &@callback) if @callback

  # when no attribute and no callback is provided, try fetching by field name
  if !@attribute && !@callback  
   output = node[@field_name.to_s] if node[@field_name.to_s]
  end
  output
end

#extract_list(input) ⇒ Object



22
23
24
25
26
# File 'lib/extraloop/json_extractor.rb', line 22

def extract_list(input)
  @environment.document = input = (input.is_a?(String) ? parse(input) : input)
  input = input.get_in(@path) if @path
  Array(@callback && @environment.run(input, &@callback) || input)
end

#parse(input) ⇒ Object



28
29
30
31
# File 'lib/extraloop/json_extractor.rb', line 28

def parse(input)
  super(input)
  @environment.document = (Yajl::Parser.new).parse(input).extend(Utils::DeepFetchable)
end