foodsoft/app/models/invite.rb

34 lines
1,000 B
Ruby
Raw Permalink Normal View History

2009-01-06 11:49:19 +01:00
require 'digest/sha1'
# Invites are created by foodcoop users to invite a new user into the foodcoop and their order group.
class Invite < ApplicationRecord
2009-01-06 11:49:19 +01:00
belongs_to :user
belongs_to :group
validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i }
validates :user, presence: true
validates :group, presence: true
validates :token, presence: true
validates :expires_at, presence: true
validate :email_not_already_registered, on: :create
2011-05-11 11:17:02 +02:00
before_validation :set_token_and_expires_at
protected
2009-01-06 11:49:19 +01:00
# Before validation, set token and expires_at.
def set_token_and_expires_at
2009-01-06 11:49:19 +01:00
self.token = Digest::SHA1.hexdigest(Time.now.to_s + rand(100).to_s)
self.expires_at = Time.now.advance(days: 7)
2009-01-06 11:49:19 +01:00
end
private
2009-01-06 11:49:19 +01:00
# Custom validation: check that email does not already belong to a registered user.
2011-05-11 11:17:02 +02:00
def email_not_already_registered
return if User.find_by_email(email).nil?
errors.add(:email, I18n.t('invites.errors.already_member'))
2009-01-06 11:49:19 +01:00
end
end