summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJerry Cheung <jollyjerry@gmail.com>2013-02-11 16:27:59 -0800
committerJerry Cheung <jollyjerry@gmail.com>2013-02-11 16:27:59 -0800
commit75ef232210e699d58299975422328374db2341f4 (patch)
treebf548d9d74102393585581b060cab98865918638
parentc2815fa066da9c29aae1c8655eb64bad44ac5fc9 (diff)
parent903045ac84bc5d39a195768f821e43830fdd88b9 (diff)
downloadhashie-75ef232210e699d58299975422328374db2341f4.tar.gz
Merge pull request #28 from mattfawcett/multiple_coercion
Let coerce_key support an array of keys to coerce.
-rw-r--r--lib/hashie/extensions/coercion.rb12
-rw-r--r--spec/hashie/extensions/coercion_spec.rb9
2 files changed, 17 insertions, 4 deletions
diff --git a/lib/hashie/extensions/coercion.rb b/lib/hashie/extensions/coercion.rb
index 848abe1..67ad607 100644
--- a/lib/hashie/extensions/coercion.rb
+++ b/lib/hashie/extensions/coercion.rb
@@ -29,18 +29,22 @@ module Hashie
# 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 || {}
diff --git a/spec/hashie/extensions/coercion_spec.rb b/spec/hashie/extensions/coercion_spec.rb
index 84a662d..8dcf6fd 100644
--- a/spec/hashie/extensions/coercion_spec.rb
+++ b/spec/hashie/extensions/coercion_spec.rb
@@ -35,6 +35,15 @@ describe Hashie::Extensions::Coercion do
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