module Anony::FieldLevelStrategies
This class is a singleton, containing all of the known strategies that Anony
can use to anonymise individual fields in your models.
Public Class Methods
Helper method for retrieving the strategy block (or testing that it exists).
@param name [Symbol] The name of the strategy to retrieve. @raise [ArgumentError] If the strategy is not already registered
# File lib/anony/field_level_strategies.rb, line 66 def self.[](name) @strategies.fetch(name) do raise ArgumentError, "Unrecognised strategy `#{name.inspect}`" end end
Registers a new Anony
strategy (or overwrites an existing strategy) of a given name. Strategies
are then available everywhere inside the `anonymise` block.
@param name [Symbol] The name of the strategy you'd like to use @param klass_or_constant [Object] The object you'd like to statically return, or an
object which responds to `#call(original_value)`.
@yield [original_value] The previous value of the field. The result of the block
will be applied to that field. If a block is not given, klass_or_constant will be used as the strategy instead.
@raise [ArgumentError] If using neither a block nor strategy class
@example Reversing a string using a block
Anony::FieldLevelStrategies.register(:reverse) do |original_value| original_value.reverse end class Manager anonymise { reverse :first_name } end
@example Using a named strategy class
class Classifier def self.call(original_value) "Classy version of #{original_value}" end end Anony::FieldLevelStrategies.register(:classify, Classifier) class Manager anonymise { classify :resource_type } end
@example Using a constant value
Anony::FieldLevelStrategies.register(:forty_two, 42) class Manager anonymise { forty_two :date_of_birth } end
# File lib/anony/field_level_strategies.rb, line 48 def self.register(name, klass_or_constant = nil, &block) if block strategy = block elsif !klass_or_constant.nil? strategy = klass_or_constant else raise ArgumentError, "Must pass either a block, constant value or strategy class" end define_method(name) { |*fields| with_strategy(strategy, *fields) } @strategies[name] = strategy end