1

I have a an array returned when using .map:

<li class="mix <%= p.sectors.map {|s| "#{s.name}"} %> all">

gives array:

["Content Management System", "Web Design", "Web Development"]

at the moment the returned result in my view is:

<li class="mix ["Content Management System", "Web Design", "Web Development"] all mix_all" </li>

I want to use each s.name as a class name, but I have an issue when using:

<li class="mix <%= p.sectors.map {|s| "#{s.name}"}.join(" ") %> all">

where each word is being treated as a separate class, so Web Design is now two classes rather than one.

Is there a way to have Web Design as one class or do I need to use different naming conventions, like Web-Design to make this work?

halfer
  • 19,471
  • 17
  • 87
  • 173
Richlewis
  • 14,492
  • 34
  • 115
  • 258

2 Answers2

4

This should work:

mix <%= p.sectors.map { |s| s.name.gsub(/\s+/, '-') }.join(' ') %>
Marek Lipka
  • 49,740
  • 7
  • 83
  • 88
3

You can't have a class name with spaces in it. So, you need to convert your phrases into class names. Class names are typically downcased (though this isn't a requirement) and separated with hyphens (rather than underscores, although again this isn't a requirement, just a convention).

So, you could downcase and hyphen-separate them as follows

<li class="mix <%= p.sectors.map{|sector| sector.name.downcase.gsub(/[^a-z0-9\-]+/, '-') }.join(' ') %> all">

My regex here will replace 1 or more instances of anything that's not a letter, number or hyphen, with a hyphen, so the result should be

<li class="mix content-management-system web-design web-development all mix_all"> 

You could move this into the model:

#in Sector class
def html_classname
  self.name.downcase.gsub(/[^a-z0-9\-]+/, '-')
end

and then change the view code to

<li class="mix <%= p.sectors.map(&:html_classname).join(' ') %> all">
Max Williams
  • 31,680
  • 30
  • 120
  • 192