Topic: Refactor controller method that is shared accross 2 others

this is actually a basic question but i had some errors when i tried it out so i figured i'd ask here.



i have 3 controllers Cat, Dog and Mouse.

Cat, Dog and Mouse have a common method in them: eat


here's a sample of Cat:

class Cat < ApplicationController
  def eat
    # do eat functionality
    @cat = Cat.find(params[:id])
    @cat.food = "Fish"
    @cat.save

    redirect_to(cats_url)
  end

  # some CRUD actions here
end


eat doesn't have it's own view.




how can i refactor this into a common controller file that the Cat, Dog and Mouse can share?



suppose the eat method did have a view, then can i refactor them the same way?





Thanks.

Re: Refactor controller method that is shared accross 2 others

You can use a module to contain the code you want to share.
Create extra_controller_methods.rb in RAILS_ROOT/lib:

module ExtraControllerMethods
def eat
    # do eat functionality
    @cat = Cat.find(params[:id])
    @cat.food = "Fish"
    @cat.save

    redirect_to(cats_url)
  end
end


Then in the controllers you want the eat action:
class Dog ...
  include ExtraControllerMethods
end

BTW - The redirect_to line will get rid of all your instance variables.

Re: Refactor controller method that is shared accross 2 others

thanks for the reply.

that's excellent. is there also a way that i can add this to a controller? what was the reason you chose to put it in the model?


not sure i understood by the redirect_to line. in this particular case, i won't have a view so that won't be a problem, right?

Re: Refactor controller method that is shared accross 2 others

Sorry, that wasn't meant to be the model, it is for the controller ... either way it is the same thing.

Oh, I see ... then you will want to make eat a private action probably.

Re: Refactor controller method that is shared accross 2 others

great thanks smile

well the thing is, i have a show view whose form action submits to this eat method. eat doesn't have a view, it just does some processing and redirects to the index.

since the view has to submit to the eat method, won't it have to be a protected method?