Sha256: 6da90d1b555e5f10fd4120a799ea7bfea5cb366330b4221ddbe647d6ed11eb89

Contents?: true

Size: 1.98 KB

Versions: 4

Compression:

Stored size: 1.98 KB

Contents

class Invitation < ActiveRecord::Base
  belongs_to :account
  validates_presence_of :account_id
  validates_presence_of :email
  has_and_belongs_to_many :projects

  after_create :deliver_invitation

  attr_accessor :new_user_name, :new_user_password,
    :new_user_password_confirmation, :existing_user_password
  attr_writer :new_user_email, :existing_user_email
  attr_reader :user
  attr_protected :account_id

  validate :validate_accepting_user, :on => :update

  def account_name
    account.name
  end

  def accept(attributes)
    self.attributes = attributes
    @user = existing_user || new_user
    if valid?
      @user.save!
      @user.memberships.create!(:account  => account,
                                :admin    => admin,
                                :projects => projects)
    end
  end

  def new_user_email
    @new_user_email ||= email
  end

  def existing_user_email
    @existing_user_email ||= email
  end

  private

  def deliver_invitation
    InvitationMailer.invitation(self).deliver
  end

  def existing_user
    if existing_user?
      User.find_by_email(existing_user_email)
    end
  end

  def existing_user?
    existing_user_password.present?
  end

  def new_user
    User.new(
      :email                 => new_user_email,
      :password              => new_user_password,
      :password_confirmation => new_user_password_confirmation,
      :name                  => new_user_name
    ).tap do |user|
      user.email_confirmed = true
    end
  end

  def validate_accepting_user
    if existing_user?
      validate_existing_user
    else
      validate_new_user
    end
  end

  def validate_new_user
    user.valid?
    user.errors.each do |field, message|
      errors.add("new_user_#{field}", message)
    end
  end

  def validate_existing_user
    if existing_user.nil?
      errors.add(:existing_user_email, "isn't signed up")
    elsif !existing_user.authenticated?(existing_user_password)
      errors.add(:existing_user_password, "is incorrect")
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
saucy-0.1.9 app/models/invitation.rb
saucy-0.1.8 app/models/invitation.rb
saucy-0.1.7 app/models/invitation.rb
saucy-0.1.6 app/models/invitation.rb