Class: ApiQueryLanguage::Filtering::Fields::FilterValueCaster
- Inherits:
-
Object
- Object
- ApiQueryLanguage::Filtering::Fields::FilterValueCaster
- Defined in:
- lib/api_query_language/filtering/fields/filter_value_caster.rb
Overview
type_caster must duck-type two methods:
.type → Symbol drawn from SUPPORTED_TYPES
.cast(value) → typed value or nil
The AR column type_caster satisfies this; consumers can inject their own.
Constant Summary collapse
- SUPPORTED_TYPES =
%i[boolean date datetime decimal float integer string text time].freeze
- BOOLEAN_TRUE_VALUES =
%w[1 t T true TRUE True on ON yes Y y].freeze
- BOOLEAN_FALSE_VALUES =
%w[0 f F false FALSE False off OFF no N n].freeze
Instance Method Summary collapse
- #cast(value) ⇒ Object
-
#initialize(type_caster, supported_types: SUPPORTED_TYPES) ⇒ FilterValueCaster
constructor
A new instance of FilterValueCaster.
Constructor Details
#initialize(type_caster, supported_types: SUPPORTED_TYPES) ⇒ FilterValueCaster
Returns a new instance of FilterValueCaster.
15 16 17 18 19 |
# File 'lib/api_query_language/filtering/fields/filter_value_caster.rb', line 15 def initialize(type_caster, supported_types: SUPPORTED_TYPES) raise Errors::UnsupportedFieldTypeError.new(type_caster.type) unless supported_types.include?(type_caster.type) @type_caster = type_caster end |
Instance Method Details
#cast(value) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/api_query_language/filtering/fields/filter_value_caster.rb', line 21 def cast(value) raise ArgumentError, "Value must be a string" unless value.is_a?(String) case type when :integer, :decimal, :float raise Errors::InvalidFieldValueError.new(type, value) unless numeric_value?(value) convert_numeric(value) when :boolean if BOOLEAN_TRUE_VALUES.include?(value) true elsif BOOLEAN_FALSE_VALUES.include?(value) false else raise Errors::InvalidFieldValueError.new(type, value) end else @type_caster.cast(value).tap do |casted_value| raise Errors::InvalidFieldValueError.new(@type_caster.type, value) if casted_value.nil? end end end |