Sha256: e489f710d35448492f58317a7ab97bf9fd1fad830747beaf14d4e8bddcf86ca2

Contents?: true

Size: 809 Bytes

Versions: 20

Compression:

Stored size: 809 Bytes

Contents

module NxtSupport
  module SafelyFindOrCreateable
    extend ActiveSupport::Concern

    module ClassMethods
      def safely_find_or_create_by(attributes, &block)
        transaction(requires_new: true) { create(attributes, &block) }
      rescue ActiveRecord::RecordNotUnique
        find_by(attributes)
      end

      def safely_find_or_create_by!(attributes, &block)
        transaction(requires_new: true) { create!(attributes, &block) }
      rescue ActiveRecord::RecordNotUnique
        find_by!(attributes)
      rescue ActiveRecord::RecordInvalid => e
        all_errors_are_uniqueness_failures = e.record.errors.details.all? { |_key, errs| errs.all? { |err| err[:error] == :taken } }
        raise unless all_errors_are_uniqueness_failures
        find_by!(attributes)
      end
    end
  end
end

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
nxt_support-0.6.0 lib/nxt_support/models/safely_find_or_createable.rb
nxt_support-0.5.0 lib/nxt_support/models/safely_find_or_createable.rb
nxt_support-0.4.3 lib/nxt_support/models/safely_find_or_createable.rb
nxt_support-0.4.2 lib/nxt_support/models/safely_find_or_createable.rb
nxt_support-0.4.1 lib/nxt_support/models/safely_find_or_createable.rb
nxt_support-0.4.0 lib/nxt_support/models/safely_find_or_createable.rb
nxt_support-0.3.0 lib/nxt_support/models/safely_find_or_createable.rb
nxt_support-0.2.1 lib/nxt_support/models/safely_find_or_createable.rb
nxt_support-0.2.0 lib/nxt_support/models/safely_find_or_createable.rb
nxt_support-0.1.16 lib/nxt_support/models/safely_find_or_createable.rb
nxt_support-0.1.15 lib/nxt_support/models/safely_find_or_createable.rb
nxt_support-0.1.9 lib/nxt_support/models/safely_find_or_createable.rb
nxt_support-0.1.8 lib/nxt_support/models/safely_find_or_createable.rb
nxt_support-0.1.7 lib/nxt_support/models/safely_find_or_createable.rb
nxt_support-0.1.6 lib/nxt_support/models/safely_find_or_createable.rb
nxt_support-0.1.5 lib/nxt_support/models/safely_find_or_createable.rb
nxt_support-0.1.4 lib/nxt_support/models/safely_find_or_createable.rb
nxt_support-0.1.3 lib/nxt_support/models/safely_find_or_createable.rb
nxt_support-0.1.2 lib/nxt_support/models/safely_find_or_createable.rb
nxt_support-0.1.1 lib/nxt_support/models/safely_find_or_createable.rb