Sha256: 8a9ab7a7e44f597dc25cdf7d24c85b8c2837e0da9df0695009a5d6dfef8e5f6c

Contents?: true

Size: 1.41 KB

Versions: 36

Compression:

Stored size: 1.41 KB

Contents

# frozen_string_literal: true

# Argument validation.
class Args
  def self.fetch_non_empty_string(hash, key)
    value = fetch_non_nil(hash, key, String)
    raise ArgumentError, "parameter #{key} empty" if value.strip.empty?

    value
  end

  def self.fetch_non_empty_int(hash, key)
    fetch_non_nil(hash, key, Integer)
  end

  def self.fetch_non_empty_hash(hash, key)
    value = fetch_non_nil(hash, key, Hash)
    raise ArgumentError, "parameter #{key} empty" if value.empty?

    value
  end

  def self.fetch_optional_hash(hash, key)
    fetch_optional(hash, key, Hash)
  end

  def self.fetch_optional_array(hash, key)
    fetch_optional(hash, key, Array)
  end

  def self.fetch_non_nil(hash, key, *classes)
    raise ArgumentError, "parameter #{key} missing" unless hash.key?(key)

    raise ArgumentError, "parameter #{key} null" if hash[key].nil?

    fetch_optional(hash, key, *classes)
  end

  def self.fetch_optional(hash, key, *classes)
    value = hash[key]
    if value && classes.size.positive? && !classes.find { |clazz| value.is_a?(clazz) }
      if classes.size != 1
        raise ArgumentError, "parameter #{key} not #{classes.map(&:to_s).map(&:downcase).join(' or ')}"
      end

      class_name = classes[0].to_s.downcase
      class_name = %w[a e i o u].include?(class_name[0]) ? "an #{class_name}" : "a #{class_name}"
      raise ArgumentError, "parameter #{key} not #{class_name}"
    end

    value
  end
end

Version data entries

36 entries across 36 versions & 1 rubygems

Version Path
sqlui-0.1.84 app/args.rb
sqlui-0.1.83 app/args.rb
sqlui-0.1.82 app/args.rb
sqlui-0.1.81 app/args.rb
sqlui-0.1.80 app/args.rb
sqlui-0.1.79 app/args.rb
sqlui-0.1.78 app/args.rb
sqlui-0.1.77 app/args.rb
sqlui-0.1.76 app/args.rb
sqlui-0.1.75 app/args.rb
sqlui-0.1.74 app/args.rb
sqlui-0.1.73 app/args.rb
sqlui-0.1.72 app/args.rb
sqlui-0.1.71 app/args.rb
sqlui-0.1.70 app/args.rb
sqlui-0.1.69 app/args.rb
sqlui-0.1.68 app/args.rb
sqlui-0.1.67 app/args.rb
sqlui-0.1.66 app/args.rb
sqlui-0.1.65 app/args.rb