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?
Are you sure you need multiple controllers? Can you have a single controller that gets passed a value to indicate how it behaves? You could also make a module that has the common functionality in it, and have the empty controller files that only reference the module.
a route could be used to pass the type in:
now in all the actions, in params you have the key :type_of_contact to guide your system.
You’ll want to make sure this is near the end of your routes so it doesn’t override access to your other controllers.