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?

7
  • BTW, why do you use such dreadful construction as "#{s.name}"? Commented May 20, 2014 at 10:29
  • "Web Design" are two classes because class names are separated by white space Commented May 20, 2014 at 10:33
  • @MarekLipka in reference to the construction..what would you do differently? Commented May 20, 2014 at 10:37
  • i started with that, but read that interpolation was more efficient? Commented May 20, 2014 at 10:38
  • Where did you read this? Commented May 20, 2014 at 10:40

2 Answers 2

5

This should work:

mix <%= p.sectors.map { |s| s.name.gsub(/\s+/, '-') }.join(' ') %>
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, works a treat :-), ill accept once default time constraints pass
Can you show the final output ? I am not getting it
@ArupRakshit ["Content Management System", "Web Design", "Web Development"].map { |s| s.gsub(/\s/, '-') } # => ["Content-Management-System", "Web-Design", "Web-Development"]
Good answer, but I would put it in a helper method.
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">

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.