Sha256: a2c0bba3ef5bc6988ea1e10ccb5b470739d2f2a30e84b442283d752ebc44c5fa

Contents?: true

Size: 1.87 KB

Versions: 3

Compression:

Stored size: 1.87 KB

Contents

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

  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.account_memberships.create!(:account => account, :admin => admin)
    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

3 entries across 3 versions & 1 rubygems

Version Path
saucy-0.1.3 app/models/invitation.rb
saucy-0.1.2 app/models/invitation.rb
saucy-0.1.1 app/models/invitation.rb