Commit 44e4b51f by Stanton Cole Bradley

Merge pull request #1 from stantoncbradley/array-validation

Array validation
parents c6d98432 f028ba3f
module RailsParam
module Param
DEFAULT_PRECISION = 14
class InvalidParameterError < StandardError
attr_accessor :param, :options
end
def param!(name, type, options = {})
name = name.to_s
class MockController
include RailsParam::Param
attr_accessor :params
end
def param!(name, type, options = {}, &block)
name = name.to_s unless name.is_a? Integer # keep index for validating elements
return unless params.member?(name) || options[:default].present? || options[:required]
......@@ -15,8 +22,25 @@ module RailsParam
params[name] = (options[:default].call if options[:default].respond_to?(:call)) || options[:default] if params[name].nil? and options[:default]
params[name] = options[:transform].to_proc.call(params[name]) if params[name] and options[:transform]
validate!(params[name], options)
if block_given?
if type == Array
params[name].each_with_index do |element, i|
if element.is_a?(Hash)
recurse element, &block
else
params[name][i] = recurse({ i => element }, i, &block) # supply index as key unless value is hash
end
end
else
recurse params[name], &block
end
end
params[name]
rescue InvalidParameterError => exception
exception.param, exception.options = name, options
exception.param ||= name
exception.options ||= options
raise exception
end
end
......@@ -41,6 +65,13 @@ module RailsParam
private
def recurse(params, index = nil)
raise InvalidParameterError, 'no block given' unless block_given?
controller = RailsParam::Param::MockController.new
controller.params = params
yield(controller, index)
end
def coerce(param, type, options = {})
begin
return nil if param.nil?
......@@ -52,8 +83,12 @@ module RailsParam
return Time.parse(param) if type == Time
return DateTime.parse(param) if type == DateTime
return Array(param.split(options[:delimiter] || ",")) if type == Array
return Hash[param.split(options[:delimiter] || ",").map{|c| c.split(options[:separator] || ":")}] if type == Hash
return Hash[param.split(options[:delimiter] || ",").map { |c| c.split(options[:separator] || ":") }] if type == Hash
return (/(false|f|no|n|0)$/i === param.to_s ? false : (/(true|t|yes|y|1)$/i === param.to_s ? true : nil)) if type == TrueClass || type == FalseClass || type == :boolean
if type == BigDecimal
param = param.delete('$,').strip.to_f if param.is_a?(String)
return BigDecimal.new(param, (options[:precision] || DEFAULT_PRECISION))
end
return nil
rescue ArgumentError
raise InvalidParameterError, "'#{param}' is not a valid #{type}"
......
......@@ -17,4 +17,18 @@ class FakeController < ActionController::Base
def new
render text: "new"
end
def edit
param! :book, Hash, required: true do |b|
b.param! :title, String, required: true
b.param! :author, Hash do |a|
a.param! :first_name, String, required: true
a.param! :last_name, String, required: true
a.param! :age, Integer, required: true
end
b.param! :price, BigDecimal, required: true
end
render text: :book
end
end
......@@ -15,6 +15,7 @@ module Rails
get '/fake/new' => "fake#new"
get '/fakes' => "fake#index"
get '/fake/(:id)' => "fake#show"
get '/fake/edit' => "fake#edit"
end
@routes
end
......
......@@ -10,12 +10,60 @@ describe FakeController, type: :controller do
end
end
describe "nested_hash" do
it "validates nested properties" do
params = {
'book' => {
'title' => 'One Hundred Years of Solitude',
'author' => {
'first_name' => 'Garbriel Garcia',
'last_name' => 'Marquez',
'age' => '70'
},
'price' => '$1,000.00'
}}
get :edit, params
expect(controller.params[:book][:author][:age]).to eql 70
expect(controller.params[:book][:author][:age]).to be_kind_of Integer
expect(controller.params[:book][:price]).to eql 1000.0
expect(controller.params[:book][:price]).to be_instance_of BigDecimal
end
it "raises error when required nested attribute missing" do
params = {
'book' => {
'title' => 'One Hundred Years of Solitude',
'author' => {
'last_name' => 'Marquez',
'age' => '70'
},
'price' => '$1,000.00'
}}
expect { get :edit, params }.to raise_error { |error|
expect(error).to be_a(RailsParam::Param::InvalidParameterError)
expect(error.param).to eql("first_name")
expect(error.options).to eql({:required => true})
}
end
it "passes when hash that's not required but has required attributes is missing" do
params = {
'book' => {
'title' => 'One Hundred Years of Solitude',
'price' => '$1,000.00'
}}
get :edit, params
expect(controller.params[:book][:price]).to eql 1000.0
expect(controller.params[:book][:price]).to be_instance_of BigDecimal
end
end
describe "InvalidParameterError" do
it "raises an exception with params attributes" do
expect { get :index, sort: "foo" }.to raise_error { |error|
expect(error).to be_a(RailsParam::Param::InvalidParameterError)
expect(error.param).to eql("sort")
expect(error.options).to eql({ :in => ["asc", "desc"], :default => "asc", :transform => :downcase })
expect(error.options).to eql({:in => ["asc", "desc"], :default => "asc", :transform => :downcase})
}
end
end
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment