Sha256: cecac05aabffda6bf48fb2f574706d247eda595ff63ab97c61a052250450d47e

Contents?: true

Size: 1.36 KB

Versions: 4

Compression:

Stored size: 1.36 KB

Contents

module Pageflow
  # @api private
  class InvitationForm
    include ActiveModel::Model

    attr_reader :membership, :target_user, :available_accounts

    def initialize(attributes, available_accounts)
      @attributes = attributes
      @available_accounts = available_accounts

      @invited_user = InvitedUser.new(attributes[:user])
      @target_user = existing_user || @invited_user

      @membership = @target_user.memberships.build(entity: initial_account,
                                                   role: initial_role)
    end

    def user
      @invited_user.becomes(User)
    end

    def save
      return false unless valid?
      Pageflow.config.quotas.get(:users, initial_account).verify_available!

      membership.save!
    end

    def valid?
      (existing_user || @invited_user.valid?) && membership.valid?
    end

    def existing_member
      @existing_member ||=
        initial_account && initial_account.users.find_by_email(user.email)
    end

    private

    def existing_user
      @existing_user ||=
        User.find_by_email(user.email)
    end

    def initial_account
      @initial_account ||= available_accounts.find_by_id(initial_account_id)
    end

    def initial_account_id
      @attributes.fetch(:membership, {})[:entity_id]
    end

    def initial_role
      @attributes.fetch(:membership, {})[:role] || 'member'
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
pageflow-12.0.4 app/models/pageflow/invitation_form.rb
pageflow-12.0.3 app/models/pageflow/invitation_form.rb
pageflow-12.0.2 app/models/pageflow/invitation_form.rb
pageflow-12.0.1 app/models/pageflow/invitation_form.rb