Josh Scott
Josh Scott

Reputation: 3840

Issue with Conditional Logic - Ruby on Rails

I am having a problem with some conditional logic with Ruby. Admittedly I am a newbie to all things Ruby.

This code is causing the site not to load:

<body style="background-image:url("<%= if @is_home_page.present? '/images/bg-main-power-bg.jpg' else '/images/bg-inner-power-bg.jpg' end %>"); background-repeat:repeat-x;">

Without the conditional the CSS loads just fine.

What am I doing wrong?

Thanks

Upvotes: 0

Views: 367

Answers (3)

Zabba
Zabba

Reputation: 65497

Your original code: The error you may be getting is probably due to the second " in this snippet "background-image:url("<%= .... Try changing it so that the <%= ... %> is inside single quotes, not double quotes, since the whole string is already delimited by double-quotes.

Ideally you should strive to:

  • Remove logic from view
  • avoid inline styles.

So:

some.html.erb

<body class='<%= body_class %>'>

some_helper.rb

class SomeHelper
  def body_class
    @is_home_page.present? ? "has_homepage" : "no_homepage"
  end
end

some.css:

body.has_homepage
  background-image:url('/images/bg-main-power-bg.jpg')
  .......
body.no_homepage
  background-image:url(/images/bg-inner-power-bg.jpg')
  .......

Upvotes: 2

deefour
deefour

Reputation: 35370

You might also consider moving this to a helper file. You could add the following to app/helpers/application_helper.rb

def bg_path
  return '/images/bg-main-power-bg.jpg' if current_page? root_path
  '/images/bg-inner-power-bg.jpg'
end

This leaves your view a bit cleaner.

<body style="background-image:url("<%= bg_path %>"); background-repeat:repeat-x;">

Reading: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-current_page-3F

Upvotes: 1

doesterr
doesterr

Reputation: 3965

Use the ternary operator for inline conditionals.

condition ? branch_a : branch_b

a == b ? "foo" : "bar"
# is the same as
if a == b
  "foo"
else
  "bar"
end

For your specific case:

@is_home_page ? '/images/bg-main-power-bg.jpg' : '/images/bg-inner-power-bg.jpg'

Upvotes: 2

Related Questions