views:

63

answers:

2

I am trying to write this :

 %meta{ :name => "keywords", :content => "#{@page_city}, #{truncate_words(@page_keywords, 7) || 'Meta, Words, Are, Dope, For, SEO'}"}

Basically it sees if there is a local page that has a page city or keywords and adds those as they meta keywords. If it doesn't, it says the latter.

This works, but the only problem is that first comma after page_city is appearing. So right now it appears as ..

 <meta content=', Meta, Words, Are, Dope, For, SEO' name='keywords' />

Does anyone know how to include that "," into the embedded variables as well?

A: 

You could always just do this:

#{@page_city + ', ' if @page_city}

Personally, I would probably go for a different approach to this altogether:

@arg1 = 'foo'
@arg2 = 'bar'
@arg3 = 'baz'
[@arg1, @arg2, @arg3].join(", ")    # => "foo, bar, baz"
Karl
I had tried this .. #{@page_city + ', '} . Produces this error = You have a nil object when you didn't expect it!You might have expected an instance of Array.The error occurred while evaluating nil.+
Trip
My mistake, that would only work if `@page_city` wasn't nil, which would defeat the purpose of doing that to begin with. I replaced it with something that would work.
Karl
Oh clever, just noticed your update, and it was something I had done as well.
Trip
+2  A: 

You can usually lean on Array for situations like this:

- default_keywords = %w[ Meta Words Are Dope For SEO ]
- meta_content = [ @page_city, (truncate_words(@page_keywords, 7) || default_keywords) ]

%meta{ :name => "keywords", :content => meta_content.flatten.compact.join(',') }

Array#compact strips out all nil values to avoid inserting extra commas.

tadman
That works Tadman, thanks. Although I just joined them with a (' '), because some keywords have two words, and I let my array have commas in it already. But definately great work nonetheless! Thanks! What is that %w?
Trip
There's a number of handy % macros for declaring Arrays. %w[ ] will split the contents on spaces and return an Array. There are about a half-dozen others that work in slightly different ways, like %Q[ ] which is an alternative to quotes, and %W[ ] which is like %w[ ] but allows #{...} interpolation on the contents. %w[ a b c ] is a lot less syntax than ['a','b','c']
tadman