Topic: Grouping controllers into a module

Hi.

I'm trying to group two controllers inside a module.
Basically, they share a lot of code (the first is a setup, the second is a config section).

I wanted to create a module that contain those controllers, following this topic (used for a model).

So I have:

# app/controllers/grouped_module.rb

module GroupedModule

  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods

    def shared_method
    end

  end

end
# app/controllers/one_controller.rb

class OneController < ApplicationController

  include GroupedModule

  def another_method
  end

end

and the require line for the module in my environment.rb.

For the routes, I tried many things. eg. the easiest (if a want to call with /config/shared_method):

map.connect 'config/:action' , :controller => 'one_controller' # For the config

Is there something right here? What is the best way?

Thanks

Re: Grouping controllers into a module

If they are going to be sharing code then sure you can do that. I don't see why you also need a require line, the include should be enough. The other way of doing this is to put shared methods into your Application Controller, not sure which is better. I've done both at various times.

Re: Grouping controllers into a module

But it does not work.

I get

Unknown action

No action responded to shared_method. Actions: another_method

(following my previous example)

I can't see what I've missed.

Re: Grouping controllers into a module


module GroupedModule

    def shared_method

    end

end

class AController < ActionController::Base

  include GropuedModule

  def another_method

  end

end

That should work. I've had a look and I remembered that it goes into an instance variable of @controller (unless I've gone mad)

Re: Grouping controllers into a module

Yeah, seems to be working! Thank you.

I don't understand I could'nt find anything on this method to reduce duplicated code. Or maybe it's too easy wink

Anyway, thanks!