Sha256: 5fec02bd4209d9da3f1a8dd00acae6ce3493ebde0759df20a0059d976f009e19

Contents?: true

Size: 1.2 KB

Versions: 6

Compression:

Stored size: 1.2 KB

Contents

class Cl
  module Cast
    class Cast < Struct.new(:type, :value, :opts)
      TRUE  = /^(true|yes|on)$/
      FALSE = /^(false|no|off)$/

      def apply
        return send(type) if respond_to?(type, true)
        raise ArgumentError, "Unknown type: #{type}"
      rescue ::ArgumentError => e
        raise ArgumentError.new(:wrong_type, value.inspect, type)
      end

      private

        def array
          Array(value).compact.flatten.map { |value| split(value) }.flatten.compact
        end

        def string
          value.to_s unless value.to_s.empty?
        end
        alias str string

        def boolean
          return true  if value.to_s =~ TRUE
          return false if value.to_s =~ FALSE
          !!value
        end
        alias bool boolean
        alias flag boolean

        def int
          Integer(value) if value
        end
        alias integer int

        def float
          Float(value) if value
        end

        def split(value)
          separator ? value.to_s.split(separator) : value
        end

        def separator
          opts[:separator]
        end
    end

    def cast(value)
      type ? Cast.new(type, value, separator: separator).apply : value
    end
  end
end

Version data entries

6 entries across 6 versions & 2 rubygems

Version Path
travis-cl-1.2.4 lib/cl/cast.rb
cl-1.2.4 lib/cl/cast.rb
cl-1.2.3 lib/cl/cast.rb
cl-1.2.2 lib/cl/cast.rb
cl-1.2.1 lib/cl/cast.rb
cl-1.2.0 lib/cl/cast.rb