Skip to content

Commit

Permalink
Merge pull request #28 from mattfawcett/multiple_coercion
Browse files Browse the repository at this point in the history
Let coerce_key support an array of keys to coerce.
  • Loading branch information
jch committed Feb 12, 2013
2 parents c2815fa + 903045a commit 75ef232
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
12 changes: 8 additions & 4 deletions lib/hashie/extensions/coercion.rb
Expand Up @@ -29,18 +29,22 @@ module ClassMethods
# and then by calling Class.new with the value as an argument
# in either case.
#
# @param [Object] key the key you would like to be coerced.
# @param [Class] into the class into which you want the key coerced.
# @param [Object] key the key or array of keys you would like to be coerced.
# @param [Class] into the class into which you want the key(s) coerced.
#
# @example Coerce a "user" subhash into a User object
# class Tweet < Hash
# include Hashie::Extensions::Coercion
# coerce_key :user, User
# end
def coerce_key(key, into)
(@key_coercions ||= {})[key] = into
def coerce_key(*attrs)
@key_coercions ||= {}
into = attrs.pop
attrs.each { |key| @key_coercions[key] = into }
end

alias :coerce_keys :coerce_key

# Returns a hash of any existing key coercions.
def key_coercions
@key_coercions || {}
Expand Down
9 changes: 9 additions & 0 deletions spec/hashie/extensions/coercion_spec.rb
Expand Up @@ -35,6 +35,15 @@ class ExampleCoercableHash < Hash
instance[:foo].should be_coerced
end

it "should support an array of keys" do
subject.coerce_keys :foo, :bar, Coercable

instance[:foo] = "bar"
instance[:bar] = "bax"
instance[:foo].should be_coerced
instance[:bar].should be_coerced
end

it 'should just call #new if no coerce method is available' do
subject.coerce_key :foo, Initializable

Expand Down

0 comments on commit 75ef232

Please sign in to comment.