1

In my app I will have an ad banner, but it won't be displayed on every page. So, I've defined the ad banner in application controller:

before_action :set_ad_banner

def set_ad_banner
  @ad_banner = Advertising
                   .where('date_start_on <= ? AND date_end_on >= ?', Date.today, Date.today)
                   .order('RAND()')
                   .take
  impressionist(@ad_banner)
end

I use impressionist gem to see, how many times the ad has been displayed. But doing so, as it is set now, will count the impressions every time any of the pages are load, even if there is no content_for tag with the banner. I also tried to move the code to the view, but this code: impressionist(@ad_banner) doesn't work in the view. Any ideas how to solve this issue? Thanks.

Alex Zakruzhetskyi
  • 1,383
  • 2
  • 22
  • 43
  • try using a helper method definition on `ApplicationHelper` rather than instance variable on ApplicationController – sa77 Oct 06 '17 at 12:45
  • If I define a helper, I won't be able to use `imressionist(ad_banner)`. It gives me an error: `undefined method `impressionist' for #<#:0x0000000520e680>` – Alex Zakruzhetskyi Oct 06 '17 at 12:55

1 Answers1

1

For example, you can use

skip_before_action :set_ad_banner, only: [:action1, :action2]

to avoid invocation of this method for some actions in controllers that inherit from your ApplicationController where before_action was defined. Guide here.

For instance:

class PostsController < ApplicationController
  skip_before_action :set_ad_banner, only: [:index]

  def index
    # some code here 
  end

  def show
    # some code here
  end
end

In the above example set_ad_banner won't be invoked before index action, but will be invoked before show.

If you don't want to invoke it at all in some controller, use skip_before_action :set_ad_banner without only/except.

Maksim Kalmykov
  • 1,293
  • 3
  • 20
  • 26
  • On some controllers, I will have the ad banner and on some other controllers, I won't. So setting controller names in `only:` array won't be easy. – Alex Zakruzhetskyi Oct 06 '17 at 12:58
  • @AlexZakruzhetskyi There are actions names in `only` (index, show, etc.), not controllers names. And `skip_before_action` is usually used in descendants of controller where `before_action` was defined. So, in some controllers you will use it, and in some - won't. Check the example with LoginsController in [guides](http://guides.rubyonrails.org/action_controller_overview.html#filters). – Maksim Kalmykov Oct 06 '17 at 13:01