Shpigford
Shpigford

Reputation: 25338

Return string if data is empty, nil or blank?

I have a text_area that I want to set the placeholder attribute for if a particular object is empty, nil or blank.

I'm currently doing this:

<%= f.text_area :comment, placeholder: @response.followup ||= "Would you like to add a note?" %>

And that seems to work if @response.followup is nil, but if it's just empty...it doesn't use the "Would you like to add a note?" default text I'm setting.

Upvotes: 2

Views: 1388

Answers (5)

nurettin
nurettin

Reputation: 11736

I do this so often, I had to make something like this:

class Object
  def fill(wtf)
    present? ? self : wtf
  end
end

<%= f.text_area :comment, placeholder: @response.followup.fill("Would you like to add a note?") %>

Example:

require 'active_support/core_ext/object/blank'

class Object
  def fill(wtf)
    present? ? self : wtf
  end
end

p nil.fill("omg")

Upvotes: 0

Thaha kp
Thaha kp

Reputation: 3709

Use present? method

<%= f.text_area :comment, placeholder: (@response.followup.present? ? "Would you like to add a note?" : @response.followup) %>

Upvotes: 0

jvnill
jvnill

Reputation: 29599

check if you have presence available in your rails version. If it is, you can do the following

<%= f.text_area :comment, placeholder: @response.followup.presence || "Would you like to add a note?" %>

If it's not available, you can choose one of the following

  1. use a decorator/presenter (i think this is overkill)
  2. set the value of the placeholder in the controller

    @response.followup = 'Would you like to add a note?' if response.blank?

  3. use a ternary operator in the view

    <%= f.text_area :comment, placeholder: (@response.followup.blank? ? "Would you like to add a note?" : @response.followup) %>

Upvotes: 4

Jakob S
Jakob S

Reputation: 20125

<%= f.text_area :comment, placeholder: (@response.followup.blank? ? "Would you like to add a note?" : @response.followup) %>

or perhaps

<%= f.text_area :comment, placeholder: (@response.followup.present? ? @response.followup : "Would you like to add a note?") %>

if you find that reads better.

Upvotes: 0

Shadwell
Shadwell

Reputation: 34774

You should be able to test for "blankness" and use:

placeholder: [email protected]? ? @response.followup : "Would you like to add a note?"

So, if the followup isn't blank then use it, otherwise use your default text.

Upvotes: 0

Related Questions