Class: EvilSeed::Anonymizer

Inherits:
Object
  • Object
show all
Defined in:
lib/evil_seed/anonymizer.rb

Overview

This class constructs customizer callable with simple DSL:

config.anonymize("User")
  name  { Faker::Name.name }
  email { Faker::Internet.email }
end

Resulting object can be called with record attributes and will return modified copy.

attrs = { name: 'Luke', email: '[email protected]' }
a.call(attrs)
attrs # => { name: 'John', email: '[email protected]' }

Instance Method Summary collapse

Constructor Details

#initialize(model_name, &block) ⇒ Anonymizer

Returns a new instance of Anonymizer.

Parameters:

  • model_name (String)

    A string containing class name of your ActiveRecord model



19
20
21
22
23
# File 'lib/evil_seed/anonymizer.rb', line 19

def initialize(model_name, &block)
  @model_class = model_name.constantize
  @changers = {}
  instance_eval(&block)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(attribute_name, &block) ⇒ Object (private)



41
42
43
44
# File 'lib/evil_seed/anonymizer.rb', line 41

def method_missing(attribute_name, &block)
  return super unless @model_class.column_names.include?(attribute_name.to_s)
  @changers[attribute_name.to_s] = block
end

Instance Method Details

#call(attributes) ⇒ Hash{String=>void}

Returns Modified deep copy of attributes.

Parameters:

  • attributes (Hash{String=>void})

    Record attributes.

Returns:

  • (Hash{String=>void})

    Modified deep copy of attributes



27
28
29
30
31
32
33
# File 'lib/evil_seed/anonymizer.rb', line 27

def call(attributes)
  attributes.deep_dup.tap do |attrs|
    @changers.each do |attribute, changer|
      attrs[attribute] = changer.call(attrs[attribute])
    end
  end
end

#respond_to_missing?(attribute_name) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/evil_seed/anonymizer.rb', line 35

def respond_to_missing?(attribute_name)
  @model_class.column_names.include?(attribute_name.to_s) || super
end