How to present a collection of objects as a Hash keyed by an attribute value?

1,375 views
Skip to first unread message

Dan Hodge

unread,
Sep 14, 2015, 11:09:35 AM9/14/15
to Grape Framework Discussion
Given an Array of objects that conform to an interface like this:

Struct.new(:date, :a, :b)

I'd like to present them in JSON like this:

{ "2015-09-14": { "foo": 1, "bar": 2}, "2015-09-13": { "foo:" 3, "bar": 4 } }

I haven't found a good way in grape-entity to do this.  

This is how I'm currently handling it:

class Thing < Grape::Entity
  def self.expose_hash(options = {})
    @key_proc = options[:key]
    yield
  end

  def self.represent(objects, options = {})
    Hash[
      objects.map do |value|
        [@key_proc.call(value), new(value, options).presented]
      end
    ]
  end

  expose_hash key: proc { |obj| obj.date } do
    expose :a, as: "foo"
    expose :b, as: "bar"
  end
end

Is there a better way to do this? Would adding support for this into grape-entity be useful? I'm happy turn this into a more general solution and open a pull request if so.



thanks,
-Dan

Daniel Doubrovkine

unread,
Sep 14, 2015, 1:33:22 PM9/14/15
to ruby-...@googlegroups.com
In a way this is about defining a dynamic key. I think this could be useful, I'd open an issue at the very least. 



--
You received this message because you are subscribed to the Google Groups "Grape Framework Discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ruby-grape+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--

Dan Hodge

unread,
Sep 14, 2015, 11:06:55 PM9/14/15
to Grape Framework Discussion
I took a stab at the implementation here: https://github.com/ruby-grape/grape-entity/pull/172

Very much a work in progress but any feedback you have would be appreciated.


thanks,
-Dan
Reply all
Reply to author
Forward
0 new messages