How to check if a param is true or false?

前端 未结 4 767
我寻月下人不归
我寻月下人不归 2020-12-24 12:10

This is really racking my brain, but maybe I\'m trying to hard.

I\'m passing a param via a URL (example.com?debug=true)

So I basically want to say:



        
4条回答
  •  失恋的感觉
    2020-12-24 12:57

    You could use ActiveRecord's method of checking truthful values if you don't want to reinvent the wheel (this is what is used when passing params inside an ActiveRecord object

    Rails 3-4.1

    if ActiveRecord::ConnectionAdapters::Column.value_to_boolean(params[:debug])
        do xyz
    else
        do abc
    

    Rails 4.2.0

    ActiveRecord::Type::Boolean.new.type_cast_from_database(params[:debug])
    

    Rails 5

    ActiveModel::Type::Boolean.new.cast(params[:debug])
    

    Might be worth wrapping in a helper but never the less it's quite flexible:

    rails c
    Loading development environment (Rails 3.2.6)
    1.9.3p194 :001 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean '1'
     => true 
    1.9.3p194 :002 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean '0'
     => false 
    1.9.3p194 :003 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean 1
     => true 
    1.9.3p194 :004 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean true
     => true 
    1.9.3p194 :005 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean 'true'
     => true 
    1.9.3p194 :006 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean 'on'
     => true 
    1.9.3p194 :007 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean 'off'
    

    Custom extension

    Some people frown on extending core classes but this does fit with the DRY principle.

    # config/initializer/boolean.rb
    class Boolean
      def self.parse(value)
        ActiveRecord::ConnectionAdapters::Column.value_to_boolean(value)
      end
    end
    

    Then used like

    if Boolean.parse(params[:debug])
      then xyz
    

提交回复
热议问题