Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add TypeFilter to additional filters #120

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/mutations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
21 changes: 21 additions & 0 deletions lib/mutations/type_filter.rb
Original file line number Diff line number Diff line change
@@ -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
64 changes: 64 additions & 0 deletions spec/type_filter_spec.rb
Original file line number Diff line number Diff line change
@@ -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