Reputation: 25338
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
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
Reputation: 3709
Use present? method
<%= f.text_area :comment, placeholder: (@response.followup.present? ? "Would you like to add a note?" : @response.followup) %>
Upvotes: 0
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
set the value of the placeholder in the controller
@response.followup = 'Would you like to add a note?' if response.blank?
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
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
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