Sha256: 0bc9a67a491c0939ad6902bd716bc7da400f37fc2c21b9257c4c201404b3fa0d

Contents?: true

Size: 1.94 KB

Versions: 1

Compression:

Stored size: 1.94 KB

Contents

require "crazy_hash_filter/version"
require "active_support/core_ext/hash/indifferent_access.rb"
require "crazy_hash_filter/core_ext/hash"

module CrazyHashFilter

  def self.process(hash, rules)
    return nil if hash.nil?

    raise "Is not a Hash" unless hash.is_a?(Hash)

    rules       = HashWithIndifferentAccess.new(rules || {}) unless rules.is_a?(HashWithIndifferentAccess)
    child_rules = rules[:child_rules] || {}
    result      = {}
    select      = rules[:select].collect(&:to_sym) unless rules[:select].nil?

    hash.each do |key, value|
      next if !select.nil? && !select.include?(key.to_sym)

      if child_rules[key].nil?
        result[key] = value
      else
        if value.is_a?(Array)
          result[key] = self.filter_array(value, child_rules[key])
        else
          result[key] = self.process(value, child_rules[key])
        end
      end
    end

    result
  end

  private

  def self.filter_array(array, rules)
    result      = []
    conditions  = rules[:conditions] || {}

    array.each do |value|
      result << self.process(value, rules) if match_conditions(value, conditions)
    end

    result
  end

  def self.match_conditions(value, conditions)
    indifferent_value = HashWithIndifferentAccess.new(value)

    conditions.inject(true) do |b, r|
      key, match = r

      if match.is_a?(Array)
        b & self.is_value_in_array?(indifferent_value[key], match)
      else
        b & self.values_match?(indifferent_value[key], match)
      end
    end
  end

  def self.is_value_in_array?(value, array)
    array.each do |v|
      return true if self.values_match?(v, value)
    end

    return false
  end

  def self.values_match?(a, b)
    a == self.equalize_type(b, a)
  end

  def self.equalize_type(value, target)
    if target.is_a?(Integer) && value.is_a?(String)
      return value.to_i
    elsif target.is_a?(String) && value.is_a?(Integer)
      return value.to_s
    else
      return value
    end
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
crazy_hash_filter-0.0.3 lib/crazy_hash_filter.rb