17th Apr, 2008

获取所有Controller和Action

最近在做一个基于Controller加Action的权限管理插件,需要得到应用中的所有Controller作为一个列表供用户选择,这可以通过ApplicationController.subclasses得到,但是Rails在启动时并不会自动加载所有Controller,而是当请求到达时,根据路由来决定应该加载那个Controller,因此要使用ApplicationController.subclasses,就必须先require所有的Controller:


def require_all_controllers(path)
  Dir.new(path).entries.collect do |e|
    controller_path = File.join(path, e)
    if e[0] != 46 # 46 = '.'
      if File.directory?(controller_path)
        require_all_controllers(controller_path)
      elsif e =~ /controller.rb$/
        ApplicationController.require_or_load controller_path
      end
    end
  end
end

require_all_controllers将加载指定目录下的所有以controller.rb结束的文件,你也可以选择将结果缓存起来,这样就不需要每次都重新require了:


  @@all_controllers = nil
  def get_all_controllers
    require_all_controllers("#{RAILS_ROOT}/app/controllers") unless @@all_controllers
    @@all_controllers ||= ApplicationController.subclasses
  end

至于Action,可以直接调用Controller的action_methods方法得到。

评论

精简一下 :)

def require_all_controllers(path)
Dir.foreach(path) do |e|
next if e =~ /^\./
controller_path = File.join(path, e)
if File.directory?(controller_path)
require_all_controllers(controller_path)
elsif e =~ /controller.rb$/
ApplicationController.require_or_load controller_path
end
end
end

留条评论?

Your response:

Categories