Module: Obfuscate::Obfuscatable::ClassMethods

Defined in:
lib/obfuscate/obfuscatable.rb

Instance Method Summary collapse

Instance Method Details

#obfuscatable(options = {}) ⇒ Object

Make this Model Obfuscatable. Adds method obfuscate_id which obfuscates the id to 11 characters. Cavaet: Only supports id lengths up to 8 (e.g. 99,999,999) due to use of Blowfish block encryption.

Parameters:

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :salt (Symbol)

    A Model specific salt, length must be between 1-56

  • :append_salt (Symbol)

    Append string to default salt and use for this Model. Overwrites the salt option.

  • :encode (Symbol)

    Enable Base64 and URL encoding for this Model. Enabled by default.

  • :remove_trailing_equal (Symbol)

    When in :block mode, removes the trailing = from the obfuscated text.



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/obfuscate/obfuscatable.rb', line 33

def obfuscatable(options = {})
  # :append_salt will append the string to the default salt
  append_salt = options.with_indifferent_access.delete(:append_salt)
  if append_salt
    options[:salt] = "#{Obfuscate.config.salt}#{append_salt}"
  end
  
  
  config = Obfuscate.config.apply(options)

  cattr_accessor :obfuscatable_config
  self.obfuscatable_config = config

  cattr_accessor :obfuscatable_crypt
  self.obfuscatable_crypt = Obfuscate::Crypt.new( config )

  define_method :obfuscated_id do
    self.obfuscatable_crypt.obfuscate( self.id, :block )
  end

  define_method :clarify_id do |text|
    self.class.clarify_id( text )
  end

  class << self

    # Find by obfuscated_id
    #
    # @return [Object]
    def find_by_obfuscated_id( text )
      find_by_id( clarify_id( text ) )
    end

    # Find by obfuscated_id
    # @raises ActiveRecord::RecordNotFound
    # @return [Object]
    def find_obfuscated( text )
      find( clarify_id( text ) )
    end

    # Clarifies obfuscated Model id
    # @return [String]
    def clarify_id( text )
      begin
        self.obfuscatable_crypt.clarify( text, :block )
      rescue ArgumentError
        # invalid text passed in, causing a Base64 decode error, ignore.
      end
    end

    # Clarify obfuscated text.
    #
    # @param [String] text to clarify
    # @param [Symbol] mode to clarify, defaults to :string
    def clarify( text, mode = :string)
      self.obfuscatable_crypt.clarify(text, mode)
    end

    #
    # @param [String] text to clarify
    # @param [Symbol] mode to clarify, defaults to :string
    def obfuscate( text, mode = :string)
      self.obfuscatable_crypt.obfuscate(text, mode)
    end
  end
end