From 35a047e3cbf914704256c9a4efeeb74a72b09be4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Niklas=20H=C3=A4usele?= Date: Tue, 22 Aug 2023 17:20:11 +0200 Subject: [PATCH] Quick upsert prototype (#23) * Add Minitest raketasks * Add a super simple prototype for upsert vs. update * Update lib/oaken.rb * Update Rakefile * Update lib/oaken.rb * Run validations before using upsert --------- Co-authored-by: Kasper Timm Hansen --- lib/oaken.rb | 8 ++++++++ test/oaken_test.rb | 9 +++++++++ test/seeds.rb | 2 ++ test/test_helper.rb | 1 + 4 files changed, 20 insertions(+) diff --git a/lib/oaken.rb b/lib/oaken.rb index af57c7e..5816218 100644 --- a/lib/oaken.rb +++ b/lib/oaken.rb @@ -48,6 +48,8 @@ def update(id, **attributes) end end end + + alias :upsert :update end class Stored::Memory < Stored::Abstract @@ -79,6 +81,12 @@ def update(id, **attributes) @type.create!(id: id.hash, **attributes) end end + + def upsert(id, **attributes) + attributes = super + @type.new(attributes).validate! + @type.upsert({ id: id.hash, **attributes }) + end end module Data diff --git a/test/oaken_test.rb b/test/oaken_test.rb index ff15f8e..dad699b 100644 --- a/test/oaken_test.rb +++ b/test/oaken_test.rb @@ -47,4 +47,13 @@ def test_updating_fixture users.update :kasper, name: "Kasper2" assert_equal "Kasper2", users.kasper.name end + + def test_upserting_vs_updating + assert_equal "Nice!", comments.praise.title + + error = assert_raises RuntimeError do + comments.update :salty, title: "foo" + end + assert_equal "after_create", error.message + end end diff --git a/test/seeds.rb b/test/seeds.rb index 5fb6a06..21e94b0 100644 --- a/test/seeds.rb +++ b/test/seeds.rb @@ -4,3 +4,5 @@ users.with name: -> { id.to_s.capitalize }, accounts: [accounts.business] users.update :kasper users.update :coworker + +comments.upsert :praise, title: "Nice!" diff --git a/test/test_helper.rb b/test/test_helper.rb index 1379756..994e05a 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -48,6 +48,7 @@ class User < ActiveRecord::Base end class Comment < ActiveRecord::Base + after_create { raise "after_create" } end Oaken::Data.records.preregister ActiveRecord::Base.connection.tables.grep_v(/^ar_/)