Module: Obfuscated::ClassMethods

Defined in:
lib/obfuscated.rb

Instance Method Summary collapse

Instance Method Details

#has_obfuscated_id(options = {}) ⇒ Object



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
# File 'lib/obfuscated.rb', line 36

def has_obfuscated_id( options={} )
  class_eval do

    include Obfuscated::InstanceMethods

    # Uses an 12 character string to find the appropriate record
    def self.find_by_hashed_id( hash, options={} )
      # Don't bother if there's no hash provided.
      return nil if hash.blank?
      
      # If Obfuscated isn't supported, use ActiveRecord's default finder
      return find_by_id(hash, options) unless Obfuscated::supported?
      
      # Update the conditions to use the hash calculation
      db = ActiveRecord::Base.connection.class.to_s.downcase
      if db.include?('postgresql')
        options.update(:conditions => ["substring(encode(digest(concat('---',id::text,'-WICKED-#{self.table_name}-#{Obfuscated::salt}'), 'sha1'), 'hex'), 1, 12) = ?", hash])
      elsif db.include?('mysql')
        options.update(:conditions => ["SUBSTRING(SHA1(CONCAT('---',#{self.table_name}.id,'-WICKED-#{self.table_name}-#{Obfuscated::salt}')),1,12) = ?", hash])
      end
      # Find it!
      first(options) or raise ActiveRecord::RecordNotFound, "Couldn't find #{self.class.to_s} with Hashed ID=#{hash}"
    end
  end
end