Skip to content

Commit

Permalink
Change to provide indifferent access to parsed params
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrmurach committed Apr 21, 2020
1 parent 1b1cd0f commit 6bbe8fb
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
20 changes: 16 additions & 4 deletions lib/tty/option/params.rb
Expand Up @@ -8,25 +8,36 @@ class Params
extend Forwardable

def_delegators :@parameters,
:keys, :key?, :has_key?, :member?, :value?, :has_value?, :empty?,
:include?, :each_key, :each_value
:keys, :key?, :has_key?, :member?, :value?, :has_value?,
:empty?, :include?, :each_key, :each_value

def initialize(parameters = {})
@parameters = parameters

@parameters.default_proc = ->(hash, key) do
return hash[key] if hash.key?(key)

case key
when Symbol
hash[key.to_s] if hash.key?(key.to_s)
when String
hash[key.to_sym] if hash.key?(key.to_sym)
end
end
end

# Access a given value for a key
#
# @api public
def [](key)
@parameters[key.to_sym]
@parameters[key]
end

# Assign value to a key
#
# @api public
def []=(key, value)
@parameters[key.to_sym] = value
@parameters[key] = value
end

# Access a given value for a key
Expand All @@ -49,6 +60,7 @@ def merge!(other_params)

def ==(other)
return false unless other.kind_of?(TTY::Option::Params)

@parameters == other.to_h
end
alias eql? ==
Expand Down
4 changes: 3 additions & 1 deletion spec/unit/params_spec.rb
Expand Up @@ -2,10 +2,12 @@

RSpec.describe TTY::Option::Params do
it "allows indifferent access to keys via has like syntax" do
params = described_class.new({foo: "bar"})
params = described_class.new({foo: "bar", "baz" => :qux})

expect(params[:foo]).to eq("bar")
expect(params["foo"]).to eq("bar")
expect(params[:baz]).to eq(:qux)
expect(params["baz"]).to eq(:qux)
end

it "allows indifferent access to keys via fetch" do
Expand Down

0 comments on commit 6bbe8fb

Please sign in to comment.