Class: JsonDataExtractor
- Inherits:
-
Object
- Object
- JsonDataExtractor
- Defined in:
- lib/src/version.rb,
lib/json_data_extractor.rb
Constant Summary collapse
- VERSION =
'0.0.10'
Instance Attribute Summary collapse
-
#data ⇒ Object
readonly
Returns the value of attribute data.
-
#modifiers ⇒ Object
readonly
Returns the value of attribute modifiers.
Instance Method Summary collapse
- #add_modifier(modifier_name, &block) ⇒ Object
- #extract(schema) ⇒ Object
-
#initialize(json_data, modifiers = {}) ⇒ JsonDataExtractor
constructor
A new instance of JsonDataExtractor.
Constructor Details
#initialize(json_data, modifiers = {}) ⇒ JsonDataExtractor
Returns a new instance of JsonDataExtractor.
7 8 9 10 |
# File 'lib/json_data_extractor.rb', line 7 def initialize(json_data, modifiers = {}) @data = json_data.is_a?(Hash) ? json_data.to_json : json_data # hopefully it's a string; maybe we'll add some validation here @modifiers = modifiers.transform_keys(&:to_sym) # todo address this later end |
Instance Attribute Details
#data ⇒ Object (readonly)
Returns the value of attribute data.
5 6 7 |
# File 'lib/json_data_extractor.rb', line 5 def data @data end |
#modifiers ⇒ Object (readonly)
Returns the value of attribute modifiers.
5 6 7 |
# File 'lib/json_data_extractor.rb', line 5 def modifiers @modifiers end |
Instance Method Details
#add_modifier(modifier_name, &block) ⇒ Object
13 14 15 16 |
# File 'lib/json_data_extractor.rb', line 13 def add_modifier(modifier_name, &block) modifier_name = modifier_name.to_sym unless modifier_name.is_a?(Symbol) modifiers[modifier_name] = block end |
#extract(schema) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/json_data_extractor.rb', line 19 def extract(schema) results = {} schema.each do |key, val| if val.is_a?(Hash) val.transform_keys!(&:to_sym) path = val[:path] modifiers = Array(val[:modifiers] || val[:modifier]).map do |mod| case mod when Symbol, Proc mod when String mod.to_sym else raise ArgumentError, "Invalid modifier: #{mod.inspect}" end end array_type = 'array' == val[:type] nested = val.dup.delete(:schema) else path = val modifiers = [] end extracted_data = JsonPath.on(@data, path) if extracted_data.empty? results[key] = nil else results[key] = apply_modifiers(extracted_data, modifiers) if array_type && nested results[key] = extract_nested_data(results[key], nested) elsif !array_type && nested results[key] = extract_nested_data(results[key], nested).first elsif !array_type && 1 < results[key].size # TODO: handle case where results[key] has more than one item # do nothing for now elsif array_type && !nested # do nothing, it is already an array else results[key] = results[key].first end end end results end |