# frozen_string_literal: true class Form < ApplicationRecord belongs_to :user has_many :submissions, dependent: :destroy before_validation :insert_defaults, on: :create after_create :create_spreadsheet has_secure_token encrypts :airtable_api_key encrypts :airtable_app_key validates :title, presence: true validates :backend_name, inclusion: { in: %w[google_sheets airtable] } # Airtable validations validates :airtable_api_key, presence: { if: :airtable? } validates :airtable_app_key, presence: { if: :airtable? } validates :airtable_table, presence: { if: :airtable? } # TODO: use counter_cache option on association def submissions_count @submissions_count ||= submissions.count end def last_submission_date @last_submission_date ||= submissions.order(created_at: :desc).first&.created_at end def deactivate!(reason = nil) user.deactivate!(reason) end delegate :active?, to: :user def airtable? backend_name == 'airtable' end def google backend_name == 'google' end def backend @backend ||= SpreadsheetBackends.const_get(backend_name.camelize).new(self) end def spreadsheet_url backend.url end def create_spreadsheet backend.create end def append_to_spreadsheet(data) backend.append(data) end def spreadsheet_headers backend.headers end def to_param token end def insert_defaults self.backend_name ||= airtable_app_key.present? ? 'airtable' : 'google_sheets' self.title ||= airtable_table end end