Jump to content

The ultimate community for Ruby on Rails developers.


Keeping it DRY.... where to put shared methods?

  • Please log in to reply
2 replies to this topic

#1 Rowel



  • Members
  • 109 posts

Posted 17 September 2013 - 10:29 AM

My code is starting to have duplicates.... because I don't know where to put methods/functions that need to be accessed by (2) different controllers, and just to get it up quickly I just duplicated it.  


So I have a users_controller, and a pages_controller and posts_controller.   


On the users page, I have posts being displayed. 

On the homepage, I also have posts being displayed.


Where should I put shared/common code so that the users_controller and pages_controller and posts_controller can all have access to ithese methods?   


Right now, I have duplicated def methods in some controllers, and also some duplicate private methods in each controller.  




On a related note, how can I access methods defined in one controller from another controller?  

#2 Ohm



  • Moderators
  • 530 posts
  • LocationCopenhagen

Posted 17 September 2013 - 10:44 AM

You could look into concerns and see if that solves your problem.



DHH blog link: http://37signals.com...t-with-concerns

Blog: http://ohm.sh | Twitter: @madsohm | Work: Lokalebasen.dk

#3 stevieing



  • Members
  • 40 posts

Posted 17 September 2013 - 12:52 PM

If you have posts being displayed on two separate pages then use a partial. I don't know what version of rails you are using but newer versions have a views/application folder for shared partials.


If you have a method that is shared across more than one controller then put it in the application controller. Controllers are classes so follow all of the normal rules.


Hope that helps.



0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users