Sha256: 60c14153332b31cdfbf2c06a051a488158b1e273531476aa10eef9997314aa89

Contents?: true

Size: 1.95 KB

Versions: 6

Compression:

Stored size: 1.95 KB

Contents

require_relative './organization_concerns/settings_validation'
require_relative './organization_concerns/task_scheduling'

module PandaPal
  module OrganizationConcerns; end

  class Organization < ActiveRecord::Base
    include OrganizationConcerns::SettingsValidation
    include OrganizationConcerns::TaskScheduling if defined?(Sidekiq.schedule)

    serialize :settings, Hash
    attr_encrypted :settings, marshal: true, key: :encryption_key
    before_save {|a| a.settings = a.settings} # this is a hacky work-around to a bug where attr_encrypted is not saving settings in place

    validates :key, uniqueness: { case_sensitive: false }, presence: true
    validates :secret, presence: true
    validates :name, uniqueness: { case_sensitive: false }, presence: true, format: { with: /\A[a-z0-9_]+\z/i }
    validates :canvas_account_id, presence: true
    validates :salesforce_id, presence: true, uniqueness: true

    after_create :create_schema
    after_commit :destroy_schema, on: :destroy

    if defined?(scheduled_task)
      scheduled_task '0 0 3 * * *', :clean_old_sessions do
        PandaPal::Session.where(panda_pal_organization: self).where('updated_at < ?', 1.week.ago).delete_all
      end
    end

    before_validation on: [:update] do
      errors.add(:name, 'should not be changed after creation') if name_changed?
    end

    def encryption_key
      # production environment might not have loaded secret_key_base yet.
      # In that case, just read it from env.
      if (Rails.application.secrets.secret_key_base)
        Rails.application.secrets.secret_key_base[0,32]
      else
        ENV["SECRET_KEY_BASE"][0,32]
      end
    end

    def switch_tenant(&block)
      if block_given?
        Apartment::Tenant.switch(name, &block)
      else
        Apartment::Tenant.switch!(name)
      end
    end

    private

    def create_schema
      Apartment::Tenant.create name
    end

    def destroy_schema
      Apartment::Tenant.drop name
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
panda_pal-5.4.0.beta7 app/models/panda_pal/organization.rb
panda_pal-5.4.0.beta6 app/models/panda_pal/organization.rb
panda_pal-5.4.0.beta5 app/models/panda_pal/organization.rb
panda_pal-5.4.0.beta4 app/models/panda_pal/organization.rb
panda_pal-5.4.0.beta3 app/models/panda_pal/organization.rb
panda_pal-5.4.0.beta2 app/models/panda_pal/organization.rb