Apr 10, 2009

Get all controllers and actions in Merb

When I was implementing our home-grown authorization system, I have to know what controllers are available, for the given controller, what actions are available. This shouldn't difficult using reflection within Ruby. But after reading the source code of Merb, I found it is dead simple to get what you want:

- Application.subclasses_list
- YourController.callable_actions

Here is the code in my Role modle:

...
def self.available_controllers(name)
roles = Role.all(:name => name, :authorizable_type.not => nil)
exists_controllers = roles.collect{|r| r.authorizable_type}
controllers = Application.subclasses_list.to_a.sort
controllers - exists_controllers
end
def authorizable_class
return nil if authorizable_type.nil?
klass = begin
authorizable_type.split("::").inject(Object){|x, y| x.const_get(y)}
rescue NameError => e
msg = "Class not found: `#{authorizable_type}'"
Merb.logger.warn!(msg)
nil
end
end
...
def callable_actions
klass = authorizable_class
# make sure is a controller
return [] if klass.nil? || !klass.respond_to?(:callable_actions)
# get the supper class's actions out your way
actions = klass.callable_actions.keys - klass.superclass.callable_actions.keys
actions.sort
end
view raw role.rb hosted with ❤ by GitHub

No comments: