简体   繁体   English

在 Rails 中,如何从 boolean 中获取字符串?

[英]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.我正在使用 Rails 5。我看到很多关于从字符串中获取 boolean 的帖子,但我想 go 反向路径。 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.您可以使用to_struefalse转换为字符串。 But you only want that if your value is different than nil .但是,如果您的值与nil不同,您只需要这样做。 The .nil? .nil? method will return true or false (if the variable is nil or not).方法将返回 true 或 false(如果变量为 nil 或不是)。 The exclamation mark negates the assertion.感叹号否定断言。 In that case, if it's NOT nil, to_s method will be called.在这种情况下,如果它不是 nil,则将调用to_s方法。

my_boolean_value.to_s if !my_boolean_value.nil?

You can use my_boolean_value.to_s .您可以使用my_boolean_value.to_s Basically it will convert booleans to string.基本上它将布尔值转换为字符串。

You can also do "#{my_boolean_value}"你也可以做"#{my_boolean_value}"

Note : If my_boolean_value can be .nil?注意:如果my_boolean_value可以是.nil? or anything other then true/false then your solution in the question is the best and simplest way to do it.或除true/false之外的任何其他内容,那么您在问题中的解决方案是最好和最简单的方法。 You can use following way as well if you don't want to use ternary operator,如果您不想使用三元运算符,也可以使用以下方式,

(.!my_boolean_value).to_s (.!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.它并不过分性感,你可以说它不必要地复杂,但如果你发现自己经常执行这个检查,你应该把它干掉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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