class BlazerJsonAPI::ResultToNestedJson

Attributes

blazer_result[R]
statement[R]

Public Class Methods

new(statement, blazer_result) click to toggle source
# File lib/blazer_json_api/result_to_nested_json.rb, line 12
def initialize(statement, blazer_result)
  @statement = statement
  @blazer_result = blazer_result
end

Public Instance Methods

call() click to toggle source
# File lib/blazer_json_api/result_to_nested_json.rb, line 17
def call
  transformed_result =
    blazer_result_to_json(blazer_result).each do |hash|
      hash.keys.select { |key| key =~ /#{nesting_column_separator}/ }.each do |namespaced_key|
        nested_keys = namespaced_key.to_s.split(nesting_column_separator)
        hash.deep_merge!(deep_hash_set(*nested_keys[0..nested_keys.size], hash[namespaced_key]))
        hash.delete(namespaced_key)
      end
    end
  collection_or_single_record(transformed_result)
end

Private Instance Methods

blazer_result_to_json(blazer_result) click to toggle source
# File lib/blazer_json_api/result_to_nested_json.rb, line 31
def blazer_result_to_json(blazer_result)
  blazer_result.rows.map do |row|
    row_hash = {}
    row.each_with_index do |value, value_index|
      row_hash[blazer_result.columns[value_index]] = value
    end
    row_hash
  end
end
collection_or_single_record(result) click to toggle source

Use the presence of LIMIT 1 in the query to decide whether to render a collection response (like an index) or a single entry response

# File lib/blazer_json_api/result_to_nested_json.rb, line 52
def collection_or_single_record(result)
  /LIMIT 1$/i.match?(statement) ? result.first : result
end
deep_hash_set(*keys, value) click to toggle source

recursively sets a nested key in a hash (like the opposite to Hash.dig) e.g. deep_hash_set(*[‘a’, ‘b’ , ‘c’], 4) { a => { b => { c => 4 } } } @return Hash

# File lib/blazer_json_api/result_to_nested_json.rb, line 45
def deep_hash_set(*keys, value)
  keys.empty? ? value : { keys.first => deep_hash_set(*keys.drop(1), value) }
end