diff options
author | Daniel Doubrovkine (dB.) @dblockdotorg <dblock@dblock.org> | 2014-06-30 16:13:32 -0400 |
---|---|---|
committer | Daniel Doubrovkine (dB.) @dblockdotorg <dblock@dblock.org> | 2014-06-30 16:13:32 -0400 |
commit | c1fad3ba4bb897dfc3a106f85602b1c00a0bfab9 (patch) | |
tree | f6250beb6975a119bb473fd7b658678d10ec63d0 /README.md | |
parent | 2b2cebba7830f13525ccc74b8a7a74ab3bca6b6b (diff) | |
parent | f09c5f68f907659a68fa759e7a7dcd225b7c2078 (diff) | |
download | hashie-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.md | 44 |
1 files changed, 44 insertions, 0 deletions
@@ -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`. |