Module methods as controller actions

Is it possible to include module methods as controller actions and use
them?

Yes.

Fred

How? :slight_smile:

I've tried something like this:

module ControllerPeople
  def index
    puts 'index action'
    render :text => 'OK'
  end

  def self.included(base)
    base.send :helper_method, :index
  end
end

class PeopleController < ActionController::Base
  include ControllerPeople
end

but, I get no method error 'index' in PeopleController.

Thanks,
Dalibor

That's odd. I've done exactly that (but without the self included
method - you don't need that) and it worked fine.

Fred

That's odd. I've done exactly that (but without the self included
method - you don't need that) and it worked fine.

Fred

Yup, it works that way. But the problem is when I use before_filter in
the controller to decide what module to be included.

Is there any solution for this or maybe any design pattern for
polymorphic controllers (that are generated dynamically depending on
some values in post data)?

That's odd. I've done exactly that (but without the self included
method - you don't need that) and it worked fine.

Fred

Yup, it works that way. But the problem is when I use before_filter in
the controller to decide what module to be included.

That's doesn't sound like a great idea - the modules that are included in the controller won't magically go away at the end of the request (except in development mode)

Is there any solution for this or maybe any design pattern for
polymorphic controllers (that are generated dynamically depending on
some values in post data)?

I've got the feeling you're overthinking things. What's wrong with

def some_action
   if foo
     bar
   else
     baz
   end
end

or just redirect the user to a different controller depending on the post data.

Fred

Redirect would not work since I'm actually writing an API. And the
problem with the above code is that it's kind of modularity
programming. I should implement a versioning system for API (depending
of the parameter in the request xml data, i.e. api_versions='2', that
version of API responses)... I suppose only controller actions and
their views would differ from version to version, and models are easy
to handle with just extending the logic in them.

Yes, this could be done with interface, but I see it unnatural for
rails MVC architecture.