Skip to content

Commit

Permalink
Support Thor::CoreExt::HashWithIndifferentAccess#except
Browse files Browse the repository at this point in the history
This PR supports `Thor::CoreExt::HashWithIndifferentAccess#except`
and prevents breaking changes in Rails upgrades when using
`options.except(:key)` in Thor task.

When Thor is used with Rails (Active Support), the behavior changes as follows.

## With Rails 5.2 or lower

```ruby
h = Thor::CoreExt::HashWithIndifferentAccess.new(foo: 1, bar: 2)
h.except(:foo) #=> {"bar"=>2}
```

## With Rails 6.0

```ruby
h = Thor::CoreExt::HashWithIndifferentAccess.new(foo: 1, bar: 2)
h.except(:foo) #=> {"foo"=>1, "bar"=>2}
```

This difference behavior is due to the following changes in Rails 6.0.
rails/rails#35771

This PR makes the behavior between Rails 5.2 and Rails 6.0 compatible.
  • Loading branch information
koic committed Jul 30, 2020
1 parent 34df888 commit e00a585
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/thor/core_ext/hash_with_indifferent_access.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ def delete(key)
super(convert_key(key))
end

def except(*keys)
dup.tap do |hash|
keys.each { |key| hash.delete(convert_key(key)) }
end
end

def fetch(key, *args)
super(convert_key(key), *args)
end
Expand Down
11 changes: 11 additions & 0 deletions spec/core_ext/hash_with_indifferent_access_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,17 @@
expect(@hash.delete(:foo)).to eq("bar")
end

it "supports except" do
unexcepted_hash = @hash.dup
@hash.except("foo")
expect(@hash).to eq(unexcepted_hash)

expect(@hash.except("foo")).to eq("baz" => "bee", "force" => true)
expect(@hash.except("foo", "baz")).to eq("force" => true)
expect(@hash.except(:foo)).to eq("baz" => "bee", "force" => true)
expect(@hash.except(:foo, :baz)).to eq("force" => true)
end

it "supports fetch" do
expect(@hash.fetch("foo")).to eq("bar")
expect(@hash.fetch("foo", nil)).to eq("bar")
Expand Down

0 comments on commit e00a585

Please sign in to comment.