grape-entity icon indicating copy to clipboard operation
grape-entity copied to clipboard

How to inject current_user helper to all entity?

Open TangMonk opened this issue 10 years ago • 4 comments

TangMonk avatar Dec 21 '15 07:12 TangMonk

👍 Me, too, I have some configuration information that doesn't directly come from the object that I'd like to pass to the front end as part of the object, how can I get a helper like that? I already have the helper I'd need (or close enough) in Grape, but it's not accessible in grape-entity.

stephancom avatar Nov 28 '17 20:11 stephancom

I needed this recently and what I did was override #present.

Here is the hack 🤖 (as a simplified example):

module API
  class Base < Grape::API
    helpers do
      def present(*args)
        options = args.count > 1 ? args.extract_options! : {}

        options.merge!(user: current_user)

        super(*args, options)
      end
    end
  end
end

module API
  class Entity < ::Grape::Entity
    expose :something, if: ->(object, options) { options[:user].admin? }
  end
end

@stephancom probably you've figured this out by now. In case you haven't you can call the helper in the context of the route and pass any info to the entity with the above (or a similar) approach.

fotos avatar Dec 06 '18 19:12 fotos

not on that project now, don't remember, but yeah, I think I figured something out.

stephancom avatar Dec 07 '18 20:12 stephancom

is any chance the solution provided by @fotos (or some similar) will be added to original source?

pavelbabin avatar Nov 16 '23 14:11 pavelbabin