Skip to content

Commit

Permalink
Quick upsert prototype (#23)
Browse files Browse the repository at this point in the history
* 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 <kaspth@gmail.com>
  • Loading branch information
codergeek121 and kaspth authored Aug 22, 2023
1 parent 9af0dee commit 35a047e
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/oaken.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ def update(id, **attributes)
end
end
end

alias :upsert :update
end

class Stored::Memory < Stored::Abstract
Expand Down Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions test/oaken_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 2 additions & 0 deletions test/seeds.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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!"
1 change: 1 addition & 0 deletions test/test_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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_/)
Expand Down

0 comments on commit 35a047e

Please sign in to comment.