Rails Filter
Filter
Action method before, after both
before around after
before / after
Example
class ExampleController < ApplicationController
before_action :start_logger
after_action :end_logger
def index
end
private
def start_logger
logger.debug('[Start]' + Time.now.to_s)
end
def end_logger
logger.debug('[Finish]' + Time.now.to_s)
end
end
[/ruby]
Use before_action as before filter,
and after_action as around filter.
around
class ExampleController < ApplicationController around_action :around_logger def index end private def around_logger # Before logger.debug('[Start]' + Time.now.to_s) yield # Execute Action # After logger.debug('[Finish]' + Time.now.to_s) end end [/ruby]
Filter range
only, except
class ExampleController < ApplicationController before_action :start_logger, only: [:index, :index2] after_action :end_logger, except: :index end [/ruby]
Skip inherited filter
Skip inherited filter
class ExampleExController < ExampleController skip_before_action :my_log # my_log belongs parent controller skip_after_action :my_after_log, only: :index end [/ruby]
Filter Example
class ExampleController < ApplicationController before_action :auth, only: :index private def auth # username / password name = 'username' passwd = 'xxxxxxxxxx' authenticate_or_request_with_http_basic('Application') do |n, p| n == name && Digest::SHA1.hsxdigest(p) == passwd end end [/ruby]