Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Coercing collections? #176

Closed
maxlinc opened this issue Jun 24, 2014 · 3 comments
Closed

Coercing collections? #176

maxlinc opened this issue Jun 24, 2014 · 3 comments

Comments

@maxlinc
Copy link
Contributor

maxlinc commented Jun 24, 2014

I find myself coercing collections fairly often. I haven't figured out an easy way to do this with Hashie, but maybe one exists and just isn't obvious.

Here is an example of something similar from roar:

module AlbumRepresenter
  include Roar::Representer::JSON

  property :title
  collection :songs, extend: SongRepresenter, class: Song
end

I usually end up doing something like this, since Hashie's coercion doesn't seem to have any built-in support for collections/arrays:

require 'hashie'

class User < Hashie::Mash; end

class Users < Set
  # Custom coercion for Hashie to handle collection
  def self.coerce(obj)
    data = obj.map do |value|
      User.new(value)
    end
    new data
  end
end

class Tweet < Hashie::Mash
  include Hashie::Extensions::Coercion
  coerce_key :user, User
  coerce_key :mentions, Users
end

larry = { name: "Larry" }
moe = { name: "Moe" }
curly = { name: "Curly" }
tweet = Tweet.new(user: larry, mentions: [moe, curly])
puts tweet.inspect
#<Tweet mentions=#<Users: {#<User name="Moe">, #<User name="Curly">}> user=#<User name="Larry">>

Is there a simpler way to do this that doesn't require the extra class and coerce method?

@dblock
Copy link
Member

dblock commented Jun 25, 2014

I don't think there's a simpler way, but lets leave this as a feature request. I am open to a PR that makes this easier!

@gregory
Copy link
Contributor

gregory commented Jul 3, 2014

@dblock & @maxlinc sounds like this PR can be closed now right?

@dblock
Copy link
Member

dblock commented Jul 3, 2014

Yep, thx.

@dblock dblock closed this as completed Jul 3, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants