Sha256: 149ca4652cc4e0ef0e8a45eee1bb624d03922c78d300e76fbc38fb8aff6b3a54

Contents?: true

Size: 1.99 KB

Versions: 9

Compression:

Stored size: 1.99 KB

Contents

# frozen_string_literal: true

module Motor
  module Forms
    module Persistance
      NameAlreadyExists = Class.new(StandardError)

      module_function

      def build_from_params(params, current_user = nil)
        form = assign_attributes(Form.new, params)

        form.author = current_user

        form
      end

      def create_from_params!(params, current_user = nil)
        raise NameAlreadyExists if Form.exists?(['lower(name) = ?', params[:name].to_s.downcase])

        form = build_from_params(params, current_user)

        ApplicationRecord.transaction do
          form.save!
        end

        form
      rescue ActiveRecord::RecordNotUnique
        retry
      end

      def update_from_params!(form, params, force_replace: false)
        tag_ids = form.tags.ids

        form = assign_attributes(form, params)

        raise NameAlreadyExists if !force_replace && name_already_exists?(form)

        ApplicationRecord.transaction do
          archive_with_existing_name(form) if force_replace

          form.save!
        end

        form.touch if tag_ids.sort != form.tags.reload.ids.sort && params[:updated_at].blank?

        form
      rescue ActiveRecord::RecordNotUnique
        retry
      end

      def assign_attributes(form, params)
        form.assign_attributes(params.slice(:name, :description, :api_path, :http_method, :preferences))
        form.updated_at = [params[:updated_at], Time.current].min if params[:updated_at].present?

        Motor::Tags.assign_tags(form, params[:tags])
      end

      def archive_with_existing_name(form)
        Motor::Form.where(['lower(name) = ? AND id != ?', form.name.to_s.downcase, form.id])
                   .update_all(deleted_at: Time.current)
      end

      def name_already_exists?(form)
        if form.new_record?
          Motor::Form.exists?(['lower(name) = ?', form.name.to_s.downcase])
        else
          Motor::Form.exists?(['lower(name) = ? AND id != ?', form.name.to_s.downcase, form.id])
        end
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
motor-admin-0.1.49 lib/motor/forms/persistance.rb
motor-admin-0.1.48 lib/motor/forms/persistance.rb
motor-admin-0.1.47 lib/motor/forms/persistance.rb
motor-admin-0.1.46 lib/motor/forms/persistance.rb
motor-admin-0.1.44 lib/motor/forms/persistance.rb
motor-admin-0.1.43 lib/motor/forms/persistance.rb
motor-admin-0.1.42 lib/motor/forms/persistance.rb
motor-admin-0.1.41 lib/motor/forms/persistance.rb
motor-admin-0.1.40 lib/motor/forms/persistance.rb