简体   繁体   中英

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"

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?

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.

Try

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM