Class: Objective::Filters::StringFilter

Inherits:
Objective::Filter show all
Defined in:
lib/objective/filters/string_filter.rb

Constant Summary collapse

Options =
OpenStruct.new(
  nils: Objective::DENY,
  invalid: Objective::DENY,
  strict: false,
  empty: Objective::DENY,
  squish: true,
  min: nil,
  max: nil,
  in: nil,
  matches: nil,
  decimal_format: 'F',
  coercable_classes: [Symbol, TrueClass, FalseClass, Integer, Float, BigDecimal].freeze
)

Instance Attribute Summary

Attributes inherited from Objective::Filter

#key, #sub_filters

Instance Method Summary collapse

Methods inherited from Objective::Filter

#default, #default?, #dup, #feed, #feed_empty, #feed_invalid, #feed_nil, #feed_result, #handle_errors, inherited, #initialize, #options, #sub_filters_hash

Constructor Details

This class inherits a constructor from Objective::Filter

Instance Method Details

#coercable?(raw) ⇒ Boolean

Returns:

  • (Boolean)


27
28
29
# File 'lib/objective/filters/string_filter.rb', line 27

def coercable?(raw)
  options.coercable_classes.map { |klass| raw.is_a?(klass) }.any?
end

#coerce(raw) ⇒ Object



20
21
22
23
24
25
# File 'lib/objective/filters/string_filter.rb', line 20

def coerce(raw)
  return raw unless raw.is_a?(String) || coercable?(raw)
  tmp = raw.is_a?(BigDecimal) ? raw.to_s(options.decimal_format) : raw.to_s
  tmp = tmp.gsub(/[[:space:]]+/, ' ').strip if options.squish
  tmp
end

#coerce_error(coerced) ⇒ Object



31
32
33
# File 'lib/objective/filters/string_filter.rb', line 31

def coerce_error(coerced)
  return :string unless coerced.is_a?(String)
end

#validate(coerced) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/objective/filters/string_filter.rb', line 35

def validate(coerced)
  return :empty if coerced.empty?
  return :min if options.min && coerced.length < options.min
  return :max if options.max && coerced.length > options.max
  return :in if options.in && !options.in.include?(coerced)
  return :matches if options.matches && (options.matches !~ coerced)
end