Skip to content

Commit

Permalink
Add presence validation for object in SnapshotItem model (#56)
Browse files Browse the repository at this point in the history
  • Loading branch information
dmrAnderson authored Aug 29, 2024
1 parent 3fcd0e4 commit 7156f56
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 11 deletions.
13 changes: 6 additions & 7 deletions lib/active_snapshot/models/snapshot_item.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,21 @@ class SnapshotItem < ActiveRecord::Base
validates :snapshot_id, presence: true
validates :item_id, presence: true, uniqueness: { scope: [:snapshot_id, :item_type] }
validates :item_type, presence: true
validates :object, presence: true

def object
return @object if @object

if ActiveSnapshot.config.storage_method_json?
@object = JSON.parse(self[:object])
@object = self[:object] ? JSON.parse(self[:object]) : {}
elsif ActiveSnapshot.config.storage_method_yaml?
yaml_method = "unsafe_load"
yaml_method = YAML.respond_to?(:unsafe_load) ? :unsafe_load : :load

if !YAML.respond_to?("unsafe_load")
yaml_method = "load"
end

@object = YAML.send(yaml_method, self[:object])
@object = self[:object] ? YAML.public_send(yaml_method, self[:object]) : {}
elsif ActiveSnapshot.config.storage_method_native_json?
@object = self[:object]
else
raise StandardError, "Unsupported storage_method: `#{ActiveSnapshot.config.storage_method}`"
end
end

Expand Down
8 changes: 4 additions & 4 deletions test/models/snapshot_item_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def test_relationships
instance.snapshot = instance
end

instance.snapshot = ActiveSnapshot::Snapshot.new
instance.snapshot = @snapshot_klass.new

instance.item = instance

Expand All @@ -31,9 +31,9 @@ def test_relationships
def test_validations
instance = @snapshot_item_klass.new

instance.valid?
assert instance.invalid?

[:item_id, :item_type, :snapshot_id].each do |attr|
[:item_id, :item_type, :snapshot_id, :object].each do |attr|
assert_equal ["can't be blank"], instance.errors[attr] ### presence error
end

Expand All @@ -42,7 +42,7 @@ def test_validations

instance = @snapshot_item_klass.new(item: snapshot.item, snapshot: snapshot)

assert_not instance.valid?
assert instance.invalid?

assert_equal ["has already been taken"], instance.errors[:item_id] ### uniq error
end
Expand Down

0 comments on commit 7156f56

Please sign in to comment.