From ae9204d87ec6ce253376aa21cfe59e5e162225ae Mon Sep 17 00:00:00 2001 From: Brian Underwood Date: Mon, 6 Apr 2015 14:50:17 +0200 Subject: [PATCH] Add .merge and .find_or_create methods to ActiveNode --- lib/neo4j/active_node/persistence.rb | 8 ++++++ spec/e2e/query_spec.rb | 37 ++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/lib/neo4j/active_node/persistence.rb b/lib/neo4j/active_node/persistence.rb index e66288d37..cef482d53 100644 --- a/lib/neo4j/active_node/persistence.rb +++ b/lib/neo4j/active_node/persistence.rb @@ -96,6 +96,14 @@ def create!(*args) end end + def merge(attributes) + neo4j_session.query.merge(n: {self => attributes}).exec + end + + def find_or_create(find_attributes, set_attributes = {}) + neo4j_session.query.merge(n: {self => find_attributes}).set(n: set_attributes).exec + end + # Finds the first node with the given attributes, or calls create if none found def find_or_create_by(attributes, &block) find_by(attributes) || create(attributes, &block) diff --git a/spec/e2e/query_spec.rb b/spec/e2e/query_spec.rb index b74c099a1..651da7496 100644 --- a/spec/e2e/query_spec.rb +++ b/spec/e2e/query_spec.rb @@ -52,6 +52,7 @@ def self.ordered_by_subject stub_active_node_class('Teacher') do property :name + property :age has_many :both, :lessons @@ -172,6 +173,42 @@ def self.ordered_by_subject end end + describe 'merge methods' do + before(:each) do + Teacher.delete_all + end + + describe '.merge' do + it 'allows for merging' do + Teacher.merge(name: 'Dr. Harold Samuels') + expect(Teacher.count).to eq(1) + Teacher.merge(name: 'Dr. Harold Samuels') + expect(Teacher.count).to eq(1) + end + end + + describe '.find_or_create' do + it 'works like .merge with just matching attributes' do + Teacher.find_or_create(name: 'Dr. Harold Samuels') + expect(Teacher.count).to eq(1) + expect(Teacher.first.name).to eq('Dr. Harold Samuels') + Teacher.find_or_create(name: 'Dr. Harold Samuels') + expect(Teacher.count).to eq(1) + end + + it 'also sets properties' do + Teacher.find_or_create(name: 'Dr. Harold Samuels') + expect(Teacher.count).to eq(1) + expect(Teacher.first.name).to eq('Dr. Harold Samuels') + expect(Teacher.first.age).to eq(nil) + Teacher.find_or_create({name: 'Dr. Harold Samuels'}, age: 34) + expect(Teacher.count).to eq(1) + expect(Teacher.first.name).to eq('Dr. Harold Samuels') + expect(Teacher.first.age).to eq(34) + end + end + end + context 'samuels teaching soc 101 and 102 lessons' do before(:each) do samuels.lessons_teaching << ss101