Quoting in tags in Rails

Ok, I am working on views of my little project. Every day I do things like this:

<li <%= 'class="'+item.status.caption+'"' if %w{ sold, absent }.include?(item.status.caption) %> >

      

I recently found the correct String method in the Ruby API called quote . I wrote this:

<li <%= 'class='+item.status.caption.quote if %w{ sold, absent }.include?(item.status.caption) %> >

      

but the app threw an error stating it didn't recognize the method. So, is there a suitable way to do such a normal quote (or even "somethination" with a custom character / string: P)? Something like "surround_with" or something else? Didn't find a hint in Rail API.

+2


source to share


5 answers


You can also create a rather trivial helper like:

  def quoted_class(val)
    "class='#{val}'"
  end

      



Then you will use it in your example like this:

<li <%= quoted_class(item.status.caption) if %w{s,abs}.include?(item.status.caption) %>>

      

+1


source


So there is too much logic inside the view and you are not using the helpers that Rails gives you. Create a method in the foo_helper.rb file in app/helpers

(where "foo" is your controller name):

def display_item(item)
  case item.status.caption
    when /sold/ then class = 'sold'
    when /absent/ then class = 'absent'
    else class = nil  # You could add more cases here as needed
  end
  content_tag :li, item.name, :class => class  # Or whatever you want shown
end

      



Then, in your opinion, you can call <%= display_item(item) %>

instead of the whole built-in if

gibberish.

(Oh, and that wasn't your question, but as a complementary exercise, also think about how to shrink the chain item.status.caption

, either with methods like item.sold?

and item.absent?

or by turning status

into something that you can check directly. Google on "Law Demeter "to see why it's a good idea.)

+2


source


Or can you use content_tag? You don't say what you are showing inside the li, but you can do something like:

<%= content_tag :li, "your list content", ({:class => item.status.caption} if %w{ sold absent }.include?(item.status.caption)) %>

BTW, I don't think you want a comma in your% w string unless you really want to match "sold" (semicolon) or "missing".

+1


source


To use quotes, I would do something like this:

"This is '#{string_inside_quotes}'."

      

or

"This is \"#{string_inside_quotes}\"."

      

although it's not entirely clear to me what you mean in your original example.

0


source


Why not easy

<li class="<%= item.status.caption if %w{ sold, absent }.include?(item.status.caption) %>">

      

as an empty class attribute as a class attribute?

If you don't want to hide your quotes, there is another way to quote in ruby:

<li <%= %q(class="#{item.status.caption}") if %w{ sold, absent }.include?(item.status.caption) %>>

      

0


source







All Articles