Skip to content

Commit

Permalink
Add .merge and .find_or_create methods to ActiveNode
Browse files Browse the repository at this point in the history
  • Loading branch information
cheerfulstoic committed Apr 6, 2015
1 parent bbc3727 commit ae9204d
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/neo4j/active_node/persistence.rb
Expand Up @@ -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)
Expand Down
37 changes: 37 additions & 0 deletions spec/e2e/query_spec.rb
Expand Up @@ -52,6 +52,7 @@ def self.ordered_by_subject

stub_active_node_class('Teacher') do
property :name
property :age

has_many :both, :lessons

Expand Down Expand Up @@ -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
Expand Down

0 comments on commit ae9204d

Please sign in to comment.