Programatically Create Controller in Rails

Posted by Trey Bean on Stack Overflow See other posts from Stack Overflow or by Trey Bean
Published on 2010-03-25T21:50:35Z Indexed on 2010/03/25 21:53 UTC
Read the original article Hit count: 378

Filed under:

What's the best way to dynamically create a controller in Rails.

I've got a class that needs to generate a bunch of controller that inherit from it. I could just create a bunch of files in /app/controllers, but they'd all be basically empty files. There's got to be a way to generate these classes dynamically and have them treated like other controllers in Rails, e.g. reloaded correctly in dev mode.

I tried putting this in a config/initializer:

FL.contact_types.each do |contact_type|
  controller_name = "#{contact_type.pluralize}Controller"
  Object.const_set(controller_name.to_sym, Class.new(ContactsController)) unless Object.const_defined?(controller_name.to_sym)
end

This worked, but I run into the dependency/reload problem and get “A copy of AuthenticatedSystem has been removed from the module tree but is still active” since the ContactsController inherits from ApplicationController which includes AuthenticatedSystem.

Is creating a bunch of empty files really the best solution?

© Stack Overflow or respective owner

Related posts about ruby-on-rails