Blog » Blog Entry

Rubyonrails get public actions from a controller

February 15, 2007

If you tuned in last week, I was blog'n about getting a list of controllers in a Rubyonrails project. Here's something I wrote to get the list of actions for a specific conroller, I keep it in a helper file:

# c = controller
# s = selected
def get_action_options( c, s='' )
  str = '<option value=""></option>'
  file = RAILS_ROOT + "/app/controllers/#{ c }_controller.rb"
  if File.exists? file
    f = File.new( file, 'r' )    
    while line = f.gets
      line = line.strip
      break if line =~ /^private/
      if line =~ /^def\ /
        action = line.gsub( /^def\ /, '' )
        str << "<option value='#{ action }'"
        str << ' selected="selected"' if action == s
        str << ">#{ action }</option>"
      end
    end
    f.close
  end
  str
end
Tags: rubyonrails, controller, actions

« ESR dumps Fedora, yay! Rubyonrails model and controller lists: »

Trying to get a list of controllers and actions via self reflection

By: Cris <cris_paltenghe at countrywide dot com>

Posted: 9 months ago

I need a routine so I can build a list of controllers and actions to populate drop down lists in a form. I was hoping to use Ruby's self reflection capabilities, but can't seem to get anything meaningful out of it. It would be great if one could do something like ApplicationController.subclasses, but all I get is what is in scope (presumably from ObjectSpace).

Add a comment:

Title:

Comment:

Name:

Email: