Class: Neo4j::Core::Index::UniqueFactory
- Inherits:
-
Object
- Object
- Neo4j::Core::Index::UniqueFactory
- Defined in:
- lib/neo4j-core/index/unique_factory.rb
Overview
A Utility class that can be used to make it easier to create unique entities. It uses Indexer#put_if_absent.
Instance Method Summary collapse
-
#get_or_create(key, value, props = nil) { ... } ⇒ Object
Get the indexed entity, creating it (exactly once) if no indexed entity exists.
-
#initialize(key, index) { ... } ⇒ UniqueFactory
constructor
A new instance of UniqueFactory.
Constructor Details
#initialize(key, index) { ... } ⇒ UniqueFactory
Returns a new instance of UniqueFactory.
18 19 20 21 22 |
# File 'lib/neo4j-core/index/unique_factory.rb', line 18 def initialize(key, index, &entity_creator_block) @key = key @index = index @entity_creator_block = entity_creator_block || Proc.new{|k,v| Neo4j::Node.new(key.to_s => v)} end |
Instance Method Details
#get_or_create(key, value, props = nil) { ... } ⇒ Object
Get the indexed entity, creating it (exactly once) if no indexed entity exists. There must be an index on the key. Must not be called inside a transaction.
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/neo4j-core/index/unique_factory.rb', line 32 def get_or_create(key, value, props=nil, &init_block) raise "Transaction already running, can't use get_or_create" if Neo4j.db.graph.respond_to?(:transactionRunning) && Neo4j.db.graph.transactionRunning tx = Neo4j::Transaction.new result = @index.get(key.to_s, value).get_single return result if result created = @entity_creator_block.call(key,value) result = @index.put_if_absent(created._java_entity, key.to_s, value) if result.nil? props.each_pair{|k,v| created[k.to_s] = v} if props init_block.call(result) if init_block result = created else created.del end tx.success result ensure tx && tx.finish end |