Created
September 2, 2021 16:43
-
-
Save tjhanley/80eb23f6f7ce4ee643b41d34a89730c8 to your computer and use it in GitHub Desktop.
url slug
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Referrer < ActiveRecord::Base | |
URL_SLUG_REGEX = /^[a-z0-9-]+$/i | |
attr_accessible :token, :campaign, :campaign_id, :user_id, :lead_id | |
belongs_to :campaign | |
belongs_to :user | |
belongs_to :lead | |
has_many :referral_click_throughs | |
has_many :referrals | |
has_many :referred_leads, through: :referrals, source: :referee_lead | |
has_many :referred_users, through: :referrals, source: :referee_user | |
has_many :converted_referrals, -> { converted }, class_name: "Referral" | |
validates_presence_of :token, :campaign_id | |
validate :user_or_lead_is_present | |
validate :token_sluggable | |
validates_uniqueness_of :token | |
before_validation on: :create do |record| | |
record.ensure_unique | |
end | |
# Ensures that the token will be unique when created | |
# | |
# | |
def ensure_unique(&block) | |
if self['token'].blank? | |
begin | |
self['token'] = (block ? block.call : self.class.generate_unique) | |
end while self.class.exists?('token' => self['token']) | |
end | |
self['token'] | |
end | |
def self.generate_unique | |
SecureRandom.hex(5) | |
end | |
def parent | |
user || lead | |
end | |
def token_sluggable | |
unless token.try(:match , URL_SLUG_REGEX ) | |
errors.add :token, "must contain only numbers, letters, hyphens" | |
end | |
end | |
private | |
def user_or_lead_is_present | |
if user_id.blank? && lead_id.blank? | |
errors[:base] << "user or lead must be present" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment