Skip to content

Commit

Permalink
Inherit key coercions.
Browse files Browse the repository at this point in the history
  • Loading branch information
Erol authored and dblock committed Dec 28, 2014
1 parent 51299aa commit a493872
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -4,6 +4,7 @@
* [#249](https://github.com/intridea/hashie/pull/249): SafeAssignment will now also protect hash-style assignments - [@jrochkind](https://github.com/jrochkind).
* [#251](https://github.com/intridea/hashie/pull/251): Add block to indifferent access #fetch - [@jgraichen](https://github.com/jgraichen).
* [#252](https://github.com/intridia/hashie/pull/252): Add support for conditionally required Hashie::Dash attributes - [@ccashwell](https://github.com/ccashwell).
* [#256](https://github.com/intridia/hashie/pull/256): Inherit key coercions - [@Erol](https://github.com/Erol).
* Your contribution here.

## 3.3.2 (11/26/2014)
Expand Down
14 changes: 11 additions & 3 deletions lib/hashie/extensions/coercion.rb
Expand Up @@ -86,6 +86,9 @@ def replace(other_hash)
end

module ClassMethods
attr_writer :key_coercions
protected :key_coercions=

# Set up a coercion rule such that any time the specified
# key is set it will be coerced into the specified class.
# Coercion will occur by first attempting to call Class.coerce
Expand All @@ -101,16 +104,15 @@ module ClassMethods
# coerce_key :user, User
# end
def coerce_key(*attrs)
@key_coercions ||= {}
into = attrs.pop
attrs.each { |key| @key_coercions[key] = into }
attrs.each { |key| key_coercions[key] = into }
end

alias_method :coerce_keys, :coerce_key

# Returns a hash of any existing key coercions.
def key_coercions
@key_coercions || {}
@key_coercions ||= {}
end

# Returns the specific key coercion for the specified key,
Expand Down Expand Up @@ -172,6 +174,12 @@ def value_coercion(value)
from = value.class
strict_value_coercions[from] || lenient_value_coercions[from]
end

def inherited(klass)
super

klass.key_coercions = key_coercions
end
end
end
end
Expand Down
15 changes: 15 additions & 0 deletions spec/hashie/extensions/coercion_spec.rb
Expand Up @@ -404,6 +404,21 @@ class TweetHash < MyHash
expect(tweet[:user]).to be_a(UserHash)
end
end

context 'when subclassing' do
class MyHash < Hash
include Hashie::Extensions::Coercion

coerce_key :value, Integer
end

class MySubclass < MyHash
end

it 'inherits key coercions' do
expect(MyHash.key_coercions).to eql(MySubclass.key_coercions)
end
end
end

describe '#coerce_value' do
Expand Down

0 comments on commit a493872

Please sign in to comment.