module OStruct::Sanitizer::ClassMethods

Provides sanitization rules that can be declaratively applied to OpenStruct fields, similar to hooks on Rails models.

Attributes

sanitizers[RW]

Public Instance Methods

alphanumeric(*fields) click to toggle source

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
digits(*fields) click to toggle source

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
sanitize(*fields, &block) click to toggle source

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
strip(*fields) click to toggle source

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
truncate(*fields, length:, strip_whitespaces: true) click to toggle source

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