Sha256: 282d37df7c50e19e9b0c04d19d25e7b5cc6761ef2bf9e78da8a6723c43630eb4

Contents?: true

Size: 1.48 KB

Versions: 24

Compression:

Stored size: 1.48 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)
        form = assign_attributes(form, params)

        raise NameAlreadyExists if name_already_exists?(form)

        ApplicationRecord.transaction do
          form.save!
        end

        form.tags.reload

        form
      rescue ActiveRecord::RecordNotUnique
        retry
      end

      def assign_attributes(form, params)
        form.assign_attributes(params.slice(:name, :description, :api_path, :http_method, :preferences))

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

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

Version data entries

24 entries across 24 versions & 1 rubygems

Version Path
motor-admin-0.1.37 lib/motor/forms/persistance.rb
motor-admin-0.1.36 lib/motor/forms/persistance.rb
motor-admin-0.1.35 lib/motor/forms/persistance.rb
motor-admin-0.1.34 lib/motor/forms/persistance.rb
motor-admin-0.1.33 lib/motor/forms/persistance.rb
motor-admin-0.1.32 lib/motor/forms/persistance.rb
motor-admin-0.1.31 lib/motor/forms/persistance.rb
motor-admin-0.1.29 lib/motor/forms/persistance.rb
motor-admin-0.1.28 lib/motor/forms/persistance.rb
motor-admin-0.1.27 lib/motor/forms/persistance.rb
motor-admin-0.1.25 lib/motor/forms/persistance.rb
motor-admin-0.1.23 lib/motor/forms/persistance.rb
motor-admin-0.1.22 lib/motor/forms/persistance.rb
motor-admin-0.1.21 lib/motor/forms/persistance.rb
motor-admin-0.1.20 lib/motor/forms/persistance.rb
motor-admin-0.1.18 lib/motor/forms/persistance.rb
motor-admin-0.1.17 lib/motor/forms/persistance.rb
motor-admin-0.1.15 lib/motor/forms/persistance.rb
motor-admin-0.1.16 lib/motor/forms/persistance.rb
motor-admin-0.1.14 lib/motor/forms/persistance.rb