How can I make the before_filter function behave differently according to the action?

I am trying to make the authentication / permission code a bit more concise.

I currently have this:

  def index
      require_role "normal" do
          @projects = Project.all
          respond_to do |format|
              format.html 
          end
      end
  end

where it require_rolehandles permission checks and redirects to the error page if you are trying to do something you shouldn't.

I would just add something like this to the top of each controller:

require_role "admin", [:delete]
require_role "normal", [:edit, :new, :create]
require_role "guest", [:show, :index]

defined something like:

 def self.require_perm( role_name, actions )
    before_filter :require_perm_admin, :only => actions
 end

The only problem is that I need to hard write the name of the method require_perm_admin. This means that if I ever add new roles, I will need to define a method for each of them.

Is it possible to add dynamically named methods to a class? e.g. check_role_admin, check_role_guest, etc.

, before_filter?

+3
2

, , , action_name before_filter. , , :)

+2

-

def self.require_perm( role_name, actions )
    before_filter "require_perm_#{role_name}".to_sym, :only => actions
end
+1

Source: https://habr.com/ru/post/1785945/


All Articles