summaryrefslogtreecommitdiff
path: root/README.md
diff options
context:
space:
mode:
authorDaniel Doubrovkine (dB.) @dblockdotorg <dblock@dblock.org>2014-06-30 16:13:32 -0400
committerDaniel Doubrovkine (dB.) @dblockdotorg <dblock@dblock.org>2014-06-30 16:13:32 -0400
commitc1fad3ba4bb897dfc3a106f85602b1c00a0bfab9 (patch)
treef6250beb6975a119bb473fd7b658678d10ec63d0 /README.md
parent2b2cebba7830f13525ccc74b8a7a74ab3bca6b6b (diff)
parentf09c5f68f907659a68fa759e7a7dcd225b7c2078 (diff)
downloadhashie-c1fad3ba4bb897dfc3a106f85602b1c00a0bfab9.tar.gz
Merge pull request #177 from gregory/issues_176_coercing_collection
Porposition for Issues 176 - coerce collections
Diffstat (limited to 'README.md')
-rw-r--r--README.md44
1 files changed, 44 insertions, 0 deletions
diff --git a/README.md b/README.md
index 5279f7b..e2d22e6 100644
--- a/README.md
+++ b/README.md
@@ -52,6 +52,50 @@ class SpecialHash < Hash
end
```
+### Coercing Collections
+
+```ruby
+class Tweet < Hash
+ include Hashie::Extensions::Coercion
+ coerce_key :mentions, Array[User]
+ coerce_key :friends, Set[User]
+end
+
+user_hash = { name: "Bob" }
+mentions_hash= [user_hash, user_hash]
+friends_hash = [user_hash]
+tweet = Tweet.new(mentions: mentions_hash, friends: friends_hash)
+# => automatically calls User.coerce(user_hash) or
+# User.new(user_hash) if that isn't present on each element of the array
+
+tweet.mentions.map(&:class) # => [User, User]
+tweet.friends.class # => Set
+```
+
+### Hash attributes Coercion
+
+```ruby
+class Relation
+ def initialize(string)
+ @relation = string
+ end
+end
+
+class Tweet < Hash
+ include Hashie::Extensions::Coercion
+ coerce_key :relations, Hash[User => Relation]
+end
+
+user_hash = { name: "Bob" }
+relations_hash= { user_hash => "father", user_hash => "friend" }
+tweet = Tweet.new(relations: relations_hash)
+tweet.relations.map { |k,v| [k.class, v.class] } # => [[User, Relation], [User, Relation]]
+tweet.relations.class # => Hash
+
+# => automatically calls User.coerce(user_hash) on each key
+# and Relation.new on each value since Relation doesn't define the `coerce` class method
+```
+
### KeyConversion
The KeyConversion extension gives you the convenience methods of `symbolize_keys` and `stringify_keys` along with their bang counterparts. You can also include just stringify or just symbolize with `Hashie::Extensions::StringifyKeys` or `Hashie::Extensions::SymbolizeKeys`.