Sha256: d8c8e92e70dbaa9edb50f0258bfb82e1b50964c391ca5d6ee069e44ce664d208

Contents?: true

Size: 530 Bytes

Versions: 5

Compression:

Stored size: 530 Bytes

Contents

module InputSanitizer
  class KeyNotAllowedError < ArgumentError; end

  class RestrictedHash < Hash
    def initialize(allowed_keys)
      @allowed_keys = allowed_keys
      super() { |hash, key| default_for_key(key) }
    end

    def key_allowed?(key)
      @allowed_keys.include?(key)
    end

    private
    def default_for_key(key)
      key_allowed?(key) ? nil : raise_not_allowed(key)
    end

    def raise_not_allowed(key)
      msg = "Key not allowed: #{key}"
      raise KeyNotAllowedError.new(msg)
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
input_sanitizer-0.2.2 lib/input_sanitizer/restricted_hash.rb
input_sanitizer-0.2.0 lib/input_sanitizer/restricted_hash.rb
input_sanitizer-0.1.10 lib/input_sanitizer/restricted_hash.rb
input_sanitizer-0.1.9 lib/input_sanitizer/restricted_hash.rb
input_sanitizer-0.1.8 lib/input_sanitizer/restricted_hash.rb