Accidental Resolution


August 13th, 2007

On any sizeable Rails app you are bound to define a method in a controller that you don’t intend on making routable and neglect to call hide_method or making. A really good sign that a method shouldn’t be routable is when the method has arity. I wrote this small script to find all of the action_methods that also accept arguments. Read on for the script.

Some day I will probably collect this and other code healthiness introspections into a rails plugin providing handy rake targets such as “rake show:actions_with_arity”. For now, load it with script/runner or inside of a script/console session.


    def get_all_controllers
      controllers=[];
      ObjectSpace.each_object do |obj|
        if (obj.is_a? Class)&&(obj.name=~/Controller$/)
          controllers << obj
        end
      end
      controllers
    end

    def get_controllers_actions_methods
      controllers = get_all_controllers

      controllers_actions= controllers.inject([]){ |controllers_actions,controller|
        if controller.respond_to?(:action_methods)
          controller_actions_methods = controller.action_methods.to_a.map { |act|
            controllers_actions << controller.new.method(act)
          }
        end
        controllers_actions
      }
      controllers_actions
    end

    def output_methods
      ms = get_controllers_actions_methods
      y (ms.reject{|x|x.arity==0}.map(&:inspect).sort)
    end

Leave a Reply