1

I was wondering whether Grape Entity would work for rendering arrays of hashes, I thought I remebered it worked but somehow I cannot get it to work right now, am I doing some obvious mistake? Here's my Entity:

class V1::Entities::Searchresult < Grape::Entity
   expose :_type, as: :type
   expose :_id, as: :id
   expose :_score, as: :score
   expose :highlight
end

In my API I call the rendering like this:

present result['hits']['hits'], with: V1::Entities::Searchresult, :params => params

The 'result['hits']['hits']' is filled with 10 hashes that contain the data. The data is present. However when I look at the result I get:

[
  {
    "type": null,
    "id": null,
    "score": null,
    "highlight": null
  },
  {
    "type": null,
    "id": null,
    "score": null,
    "highlight": null
  },
  ......

Am I doing something wrong, or is this simply not possible. I can't seem to dig up any documentation on the array toppic.

Cheers

Tom

Tom
  • 3,807
  • 4
  • 33
  • 58

1 Answers1

2

I found the error, Grape::Entity::Delegator::HashObject fails to work with hashes that have string keys and not symbols. It cannot extract the values.

  data = []
  result['hits']['hits'].each do |item|
    data << item.symbolize_keys
  end

  present data, with: V1::Entities::Searchresult, :params => params

This workaround ommits the problem. I will also open a github Issue for a fix since a simple

object[attribute] || object[attribute.to_s]

would solve the whole problem instead of only using

object[attribute]

to read the attribute.

Tom
  • 3,807
  • 4
  • 33
  • 58