module OStruct::Sanitizer::ClassMethods
Provides sanitization rules that can be declaratively applied to OpenStruct fields, similar to hooks on Rails models.
Attributes
Public Instance Methods
Remove any non-alphanumeric character from the field's value
@param [Array<Symbol>] a list of field names to be sanitized
# File lib/ostruct/sanitizer.rb, line 126 def alphanumeric(*fields) sanitize(*fields) { |value| value.gsub(/[^A-Za-z0-9\s]/, '') } end
Removes any non-digit character from the values of the given fields
@param [Array<Symbol>] fields list of fields to be sanitized
# File lib/ostruct/sanitizer.rb, line 142 def digits(*fields) sanitize(*fields) { |value| value.to_s.gsub(/[^0-9]/, '') } end
Registers a sanitization block for a given field
@param [Array<Symbol>] a list of field names to be sanitized @param [#call] block sanitization block to be applied to the current value of each field and returns the new sanitized value
# File lib/ostruct/sanitizer.rb, line 102 def sanitize(*fields, &block) @sanitizers ||= {} fields.each do |field| field_sanitizers = @sanitizers[field.to_sym] ||= [] field_sanitizers << block end end
Strips out leading and trailing spaces from the values of the given fields
@param [Array<Symbol>] fields list of fields to be sanitized
# File lib/ostruct/sanitizer.rb, line 134 def strip(*fields) sanitize(*fields) { |value| value.strip } end
Truncates fields to a given length value
@param [Array<Symbol>] a list of field names to be sanitized @param [Integer] length the amount to truncate the field's value to @param [Boolean] strip_whitespaces whether or not to strip whitespaces
# File lib/ostruct/sanitizer.rb, line 116 def truncate(*fields, length:, strip_whitespaces: true) strip(*fields) if strip_whitespaces sanitize(*fields) { |value| value[0...length] } strip(*fields) if strip_whitespaces end