master
1class User < ApplicationRecord
2 has_secure_password
3 before_save :ensure_authentication_token
4 after_create :send_welcome_email unless Rails.env.test?
5
6 validates :name, presence: true
7 validates :email, presence: true, uniqueness: true, email: true
8 validates :website, format: URI::regexp(%w(http https)), allow_blank: true
9 validates_length_of :password, within: 6..20, allow_blank: true
10
11 has_many :creations, dependent: :destroy
12 has_many :favorites, dependent: :destroy
13 has_many :tutorials, dependent: :destroy
14 has_many :activities, dependent: :destroy
15 has_many :comments, dependent: :destroy
16 has_many :user_sessions, dependent: :destroy
17 has_and_belongs_to_many :interests, join_table: 'users_interests', autosave: true
18 has_one :avatar, class_name: 'Photo', as: :imageable
19 acts_as_tagger
20
21 def add_favorite(cake)
22 return if self.owns(cake)
23 cake.liked_by(self)
24 end
25
26 def already_likes(creation)
27 creation.is_liked_by(self)
28 end
29
30 def owns(creation)
31 creation.user == self
32 end
33
34 def change_password(password, confirmation=password)
35 return false unless password == confirmation
36 self.password = password
37 self.save
38 end
39
40 def has_avatar?
41 self.avatar && self.avatar.image.present?
42 end
43
44 def to_param
45 "#{id}-#{name.parameterize}"
46 end
47
48 def send_welcome_email
49 UserMailer.welcome_email(self).deliver_later
50 end
51
52 def recent_activities(limit = 20)
53 activities.includes(subject: [{user: :avatar}, :creation]).order(created_at: :desc).limit(limit)
54 end
55
56 def comment_on(creation, text, disqus_id)
57 creation.comments.create(text: text, user: self, disqus_id: disqus_id)
58 end
59
60 def favorite_cakes
61 favorites.includes(creation: [:photos, :user]).map(&:creation)
62 end
63
64 def create_cake(name:, category:)
65 creations.create(name: name, category_id: category.id)
66 end
67
68 def notify_of_activity
69 NotificationMailer.notification_email(self).deliver_later
70 end
71
72 class << self
73 def login(email, password)
74 user = User.find_by(email: email)
75 return false if user.nil?
76 user.user_sessions.create! if user.authenticate(password)
77 end
78 end
79
80 private
81
82 def ensure_authentication_token
83 self.authentication_token = SecureRandom.hex(32) if self.authentication_token.blank?
84 end
85end