Skip to content

Instantly share code, notes, and snippets.

@vinhnglx
Created January 12, 2016 02:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vinhnglx/9ef5ede01e26ec1e618b to your computer and use it in GitHub Desktop.
Save vinhnglx/9ef5ede01e26ec1e618b to your computer and use it in GitHub Desktop.

============== #rails #tips ​​_[Mẹo hay]_​ Viết filter phức tạp cho rails controller thì nên cho vào Filter class​ Vd nếu bạn cần một filter phức tạp cho before_action, rails có một dạng là nhận vào một class

class ApplicationController < ActionController::Base
  before_action LoginFilter
end
 
class LoginFilter
  def self.before(controller)
    unless controller.send(:logged_in?)
      controller.flash[:error] = "You must be logged in to access this section"
      controller.redirect_to controller.new_login_url
    end
  end
end

Ở trên có thể thấy là class LoginFilter đc truyền vào, lưu ý là ở đây class này có implement before method vì đây là before_ filter, nếu bạn dùng after_ filter thì phải implement after, cuối cùng nếu dùng around filter thì phải implement yield.

Đây là một cách để nhóm các logic phức tạp vào một class và bạn có thể test riêng cái filter này dễ dàng mà không phải hit controller stack

=== END

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment