9

Trying to come up with a more compact way of expressing this conditional in HAML and Ruby, perhaps with a ternary operator:

- if @page.nil?
  %br (nothing yet)
- else
  %br #{@page.name}

(looking for similar approach as per Neat way to conditionally test whether to add a class in HAML template)

Your help would be appreciated :)

Community
  • 1
  • 1
Daniel May
  • 2,192
  • 5
  • 25
  • 43

4 Answers4

18

The code you have makes the text a child of the <br> element; that is not desirable. What you really meant, I think, was:

%br
- if @page.nil?
  (nothing yet)
- else
  #{@page.name}

For this you can simply do:

%br
#{@page.nil? ? "(nothing yet)" : @page.name}

Or

%br
= @page.nil? ? "(nothing yet)" : @page.name

Or simply:

<br>#{@page ? @page.name : "(nothing yet)"}

However, personally I would 'fix' this in the controller so that you always have a @page, with something like:

unless @page
  @page = Page.new( name:"(nothing yet)", … )
end

With this you can stub out what a new/empty/nothing page looks like and let your view treat it like any other. Your @page still won't have a @page.id, so you can use that for tests to decide if you are creating a new item or editing an existing one.

This is how I handle all my forms that may be used to create or edit an item: provide defaults by creating (but not adding to the database) an item with the default values.

Aside: You're creating a <br> which is almost never a good idea, and you're creating it with Haml which should not be used for content markup. You might step back and think about what you're doing.

Phrogz
  • 296,393
  • 112
  • 651
  • 745
1

Simply do:

%br
= @page.try(:name)
apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • -1 This usage of [`try`](http://api.rubyonrails.org/classes/Object.html#method-i-try) is Rails, not Sinatra. Further, it does not have the "(nothing yet)" text the OP has asked for. – Phrogz Sep 08 '12 at 13:48
0

You can also embed in a string assuming - order_count = 12: %h5= Ordered #{ order_count == 1 ? "1 item" : "#{order_count} items" } for this session

Jon Wexler
  • 151
  • 9
-1
%br = @page ? (nothing yet) : #{@page.name}
Phrogz
  • 296,393
  • 112
  • 651
  • 745
AnkitG
  • 6,438
  • 7
  • 44
  • 72
  • -1 because: this creates content as a child of `
    `; the logic is backwards; you are treating Ruby code mode like it is text mode. The 'correct' form to fix the latter two would be `%br= @page ? @page.name : "(nothing yet)"`…but this still creates `
    foo`. See my answer.
    – Phrogz Sep 08 '12 at 14:03