Guest User

Untitled

a guest
Jan 25th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. User Model
  2. ==========
  3. require 'digest'
  4. class User < ActiveRecord::Base
  5. attr_accessor :password
  6.  
  7. has_one :profile
  8. has_many :articles, :order => 'published_at DESC, title ASC',
  9. :dependent => :nullify
  10. has_many :replies, :through => :articles, :source => :comments
  11.  
  12. validates :email, :uniqueness => true,
  13. :length => { :within => 5..50 },
  14. :format => { :with => /^[^@][\w.-]+@[\w.-]+[.][a-z]{2,4}$/i }
  15. validates :password,:confirmation => true,
  16. :length => { :within => 4..20 },
  17. :presence => true,
  18. :if => :password_required?
  19.  
  20. before_save :encrypt_new_password
  21.  
  22. def self.authenticate(email, password)
  23. user = find_by_email(email)
  24. return user if user && user.authenticated?(password)
  25. end
  26.  
  27. def authenticated?(password)
  28. self.hashed_password == encrypt(password)
  29. end
  30.  
  31. protected
  32.  
  33. def encrypt_new_password
  34. return if password.blank?
  35. self.hashed_password = encrypt(password)
  36. end
  37.  
  38. def password_required?
  39. hashed_password.blank? || password.present?
  40. end
  41.  
  42. def encrypt(string)
  43. Digest::SHA1.hexdigest(string)
  44. end
  45.  
  46. end
  47.  
  48. CONSOLE
  49. =======
  50. ruby-1.9.2-p180 :001 > u = User.find(5)
  51. => #<User id: 5, email: "me@example.com", hashed_password: "password", created_at: "2011-07-26 10:03:41", updated_at: "2011-07-26 10:03:41">
  52. ruby-1.9.2-p180 :002 > u.update_attributes(:password => "password", :password_confirmation => "password")
  53. => false
  54. ruby-1.9.2-p180 :003 > u.errors
  55. => {:email=>["has already been taken"]}
  56. ruby-1.9.2-p180 :004 >
Add Comment
Please, Sign In to add comment