From 0318747b145034af7fd138a303d56e4fdf001584 Mon Sep 17 00:00:00 2001 From: Raph Estrada Date: Sun, 22 Oct 2017 15:38:49 +0100 Subject: [PATCH] add TypeFilter to additional filters This PR adds a filter for object inputs of a certain type. --- lib/mutations.rb | 1 + lib/mutations/type_filter.rb | 21 ++++++++++++ spec/type_filter_spec.rb | 64 ++++++++++++++++++++++++++++++++++++ 3 files changed, 86 insertions(+) create mode 100644 lib/mutations/type_filter.rb create mode 100644 spec/type_filter_spec.rb diff --git a/lib/mutations.rb b/lib/mutations.rb index cae4ef0..da18f31 100644 --- a/lib/mutations.rb +++ b/lib/mutations.rb @@ -9,6 +9,7 @@ require 'mutations/errors' require 'mutations/input_filter' require 'mutations/additional_filter' +require 'mutations/type_filter' require 'mutations/string_filter' require 'mutations/integer_filter' require 'mutations/float_filter' diff --git a/lib/mutations/type_filter.rb b/lib/mutations/type_filter.rb new file mode 100644 index 0000000..ab4cac2 --- /dev/null +++ b/lib/mutations/type_filter.rb @@ -0,0 +1,21 @@ +module Mutations + class TypeFilter < AdditionalFilter + @default_options = { + :nils => false, # true allows an explicit nil to be valid. Overrides any other options + :klass => nil, # require the input to be of this type + } + + def filter(data) + if data.nil? + return [nil, nil] if options[:nils] + return [nil, :nils] + end + + klass = options[:klass] + return [nil, :klass] unless klass.is_a?(Class) + return [nil, :invalid] unless data.is_a?(klass) + + [data, nil] + end + end +end diff --git a/spec/type_filter_spec.rb b/spec/type_filter_spec.rb new file mode 100644 index 0000000..d5c0b71 --- /dev/null +++ b/spec/type_filter_spec.rb @@ -0,0 +1,64 @@ +require 'spec_helper' + +describe Mutations::TypeFilter do + let(:options){ {} } + let(:outcome){ Mutations::TypeFilter.new(options).filter(input) } + let(:result){ outcome[0] } + let(:errors){ outcome[1] } + + describe 'klass input' do + class Foo + end + + let(:options){ { klass: Foo } } + + describe 'exactly klass' do + let(:input){ Foo.new } + + it{ assert_equal(result, input) } + it{ assert_nil(errors) } + end + + describe 'subclass of klass' do + let(:input){ Class.new(Foo).new } + + it{ assert_equal(result, input) } + it{ assert_nil(errors) } + end + + describe 'not a Class' do + let(:options){ { klass: 123 } } + let(:input){ Foo.new } + + it{ assert_nil(result) } + it{ assert_equal(errors, :klass) } + end + + describe 'not a klass' do + let(:input){ Class.new } + + it{ assert_nil(result) } + it{ assert_equal(errors, :invalid) } + end + + end + + describe 'nil input' do + let(:input){ nil } + + describe 'nils allowed' do + let(:options){ { nils: true } } + + it{ assert_nil(result) } + it{ assert_nil(errors) } + end + + describe 'nils not allowed' do + let(:options){ { nils: false } } + + it{ assert_nil(result) } + it{ assert_equal(errors, :nils) } + end + end + +end