Module: ActsAsObfuscated::ClassMethods

Defined in:
app/models/concerns/acts_as_obfuscated.rb

Instance Method Summary collapse

Instance Method Details

#deobfuscate(original, rescue_with_original_id = true) ⇒ Object

If rescue_with_original_id is set to true the original ID will be returned when its Obfuscated Id is not found

We use this as the default behaviour on everything except Class.find()



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'app/models/concerns/acts_as_obfuscated.rb', line 75

def deobfuscate(original, rescue_with_original_id = true)
  if original.kind_of?(Array)
    return original.map { |value| deobfuscate(value, true) } # Always rescue with original ID
  elsif !(original.kind_of?(Integer) || original.kind_of?(String))
    return original
  end

  # Remove any non-digit formatting characters, and only consider the first 10 digits
  obfuscated_id = original.to_s.delete('^0-9').first(10)

  # 2147483647 is PostgreSQL's Integer Max Value.  If we return a value higher than this, we get weird DB errors
  revealed = [EffectiveObfuscation.show(obfuscated_id, acts_as_obfuscated_opts[:spin]).to_i, 2147483647].min

  if rescue_with_original_id && (revealed >= 2147483647 || revealed > deobfuscated_maximum_id)
    original
  else
    revealed
  end
end

#deobfuscated_maximum_idObject



110
111
112
# File 'app/models/concerns/acts_as_obfuscated.rb', line 110

def deobfuscated_maximum_id
  acts_as_obfuscated_opts[:max_id] ||= (self.unscoped.maximum(:id) rescue 2147483647)
end

#deobfuscator(left) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'app/models/concerns/acts_as_obfuscated.rb', line 95

def deobfuscator(left)
  acts_as_obfuscated_opts[:deobfuscators] ||= Hash.new().tap do |deobfuscators|
    deobfuscators['id'] = Proc.new { |right| self.deobfuscate(right) }

    reflect_on_all_associations(:belongs_to).each do |reflection|
      if (reflection.klass rescue nil).respond_to?(:deobfuscate)
        deobfuscators[reflection.foreign_key] = Proc.new { |right| reflection.klass.deobfuscate(right) }
        # Should override the foreign_object_id= method and deobfuscate it too
      end
    end
  end

  acts_as_obfuscated_opts[:deobfuscators][left.to_s]
end

#obfuscate(original) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
# File 'app/models/concerns/acts_as_obfuscated.rb', line 60

def obfuscate(original)
  obfuscated = EffectiveObfuscation.hide(original, acts_as_obfuscated_opts[:spin])

  if acts_as_obfuscated_opts[:format] # Transform 1234567890 from ###-####-### into 123-4567-890 as per :format option
    acts_as_obfuscated_opts[:format].dup.tap do |formatted|
      10.times { |x| formatted.sub!('#', obfuscated[x]) }
    end
  else
    obfuscated
  end
end

#relationObject



115
116
117
# File 'app/models/concerns/acts_as_obfuscated.rb', line 115

def relation
  super.tap { |relation| relation.extend(FinderMethods) }
end