Skip to content

Commit

Permalink
options for handling non-persisted node upon assignment of an associa…
Browse files Browse the repository at this point in the history
…tion
  • Loading branch information
dpisarewski committed Feb 6, 2015
1 parent 642cb28 commit 41b2580
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
13 changes: 12 additions & 1 deletion lib/neo4j/active_node/has_n.rb
Expand Up @@ -62,6 +62,17 @@ def cypher_hash(cypher_string)
cypher_string.hash.abs
end

def handle_non_persisted_node
return if self._persisted_obj
if Neo4j::Config[:autosave_on_assignment]
save
elsif Neo4j::Config[:hook_for_non_persisted_node]
Neo4j::Config[:hook_for_non_persisted_node].call(self)
else
fail(Neo4j::ActiveNode::HasN::NonPersistedNodeError, 'Unable to create relationship with non-persisted nodes')
end
end

module ClassMethods
# :nocov:
# rubocop:disable Style/PredicateName
Expand Down Expand Up @@ -151,7 +162,7 @@ def has_one(direction, name, options = {})

module_eval(%{
def #{name}=(other_node)
raise(Neo4j::ActiveNode::HasN::NonPersistedNodeError, 'Unable to create relationship with non-persisted nodes') unless self._persisted_obj
handle_non_persisted_node
clear_association_cache
#{name}_query_proxy(rel: :r).query_as(:n).delete(:r).exec
#{name}_query_proxy << other_node
Expand Down
26 changes: 24 additions & 2 deletions spec/e2e/has_one_spec.rb
Expand Up @@ -20,8 +20,30 @@ class HasOneB
expect(unsaved_node.parent).to eq nil
end

it 'raises an error when trying to create a relationship' do
expect { unsaved_node.parent = HasOneA.create }.to raise_error(Neo4j::ActiveNode::HasN::NonPersistedNodeError)
context 'with disabled auto-saving and without hook' do
it 'raises an error when trying to create a relationship' do
expect { unsaved_node.parent = HasOneA.create }.to raise_error(Neo4j::ActiveNode::HasN::NonPersistedNodeError)
end
end

context 'with enabled auto-saving' do
before { Neo4j::Config[:autosave_on_assignment] = true }
after { Neo4j::Config[:autosave_on_assignment] = false }

it 'saves the node' do
expect { unsaved_node.parent = HasOneA.create }.to change(unsaved_node, :persisted?).from(false).to(true)
end
end

context 'with a hook' do
let(:error) { Exception.new('Custom error') }
let(:hook) { ->(_) { fail error } }
before { Neo4j::Config[:hook_for_non_persisted_node] = hook }
after { Neo4j::Config[:hook_for_non_persisted_node] = nil }

it 'calls hook' do
expect { unsaved_node.parent = HasOneA.create }.to raise_error(error)
end
end
end

Expand Down

0 comments on commit 41b2580

Please sign in to comment.