Question

How can I pass an argument to a model method using grape entity ?

I'd like to check wheter the current_user likes an item when presenting the item, so I built a model user_likes? method:

class Item
  include Mongoid::Document
  #some attributes here...
  has_and_belongs_to_many :likers

  def user_likes?(user)
    likers.include?(user)
  end
end

but I don't know how to send current_user to the grape-entity model :

module FancyApp
  module Entities
    class Item < Grape::Entity
      expose :name #easy
      expose :user_likes # <= How can I send an argument to this guy ?
    end 
  end
end

in the grape api:

get :id do
  item = Item.find(.....)
  present item, with: FancyApp::Entities::Item # I should probably send current_user here, but how ?
end

I feel like the current_user should probably be sent from this last piece of code, but I can't figure how to do it :(

Any thoughts ? Thanks !

Was it helpful?

Solution

Well, I found I could pass current as a parameters, and use it in a block. So :

present item, with: FancyApp::Entities::Item, :current_user => current_user 

and in the entity definition:

expose :user_likes do |item,options|
  item.user_likes?(options[:current_user])
end

OTHER TIPS

@aherve, for some reason your syntax won't work in my case. The syntax in Grape Entity docs is a little different

your example, the syntax should be:

expose(:user_likes) { |item, options| item.user_likes?(options[:current_user]) }

Another way would be to store the current user in the item temporarily by defining an attribute accessor:

class Item
  include Mongoid::Document
  #some attributes here...
  has_and_belongs_to_many :likers
  attr_accessor :current_user

  def user_likes
    likers.include?(current_user)
  end
end

and in the grape api set the current user:

get :id do
  item = Item.find(.....)
  item.current_user = current_user
  present item, with: FancyApp::Entities::Item
end

no changes to the grape-entity model is needed.
There is no database field current_user_id or so. No writes to database.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top