Aug 30
Role Based Authentication from Rails Recipes. Part 2
Once I had the user roles code in place, working, and cleaned up, I decided to extend it by allowing regular expressions in the rights instead of literal strings (for controller & action names). Whether I stick with this going forward, who knows… but it’s convenient for development. Instead of separate rights for each action on a controller I can specify .* as the action to have the right apply to all actions for a controller.
Recall that I ended up with the core of the rights checking code actually in the Right class:
class Right < ActiveRecord::Base has_and_belongs_to_many :roles def has_right_for?(action_name, controller_name) action == action_name && controller == controller_name end end
My first step was to wrap Rights attributes in a Regexp and do a match with the requested controller/action names:
class Right < ActiveRecord::Base has_and_belongs_to_many :roles def has_right_for?(action_name, controller_name) get_action_regex.match(action_name) && get_controller_regex.match(controller_name) end def get_action_regex Regexp.new(action) end def get_controller_regex Regexp.new(controller) end end
It might be a case of premature optimization, but the Regexps can easily be cached since they are nicely encapsulated:
class Right < ActiveRecord::Base has_and_belongs_to_many :roles def has_right_for?(action_name, controller_name) get_action_regex.match(action_name) && get_controller_regex.match(controller_name) end def get_action_regex @action_regex || (@action_regex = Regexp.new(action)) end def get_controller_regex @controller_regex || (@controller_regex = Regexp.new(controller)) end end
Part of the reason I blogged this was as an example of how much easier and obvious an enhancement can be when the code is cleanly (and extremely) refactored. More importantly, the details of rights can be changed without anything outside of the Right class being aware of it. If this ability is not one of the core benefits of OO, what is?
Comments Off
