Module: OStruct::Sanitizer

Defined in:
lib/ostruct/sanitizer.rb,
lib/ostruct/sanitizer/version.rb

Overview

Provides a series of sanitization rules to be applied on OpenStruct fields on a Rails-ish fashion.

Examples:

class Person < OpenStruct
  include WellsFargoRetail::Sanitizer

  truncate :name, length: 20
  drop_punctuation :name
  sanitize :middle_name do |value|
    # Perform a more complex sanitization process
  end
end

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VERSION =
"0.2.0"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/ostruct/sanitizer.rb', line 20

def self.included(base)
  unless base.ancestors.include? OpenStruct
    raise "OpenStructSanitizer can only be used within OpenStruct classes."
  end

  base.extend ClassMethods
end

Instance Method Details

#initialize(attrs = {}) ⇒ Object

Initializes the OpenStruct applying any registered sanitization rules



30
31
32
33
34
35
# File 'lib/ostruct/sanitizer.rb', line 30

def initialize(attrs = {})
  super
  attrs.each_pair do |field, value|
    self.send("#{field}=", value)
  end
end

#new_ostruct_member(field) ⇒ Symbol

Overrides ostruct member definition applying sanitization rules when needed

Parameters:

  • field (#to_sym)

    the name of the field being defined

Returns:

  • (Symbol)

    the name of the defined field



42
43
44
45
46
47
48
49
50
51
# File 'lib/ostruct/sanitizer.rb', line 42

def new_ostruct_member(field)
  field = field.to_sym
  unless respond_to?(field)
    define_singleton_method(field) { modifiable[field] }
    define_singleton_method("#{field}=") do |value|
      modifiable[field] = sanitize(field, value)
    end
  end
  field
end