Sha256: 430cc5c2776628dd7cb0323ba00331da5df98fd3ef9798ce1ee309c68d1bd7a2

Contents?: true

Size: 1.24 KB

Versions: 17

Compression:

Stored size: 1.24 KB

Contents

module Shamu

  # Adds `to_bool` to strings, numbers, booleans and nil class to provide a
  # consistent means of parsing values to a Boolean type.
  module ToBoolExtension

    # Extend common classes to add `to_model_id` method.
    def self.extend!
      String.include Strings
      Integer.include Integers
      TrueClass.include Boolean
      FalseClass.include Boolean
      NilClass.include Nil
    end

    # Add `to_model_id` to String types.
    module Strings
      def to_bool( default = false )
        case self
        when "1", /\At(rue)?\z/i, /\Ay(es)?\z/i     then true
        when "0", "", /\Af(alse)?\z/i, /\An(o)?\z/i then false
        else                                             default
        end
      end
    end

    # Add `to_model_id` to Integer types.
    module Integers
      def to_bool( default = false )
        case self
        when 1 then true
        when 0 then false
        else        default
        end
      end
    end

    # Add `to_model_id` to Boolean types.
    module Boolean
      def to_bool( default = self )
        self
      end
    end

    # Add `to_model_id` to nil.
    module Nil
      def to_bool( default = self )
        default
      end
    end


  end
end


Shamu::ToBoolExtension.extend!

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
shamu-0.0.24 lib/shamu/to_bool_extension.rb
shamu-0.0.21 lib/shamu/to_bool_extension.rb
shamu-0.0.20 lib/shamu/to_bool_extension.rb
shamu-0.0.19 lib/shamu/to_bool_extension.rb
shamu-0.0.18 lib/shamu/to_bool_extension.rb
shamu-0.0.17 lib/shamu/to_bool_extension.rb
shamu-0.0.15 lib/shamu/to_bool_extension.rb
shamu-0.0.14 lib/shamu/to_bool_extension.rb
shamu-0.0.13 lib/shamu/to_bool_extension.rb
shamu-0.0.11 lib/shamu/to_bool_extension.rb
shamu-0.0.9 lib/shamu/to_bool_extension.rb
shamu-0.0.8 lib/shamu/to_bool_extension.rb
shamu-0.0.7 lib/shamu/to_bool_extension.rb
shamu-0.0.5 lib/shamu/to_bool_extension.rb
shamu-0.0.4 lib/shamu/to_bool_extension.rb
shamu-0.0.3 lib/shamu/to_bool_extension.rb
shamu-0.0.2 lib/shamu/to_bool_extension.rb