Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby On Rails Helpers -- Using instance variables in helpers

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?

like image 368
Chris Muench Avatar asked Mar 11 '11 15:03

Chris Muench


People also ask

How do you use the helper method in Ruby on Rails?

A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods. One of these built-in helpers is time_ago_in_words . This method is helpful whenever you want to display time in this specific format.

What is instance variable in Ruby on Rails?

An instance variable in ruby has a name starting with @ symbol, and its content is restricted to whatever the object itself refers to. Two separate objects, even though they belong to the same class, are allowed to have different values for their instance variables.


2 Answers

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.

like image 189
Jim Mitchener Avatar answered Nov 03 '22 22:11

Jim Mitchener


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...

like image 33
Derek Prior Avatar answered Nov 04 '22 00:11

Derek Prior