Module: OStruct::Sanitizer::ClassMethods

Defined in:
lib/ostruct/sanitizer.rb

Overview

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#sanitizersObject

Returns the value of attribute sanitizers.



70
71
72
# File 'lib/ostruct/sanitizer.rb', line 70

def sanitizers
  @sanitizers
end

Instance Method Details

#digits(*fields) ⇒ Object

Removes any non-digit character from the values of the given fields



118
119
120
121
122
# File 'lib/ostruct/sanitizer.rb', line 118

def digits(*fields)
  fields.each do |field|
    sanitize(field) { |value| value.to_s.gsub(/[^0-9]/, '') }
  end
end

#drop_punctuation(*fields) ⇒ Object

Drops any punctuation character from the field’s value



98
99
100
101
102
# File 'lib/ostruct/sanitizer.rb', line 98

def drop_punctuation(*fields)
  fields.each do |field|
    sanitize(field) { |value| value.gsub(/[^\w\s]/, '') }
  end
end

#sanitize(field, &block) ⇒ Object

Registers a sanitization block for a given field



77
78
79
80
81
# File 'lib/ostruct/sanitizer.rb', line 77

def sanitize(field, &block)
  @sanitizers ||= {}
  field_sanitizers = @sanitizers[field] ||= []
  field_sanitizers << block
end

#strip(*fields) ⇒ Object

Strips out leading and trailing spaces from the values of the given fields



108
109
110
111
112
# File 'lib/ostruct/sanitizer.rb', line 108

def strip(*fields)
  fields.each do |field|
    sanitize(field) { |value| value.strip }
  end
end

#truncate(*fields, length:) ⇒ Object

Truncates fields to a given length value



88
89
90
91
92
# File 'lib/ostruct/sanitizer.rb', line 88

def truncate(*fields, length:)
  fields.each do |field|
    sanitize(field) { |value| value[0...length] }
  end
end