Module: HasDigest
- Defined in:
- lib/has_digest.rb
Defined Under Namespace
Modules: ClassMethods
Class Method Summary collapse
-
.included(base) ⇒ Object
:nodoc:.
Instance Method Summary collapse
-
#digest(*values) ⇒ Object
Returns a 40-character hexadecimal token.
-
#generate_has_digest_attributes ⇒ Object
:nodoc:.
Class Method Details
.included(base) ⇒ Object
:nodoc:
4 5 6 7 |
# File 'lib/has_digest.rb', line 4 def self.included(base) # :nodoc: base.before_save :generate_has_digest_attributes, :unless => lambda { |record| record.class.has_digest_attributes.empty? } base.extend(ClassMethods) end |
Instance Method Details
#digest(*values) ⇒ Object
Returns a 40-character hexadecimal token. When no values
are given, the token is seeded with a randomized form of the current time. When values
are given, the token is seeded with them instead, unless any of them evaluate to false
, in which case the returned token is nil
.
digest
is available as an instance method on any of your ActiveRecord
models, so you can use it as needed. For example:
class User < ActiveRecord::Base
def authenticate(password)
encrypted_password == digest(salt, password)
end
end
20 21 22 23 24 25 26 27 28 |
# File 'lib/has_digest.rb', line 20 def digest(*values) if values.empty? Digest::SHA1.hexdigest(Time.now.to_default_s.split(//).sort_by { Kernel.rand }.join) elsif values.all? Digest::SHA1.hexdigest("--#{values.join('--')}--") else nil end end |
#generate_has_digest_attributes ⇒ Object
:nodoc:
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/has_digest.rb', line 30 def generate_has_digest_attributes # :nodoc: if new_record? if attribute_names.include?('salt') self[:salt] = digest end self.class.standalone_has_digest_attributes.each do |name, | self[name] = digest end end lookup_value = lambda { |dependency| send(dependency) } self.class.dependent_has_digest_attributes.each do |name, | dependencies = [:dependencies] synthetic_dependencies = [:synthetic_dependencies] if synthetic_dependencies.all?(&lookup_value) self[name] = digest(*dependencies.map(&lookup_value)) end end end |