Sha256: fbfc60252ad9c589c70881c841973682420cc37d1f468e137bf20f196daa1a0d

Contents?: true

Size: 1.32 KB

Versions: 3

Compression:

Stored size: 1.32 KB

Contents

class Joshua
  module Params
    class Parse
      class << self
        def define name, &block
          define_method 'check_%s' % name do |value, opts|
            block.call value, opts || {}
          end
        end
      end

      ###

      # check :boolean, 'on'
      def check type, value, opts={}
        opts[:required] = true if opts.delete(:req)

        if value.to_s == ''
          if !opts[:default].nil?
            opts[:default]
          elsif opts[:required]
            error 'Argument missing'
          end
        else
          m = 'check_%s' % type
          hard_error 'Unsupported paramter type: %s' % type unless respond_to?(m)

          if opts[:array]
            delimiter = opts[:array].is_a?(TrueClass) ? /\s*[,:;]\s*/ : opts[:array]

            value = value.split(delimiter) unless value.is_a?(Array)
            value.map { |_| check_send m, _, opts }
          else
            check_send m, value, opts
          end
        end
      end

      private

      def check_send m, value, opts
        send(m, value, opts).tap do |_|
          error 'Value not in range of values' if opts[:values] && !opts[:values].include?(_)
        end
      end

      def error desc
        raise Joshua::Error, desc
      end

      def hard_error desc
        raise StandardError, desc
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
joshua-0.2.2 ./lib/joshua/params/parse.rb
joshua-0.2.1 ./lib/joshua/params/parse.rb
joshua-0.1.0 ./lib/joshua/params/parse.rb