Sha256: 33a3d6629d9dce6f68a2f23ac310b0fb3248ef0deefe281e09284a712169f62c

Contents?: true

Size: 1.24 KB

Versions: 7

Compression:

Stored size: 1.24 KB

Contents

module Squall
  class Params
    # Required
    attr_accessor :valid

    # Optional
    attr_accessor :optional

    def initialize
      @valid    = []
      @optional = []
    end

    def required(*options)
      @valid = options.flatten.map { |o| o.to_sym}
      @valid.uniq!
      @optional.concat @valid
      @optional.uniq!
      self
    end

    def accepts(*options)
      @optional.concat options.flatten.map { |o| o.to_sym}
      @optional.uniq!
      self
    end

    def validate!(*options)
      validate_required!(*options) unless @valid.empty?
      validate_optionals!(*options) unless @optional.empty?
    end

    def validate_required!(*options)
      options = options.first.keys if options.first.respond_to?(:keys)
      options.map! { |o| o.respond_to?(:to_sym) ? o.to_sym : o }
      delta = (@valid - options)
      raise ArgumentError, "Missing required params: #{delta.join(',')}" if delta.any?
      true
    end

    def validate_optionals!(*options)
      options = options.first.keys if options.first.respond_to?(:keys)
      options.map! { |o| o.respond_to?(:to_sym) ? o.to_sym : o }
      options.each do |key|
        raise ArgumentError, "Unknown params: #{key}" unless @optional.include?(key)
      end
      true
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
squall-1.3.0 lib/squall/support/params.rb
squall-1.2.1beta1 lib/squall/support/params.rb
squall-1.2.0beta1 lib/squall/support/params.rb
squall-1.1.0 lib/squall/support/params.rb
squall-1.0.2 lib/squall/params.rb
squall-1.0.1 lib/squall/params.rb
squall-1.0.0 lib/squall/params.rb