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.
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
.