Sha256: d49bddb678418842d06a8cb4224b6d7690c5630947de4bff839030398ff795fb

Contents?: true

Size: 1.94 KB

Versions: 1

Compression:

Stored size: 1.94 KB

Contents

module ParamChecker

  module_function

  def check_integer_param(param, default, min = nil, max = nil)
    min_lambda = (min.nil? ? lambda { true } : lambda { param.strip.to_i >= min })
    max_lambda = (max.nil? ? lambda { true } : lambda { param.strip.to_i <= max })

    if (param && param.strip =~ /^-?[0-9]+$/ && min_lambda.call && max_lambda.call)
      param.strip.to_i
    else
      default
    end
  end

  def check_float_param(param, default, min = nil, max = nil)
    min_lambda = (min.nil? ? lambda { true } : lambda { param.strip.to_i >= min })
    max_lambda = (max.nil? ? lambda { true } : lambda { param.strip.to_i <= max })

    if (param && param.strip =~ /^-?[0-9]+(\.[0-9]+)?$/ && min_lambda.call && max_lambda.call)
      param.strip.to_f
    else
      default.to_f
    end
  end

  def check_string_param(param, default, allowed)
    if (param && allowed.class == Regexp && param =~ allowed)
      param
    elsif (param && allowed.class == Array && allowed.include?(param))
      param
    elsif (param && allowed.class == String && allowed == param)
      param
    else
      default
    end
  end

  def check_symbol_param(param, default, allowed)
    begin
      if (param && allowed.class == Regexp && param.to_s =~ allowed)
        param.to_sym
      elsif (param && allowed.class == Array && allowed.map { |i| i.to_sym }.include?(param.to_sym))
        param.to_sym
      elsif (param && (allowed.class == String || allowed.class == Symbol) && allowed.to_sym == param.to_sym)
        param.to_sym
      else
        default.to_sym
      end
    rescue
      default.to_sym
    end
  end

  def check_boolean_param(param, default)
    if (param && param == "1" || param == "true")
      true
    elsif (param && param == "0" || param == "false")
      false
    else
      default
    end
  end

  public :check_integer_param,
         :check_float_param,
         :check_string_param,
         :check_symbol_param,
         :check_boolean_param
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
param_checker-0.0.2 lib/param_checker.rb