Domanda

I'm learned RoR programming through Mickael Hartl's tutorial, which I really enjoyed.

Now I'm developing an application with 8 types of objects.

For each object, I need to assign a status, coming from a statuses table, and to assign current user's name.

In each controller, in private section, I wrote a statuses_list function and a current_user_name, which make these data available to select fields in the forms respectively.

This does not sound DRY-like that much. Would it be relevant and secure to write such functions as helpers so the data are available anywhere in my application ?

Thanks for your advice,

Best regards,

Frédéric

È stato utile?

Soluzione 5

Well, thanks to all the answers collected, here is how I did :

Defined a set_statuses_list method in a ParametersHelper

Added include ParamtersHelper to the ApplicationController

Added before_action :set_statuses_list in each of my 8 objects controllers

It feels like a good balance, and I'll be happy to get comments about it. Note that the current_user method was indeed already available through the SessionsHelper.

Thanks for your help,

Best regards,

Frédéric

Altri suggerimenti

Move those methods to their home classes. Status.list() and User.current_user(). That's generally how people solve the problem "everyone needs a current_user, but nobody wants a $current_user global variable.

Then assign the current_user very early in your before_filters, when the authentication system identifies the user. And read /Confident Ruby/, by Avdi Grimm, for a very good write-up on how and why to create a Guest user, for current_user to return if nobody is logged in: http://devblog.avdi.org/2013/08/26/confident-ruby-is-finished/

Putting the methods in a helper file is the best way to make them available in your views, but if you also want to make these methods available in your controllers, then put these as methods in ApplicationController and at the top specify:

helper_method: :statuses_list, :current_user_name

Hope that helps.

To make your code accessible throughout your application, you have to mention it in helpers. This is ofcourse a DRY principle and would help you to reduce the same line of code again and again..

I would recomment using inheritance to give some controller some same methods.

Create a SuperClass that extends ApplicationController like:

class SuperController < ApplicationController
    [...]
end

and subclass it

class MyControllerClass < SuperController
    [...]
end

Put the repetitive stuff in the SuperController - et voila ! MyControllerClass inherits methods SuperController so you dont need to repeat them.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top