Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How skip config.middleware.use for a specific controller action in Rails 5

Tags:

Is there a way to setup config.middleware.use to exclude / ignore / skip a specific controller action?

For example, if I wanted to exclude the Post#show controller action.

I'm using https://github.com/railslove/rack-tracker to test Google Analytics/Tag Manager.

  # Rack Tracker config
  config.middleware.use(Rack::Tracker) do
    handler :google_tag_manager, { container: ENV['GTM_CONTAINER_ID'] }
  end

I thought I could use a condition like:

  # Rack Tracker config
  config.middleware.use(Rack::Tracker) do
    handler :google_tag_manager, { container: ENV['GTM_CONTAINER_ID'] } if app.route != ApplicationController::PostController.show
  end

Any help is much appreciated.

like image 608
Wasabi Developer Avatar asked Feb 01 '17 13:02

Wasabi Developer


1 Answers

You can provide a lambda to the container option:

config.middleware.use(Rack::Tracker) do
  handler :google_tag_manager, { container: lambda { |env| ENV['GTM_CONTAINER_ID'] if env['REQUEST_PATH'].match(/\/posts\/\d+/) } }
end

This lambda will be evaluated in each request and give you access to the env object. With that you can return a string for the google tag manager container based on the current request path.

like image 181
pedrosfdcarneiro Avatar answered Sep 25 '22 09:09

pedrosfdcarneiro