0

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}
8
  • What code are you using in the view? Do you have a CSS class called "highlight"? Commented Oct 29, 2013 at 3:16
  • And is the sort variable coming from something like params[:sort]? Commented Oct 29, 2013 at 3:16
  • I'd say a more elegant approach would be to use a view helper. Could you output the code for your table headers? Commented Oct 29, 2013 at 3:16
  • Yes, I do have a css class for highlight. The above code works, since in the view the th tag will have the class like the variable name. I just wish I could use meta programming to dynamically select which @sort_by variable I should use Commented Oct 29, 2013 at 3:26
  • 1
    Show us the code for the table headers. The highlight should be managed entirely from within the view and helpers. Not the controller. Commented Oct 29, 2013 at 3:30

2 Answers 2

2

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.

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

2 Comments

guess that's the answer I was originally looking for, but I do agree that the next answer is better... thanks Damien
@gaudi_br to be fair, I've covered both in my answer, and I already answered in the comments. Anyway, I sincerely suggest you avoid using the above technique and use a view helper. That's what they're for.
1

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')}

Comments

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.