Sha256: b63d03434aa3583aef600c8d502adf2d70e6446ec6d1ee3fa467642b71a7d99f

Contents?: true

Size: 996 Bytes

Versions: 4

Compression:

Stored size: 996 Bytes

Contents

module MrSpeedyRuby
  module Lib
    # Hash Module Refinement
    # https://medium.com/rubycademy/refine-and-using-methods-in-ruby-part-i-2aef6d7a4325
    module HashRefinement
      extend self

      def symbolize_recursive(hash)
        {}.tap do |h|
          hash.each { |key, value| h[key.to_sym] = transform(value) }
        end
      end

      private

      def transform(thing)
        case thing
        when Hash; symbolize_recursive(thing)
        when Array; thing.map { |v| transform(v) }
        else; thing
        end
      end

      refine Hash do
        def deep_symbolize_keys
          HashRefinement.symbolize_recursive(self)
        end

        # Ensure Hash parameters are completed
        # https://coderwall.com/p/ne7owq/validating-hash-params-in-ruby
        def assert_required_keys(*keys)
          keys.flatten.each do |key|
            raise ArgumentError, "Required key: #{key.inspect}" unless key?(key)
          end
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
mr_speedy_ruby-1.0.0.pre.alpha.6 lib/mr_speedy_ruby/lib/hash_refinement.rb
mr_speedy_ruby-1.0.0.pre.alpha.4 lib/mr_speedy_ruby/lib/hash_refinement.rb
mr_speedy_ruby-1.0.0.pre.alpha.3 lib/mr_speedy_ruby/lib/hash_refinement.rb
mr_speedy_ruby-1.0.0.pre.alpha.2 lib/mr_speedy_ruby/lib/hash_refinement.rb