Programatically Create Controller in Rails
- by Trey Bean
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?