Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing argument to model method with grape-entity

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 !

like image 288
aherve Avatar asked Oct 27 '25 13:10

aherve


1 Answers

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
like image 156
aherve Avatar answered Oct 30 '25 07:10

aherve