Skip to content

Commit

Permalink
Add Model#exists? method to detect deleted records
Browse files Browse the repository at this point in the history
Disambiguate between records that have been created-but-not-persisted,
created-and-persisted, persisted-and-deleted.
  • Loading branch information
mwpastore committed Oct 24, 2017
1 parent 3aaae93 commit 93d8d8e
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
33 changes: 32 additions & 1 deletion lib/ohm.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1188,7 +1188,8 @@ def set(att, val)
@attributes[att] = val
end

# Returns +true+ if the model is not persisted. Otherwise, returns +false+.
# Returns +true+ if the model has never been persisted. Otherwise, returns
# +false+.
#
# Example:
#
Expand All @@ -1208,6 +1209,36 @@ def new?
!defined?(@id)
end

# Returns +true+ if the model is persisted. Otherwise, returns +false+.
#
# Example:
#
# class User < Ohm::Model
# attribute :name
# end
#
# u = User.new(:name => "John")
# u.new?
# # => true
# u.exists?
# # => false
#
# u.save
# u.new?
# # => false
# u.exists?
# # => true
#
# u.delete
# u.new?
# # => false
# u.exists?
# # => false
#
def exists?
!new? && self.class.exists?(id)
end

# Increments a counter atomically. Internally uses `HINCRBY`.
#
# class Ad
Expand Down
17 changes: 17 additions & 0 deletions test/model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,23 @@ class RedefinedModel < Ohm::Model
assert_equal "2", event2.id
end

test "event shows the correct states" do
event = Event.new

assert event.new?
assert !event.exists?

event.save

assert !event.new?
assert event.exists?

event.delete

assert !event.new?
assert !event.exists?
end

# Saving a model
test "create the model if it is new" do
event = Event.new(:name => "Foo").save
Expand Down

0 comments on commit 93d8d8e

Please sign in to comment.