gaudi_br
gaudi_br

Reputation: 193

How do I dynamically assign a variable in Ruby on Rails?

I would like to highlight a table header depending on a variable's name passed in via the params.

In the controller I have:

case sort
    when 'grade'
        @sort_by_grade = 'highlight'
    when 'student_name'
        @sort_by_student_name = 'highlight'
end

Is there a more elegant way to do this? For instance, something like:

"sort_by_#{sort}" = 'highlight'

My table headers code are something like this in Haml:

%th{:class => @sort_by_grade}

Upvotes: 0

Views: 94

Answers (2)

user419017
user419017

Reputation:

As I detailed in the comments, which is hacky and bad practice:

instance_variable_set("@sort_by_#{sort}", "highlight")

Personally, I wouldn't manage the highlight logic from within the controller. Extract it into a view helper or put the logic directly in the view:

%th{class: ('highlight' if params[:sort] == 'grade')}

Or, using a view helper:

application_helper

def sort_highlight(col)
  "highlight" if params[:sort] == col
end

view

%th{class: sort_highlight('grade')}

Upvotes: 1

Phrogz
Phrogz

Reputation: 303520

Direct answer to your question (not best practice):

instance_variable_set :"@sort_by_#{sort}", 'highlight'

But really, using a hash or other better data structure is a better answer.

Upvotes: 2

Related Questions