I've got a code that almost repeats itself in three of my controllers and i was wondering: is there a way to render partials inside controllers? I'll clarify, i want to write the same piece of ruby code and render it in each one of the controllers. Anyone know a way to do that? thanks
Asked
Active
Viewed 81 times
0
-
1I don't get your idea. Partials are part of the view logic and then you are asking for repeated code inside controllers. Can you put an example that clarify your question? – Pigueiras Feb 27 '13 at 17:38
2 Answers
5
I'm very confused by your question; I don't see what it has to do with partials. However, if I understand correctly, what you have is something like.
class FooController < ApplicationController
def my_method
end
end
class BarController < ApplicationController
def my_method
end
end
class BazController < ApplicationController
def my_method
end
end
And you want to DRY it up by abstracting the my_method
method to a single place. The solution is to define it on ApplicationController
, which the other three controllers all inherit from.

gregates
- 6,607
- 1
- 31
- 31
1
There are two solutions, the module, and playing with the inheritance
Module
Define a module with your custom code and include it in your controllers
module MyCustomModule
def method_1
#code ...
end
def method_2
#code ...
end
def method_2
#code ...
end
end
Then in your controllers :
class MyController < AplicationController
include MyCustomModule
end
Inheritance
If you don't mind having all your controllers ending up with these methods, simply define them in the application controller
class ApplicationController < ActionController::Base
# ...
def method_1
#code
end
# And so on ...
end

Intrepidd
- 19,772
- 6
- 55
- 63