Gem methods not available inside Grape Api

347 Views Asked by At

I'm currently building my first API with Grape and the Rails 5 api mode and it's going fairly well until now. I decided to install the Impressionist gem to be able to log the view counts of a certain model (future "popular" page) but I'm running into an issue where I feel I have setup the gem correctly but the impressionist method used to actually log the info in the database is undefined.

In my model, the gem is initialized like this is_impressionable :counter_cache => true

I then have in app/api/my_app/my_model.rb

module MyApp
  class MyModel < Grape::API
    # GET /api/v1/model/:slug
    desc "Returns a model record"
    params do
      requires :slug, type: String, desc: "Model slug", allow_blank: false
    end
    route_param :slug do
      get do
        my_model = MyModel.friendly.find(params[:slug])
        impressionist(my_model)
        present my_model, with: MyModelPresenter
      end
    end
  end
end

to log the activity but the impressionist method is undefined. I tried ImpressionistController::ClassMethods.impressionist as well without success. I have other gems like friendly_id and will_paginate which work perfectly out of the box with this setup. Do I have to require something specific ?

1

There are 1 best solutions below

1
On BEST ANSWER

It seems that impressionist does not support Grape:

You can use it manually:

  imp = Impression.new
  imp.impressionable_type = object.class.to_s
  imp.impressionable_id = object.id
  imp.user_id = current_user.nil? ? 0 : current_user.id
  imp.controller_name = "topics"
  imp.action_name = "show"
  imp.request_hash = Digest::SHA2.hexdigest(Time.now.to_f.to_s+rand(10000).to_s)
  imp.ip_address = env['REMOTE_ADDR']
  imp.session_hash = request.session_options[:id]
  imp.referrer = request.referer
  imp.save

https://github.com/charlotte-ruby/impressionist/issues/172#issuecomment-62844576