String “true” and “false” to boolean

前端 未结 13 762
青春惊慌失措
青春惊慌失措 2020-12-08 18:23

I have a Rails application and I\'m using jQuery to query my search view in the background. There are fields q (search term), start_date, end

相关标签:
13条回答
  • 2020-12-08 18:32

    ActiveRecord provides a clean way of doing this.

    def is_true?(string)
      ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES.include?(string)
    end
    

    ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES has all of the obvious representations of True values as strings.

    0 讨论(0)
  • 2020-12-08 18:32

    Looking at the source code of Virtus, I'd maybe do something like this:

    def to_boolean(s)
      map = Hash[%w[true yes 1].product([true]) + %w[false no 0].product([false])]
      map[s.to_s.downcase]
    end
    
    0 讨论(0)
  • 2020-12-08 18:34

    You could add to the String class to have the method of to_boolean. Then you could do 'true'.to_boolean or '1'.to_boolean

    class String
      def to_boolean
        self == 'true' || self == '1'
      end
    end
    
    0 讨论(0)
  • 2020-12-08 18:35

    In Rails 5 you can use ActiveRecord::Type::Boolean.new.cast(value) to cast it to a boolean.

    0 讨论(0)
  • 2020-12-08 18:37

    Security Notice

    Note that this answer in its bare form is only appropriate for the other use case listed below rather than the one in the question. While mostly fixed, there have been numerous YAML related security vulnerabilities which were caused by loading user input as YAML.


    A trick I use for converting strings to bools is YAML.load, e.g.:

    YAML.load(var) # -> true/false if it's one of the below
    

    YAML bool accepts quite a lot of truthy/falsy strings:

    y|Y|yes|Yes|YES|n|N|no|No|NO
    |true|True|TRUE|false|False|FALSE
    |on|On|ON|off|Off|OFF
    

    Another use case

    Assume that you have a piece of config code like this:

    config.etc.something = ENV['ETC_SOMETHING']
    

    And in command line:

    $ export ETC_SOMETHING=false
    

    Now since ENV vars are strings once inside code, config.etc.something's value would be the string "false" and it would incorrectly evaluate to true. But if you do like this:

    config.etc.something = YAML.load(ENV['ETC_SOMETHING'])
    

    it would be all okay. This is compatible with loading configs from .yml files as well.

    0 讨论(0)
  • 2020-12-08 18:37

    I'm surprised no one posted this simple solution. That is if your strings are going to be "true" or "false".

    def to_boolean(str)
        eval(str)
    end
    
    0 讨论(0)
提交回复
热议问题