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