module Hibp::Helpers::JsonConversion

Hibp::Helpers::JsonConversion

Used to convert raw API response data to the entity models

Protected Instance Methods

convert(data, &block) click to toggle source

Convert raw data to the entity model

@param data [Array<Hash>, Hash] - Raw data from response

# File lib/hibp/helpers/json_conversion.rb, line 16
def convert(data, &block)
  data.is_a?(Array) ? convert_to_list(data, &block) : convert_to_entity(data, &block)
end

Private Instance Methods

convert_to_entity(data) { |attributes| ... } click to toggle source
# File lib/hibp/helpers/json_conversion.rb, line 26
def convert_to_entity(data)
  attributes = data.each_with_object({}) do |(key, value), hash|
    hash[transform_key(key)] = value
  end

  yield(attributes)
end
convert_to_list(data, &block) click to toggle source
# File lib/hibp/helpers/json_conversion.rb, line 22
def convert_to_list(data, &block)
  data.map { |d| convert_to_entity(d, &block) }
end
transform_key(key) click to toggle source
# File lib/hibp/helpers/json_conversion.rb, line 34
def transform_key(key)
  underscore(key.to_s).to_sym
end
underscore(camel_cased_word) click to toggle source
# File lib/hibp/helpers/json_conversion.rb, line 38
def underscore(camel_cased_word)
  camel_cased_word.gsub(/::/, '/')
                  .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
                  .gsub(/([a-z\d])([A-Z])/, '\1_\2')
                  .tr('-', '_')
                  .downcase
end