Sha256: e67497879bcd2e173c2f9ab68cd24bf587a5bdebeb19ddb755eb749b400976cb

Contents?: true

Size: 1.03 KB

Versions: 17

Compression:

Stored size: 1.03 KB

Contents

module NxtSupport
  module HashTranslator
    class HashTranslationService
      class InvalidTranslationArgument < StandardError; end

      require 'nxt_init'

      include NxtInit
      attr_init :hash, :tuples

      def call
        tuples.inject(hash.with_indifferent_access) do |acc, (old_key, new_key)|
          if new_key.is_a?(Hash)
            raise InvalidTranslationArgument.new("#{new_key} hash must contain only 1 key-value pair!") if new_key.size > 1
            key, value = new_key.shift
            raise InvalidTranslationArgument.new("#{value} must be a callable block!") unless value.respond_to?(:call)
            acc[key] = value.call(acc.delete(old_key))
          elsif new_key.is_a?(Array)
            value = acc.delete(old_key)
            new_key.each { |key| acc[key] = value }
          else
            acc[new_key] = acc.delete(old_key)
          end

          acc
        end
      end
    end

    def translate_hash(hash, **tuples)
      HashTranslationService.new(hash: hash, tuples: tuples).call
    end
  end
end

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
nxt_support-0.6.0 lib/nxt_support/util/hash_translator.rb
nxt_support-0.5.0 lib/nxt_support/util/hash_translator.rb
nxt_support-0.4.3 lib/nxt_support/util/hash_translator.rb
nxt_support-0.4.2 lib/nxt_support/util/hash_translator.rb
nxt_support-0.4.1 lib/nxt_support/util/hash_translator.rb
nxt_support-0.4.0 lib/nxt_support/util/hash_translator.rb
nxt_support-0.3.0 lib/nxt_support/util/hash_translator.rb
nxt_support-0.2.1 lib/nxt_support/util/hash_translator.rb
nxt_support-0.2.0 lib/nxt_support/util/hash_translator.rb
nxt_support-0.1.16 lib/nxt_support/util/hash_translator.rb
nxt_support-0.1.15 lib/nxt_support/util/hash_translator.rb
nxt_support-0.1.9 lib/nxt_support/util/hash_translator.rb
nxt_support-0.1.8 lib/nxt_support/util/hash_translator.rb
nxt_support-0.1.7 lib/nxt_support/util/hash_translator.rb
nxt_support-0.1.6 lib/nxt_support/util/hash_translator.rb
nxt_support-0.1.5 lib/nxt_support/util/hash_translator.rb
nxt_support-0.1.4 lib/nxt_support/util/hash_translator.rb