Search code examples
ruby-on-railsattr-accessor

attr_accessor in controller for storing permissions


I'm using attr_accessor in my controllers to store permissions which are set in a method defined in the applicationController but I'm having issues. If I do this:

class ApplicationController < ActionController::Base

    attr_accessor :perms

    def self.set_permissions *permissions
      self.perms = permissions
    end

    def check_permissions
        print self.perms
    end

end

Then rails claims that perms= doesn't exist

if I do:

class ApplicationController < ActionController::Base

    attr_accessor :perms

    def self.set_permissions *permissions
      @perms = permissions
    end

    def check_permissions
        print @perms
    end
end

@perms in check_permissions is nil in any child controller, I checked for what instance methods are available using: print self.instance_variables but @perms didn't show up; probably because @perms is being set for the class instance but not the object instance of the controller that's created when the action is called

Whats going on? Does rails not like attr_accessor on controllers? How can I get this to work so I can set permissions within the class and have them accessible to any objects of that class so I can set them like this:

class Api::ApiController < ApplicationController

    set_permissions :api
    before_action :check_permissions, except: :set_permissions

end

I have to use self.set_permissions, otherwise It claims that set_permissions doesn't exist when I try to set them (because it's an object method not a class method)

EDIT: For clarification, I want the permissions to be set in the controller (but be different for each controller); be the same for any instance's of that controller (I.e. object instance created for an action) or any controllers that inherit from that controller (e.g. node controller inherits from api controller and so uses the same permissions) unless it's been defined within that inherited controller separately (tokens controller inherits from api controller but need to be permission free so a person can actually get a token without needing permissions).


Solution

  • You are defining

    def self.set_permissions *permissions
      self.perms = permissions
    end
    

    which is a class level method, while attr_accessor is at instance level.

    If you wish to set class level permissions I suggest you to use cattr_accessor. Check its instance_reader and instance_writer options too.