satish
satish

Reputation: 943

In Rails, how can I get a string from a boolean?

I'm using Rails 5. I see many posts about getting a boolean from a string, but I would like to go the reverse path. I was wondering if there is a more elegant way than this ...

my_boolean_value ? "true" : "false"

Upvotes: 0

Views: 2522

Answers (4)

B-M
B-M

Reputation: 1308

You can use to_s to transform true or false to a string. But you only want that if your value is different than nil. The .nil? method will return true or false (if the variable is nil or not). The exclamation mark negates the assertion. In that case, if it's NOT nil, to_s method will be called.

my_boolean_value.to_s if !my_boolean_value.nil?

Upvotes: 2

Amit Patel
Amit Patel

Reputation: 15985

Try

ActiveRecord::Type::Boolean.new.type_cast_from_user(my_boolean_value).to_s

Upvotes: 0

Abhishek
Abhishek

Reputation: 7045

You can use my_boolean_value.to_s. Basically it will convert booleans to string.

You can also do "#{my_boolean_value}"

Note: If my_boolean_value can be .nil? or anything other then true/false then your solution in the question is the best and simplest way to do it. You can use following way as well if you don't want to use ternary operator,

(!!my_boolean_value).to_s

But I still think from readability and maintainability point of view, you should use the solution given in the question. Reason would be, you are doing double negation can be confusing if you don't put comments around.

Upvotes: 1

Josh Brody
Josh Brody

Reputation: 5363

More elegant way? No. More practical way? Maybe.

# in app/helpers/application_helper.rb
module ApplicationHelper
  def boolean_label_for(value)
    BooleanLabel.to_s(value)
  end
end 

# in lib/boolean_label.rb
class BooleanLabel
  def self.to_s(value)
    new(value).to_s
  end

  def initialize(value)
    @value = value 
  end 

  def to_s
    if @value 
      "true"
    elsif @value.nil?
      "i am nil — false"
    elsif @value
      "false"
    end
  end 
end 

It's not overly sexy and you could argue it's unnecessarily complicated, but if you find yourself implementing this check a lot, you should DRY it up.

Upvotes: 0

Related Questions