10

I have a helper for a controller:

module CourseStepsHelper
  def current_quiz_result
    @course_step.step.step_quiz.quiz_attempts.where(:patient_id => current_user.id, :step_quiz_id => @course_step.step.step_quiz.id).first
  end
end

It has access to @course_step which is defined in the CourseSteps controller show "action". Is this common practice to use instance variables in helpers?

3
  • Please try to shell out more clearly what your question is. Commented Mar 11, 2011 at 15:57
  • @polarblau I have cleared up my question Commented Mar 11, 2011 at 16:38
  • For actual answer please see stackoverflow.com/questions/6474596/… Commented Jun 27, 2012 at 7:12

2 Answers 2

1

Depending on the level of detail for this quiz result you may actually want to use a partial. In which case the syntax would be:

<%= render :partial => 'quiz/results', :locals => { :quiz => @quiz } %>

If it's relatively simple and you think it should be in a helper you should make simply make quiz a parameter. Requiring views to provide a specific instance variable to use your helper would likely be frowned upon by other developers.

def quiz_result(quiz)    # no need to call it "current" when we supply quiz
    # do some stuff
end

It also looks to me that you may want to restructure your models in some way. As you can see I implemented my examples with a Quiz class. I'm not sure what your data model looks like but when you are calling properties that are nested that deep it's generally a sign that something is wrong.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, but this doesn't really answer the original question. In my opinion the question is "using/assuming instance variables vs. passing as a parameter." For example, is the helper called as-is, assuming the @course_step variable exists? Or should you call the helper like so: current_quiz_result(@course_step), and should the function accept a single parameter?
For actual answer please see stackoverflow.com/questions/6474596/… Thanks, @ybakos!
1

I haven't seen a good argument presented for either case, and stumbled onto this question when I was searching for an answer. Personally, I've been using the instance variables in helper methods where it's possible as this is the dryest approach across both helper and view. Rather than passing the instance variable from my view and defining my helper method to accept it, I can just use it directly in the helper. Slightly less typing, anyway...

1 Comment

... by using the instance variable. Your helper has access to the same instance variables your view does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.