Skip to content

Commit

Permalink
Adds Grape::ParameterTypes, but doesn't use it yet.
Browse files Browse the repository at this point in the history
  • Loading branch information
rnubel committed Jun 24, 2015
1 parent 7bc4deb commit 17fe211
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/grape.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
require 'active_support/core_ext/array/extract_options'
require 'active_support/core_ext/hash/deep_merge'
require 'active_support/dependencies/autoload'
require 'grape/util/content_types'
require 'multi_json'
require 'multi_xml'
require 'virtus'
Expand Down Expand Up @@ -160,6 +159,9 @@ module Presenters
end
end

require 'grape/util/content_types'
require 'grape/util/parameter_types'

require 'grape/validations/validators/base'
require 'grape/validations/attributes_iterator'
require 'grape/validations/validators/allow_blank'
Expand Down
43 changes: 43 additions & 0 deletions lib/grape/util/parameter_types.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
module Grape
module ParameterTypes
# Classes which we expect to be able to coerce through Virtus,
# or through any coercion logic built in to Grape.
KNOWN_TYPES = [
# Numerical
Integer,
Float,
BigDecimal,
Numeric,

# Data structures
Hash,
Array,
Set,

# Date/time
Date,
DateTime,
Time,

# Misc
Virtus::Attribute::Boolean,
String,
Symbol,
Rack::Multipart::UploadedFile
]

# @param type [Class] type to check
# @returns [Boolean] whether or not the type is known
# by Grape as an acceptable parameter type
def self.known_type?(type)
KNOWN_TYPES.include?(type)
end

# @param type [Class] type to check
# @returns [Boolean] whether or not the type can be used
# as a custom type
def self.custom_type?(type)
!known_type?(type) && type.respond_to?(:parse)
end
end
end
36 changes: 36 additions & 0 deletions spec/grape/util/parameter_types_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
require 'spec_helper'

describe Grape::ParameterTypes do
class FooType
def self.parse
end
end

describe '::known_type?' do
[
Integer, Float, Numeric, BigDecimal,
Virtus::Attribute::Boolean, String, Symbol,
Hash, Array, Set,
Date, DateTime, Time
].each do |type|
it "recognizes #{type} as a known type" do
expect(described_class.known_type?(type)).to be_truthy
end
end

it 'identifies unknown types' do
expect(described_class.known_type?(Object)).to be_falsy
expect(described_class.known_type?(FooType)).to be_falsy
end
end

describe '::custom_type?' do
it 'returns false if the type does not respond to :parse' do
expect(described_class.custom_type?(Object)).to be_falsy
end

it 'returns true if the type responds to :parse' do
expect(described_class.custom_type?(FooType)).to be_truthy
end
end
end

0 comments on commit 17fe211

Please sign in to comment.