lib/neo4j/active_node/id_property.rb in neo4j-3.0.0.rc.3 vs lib/neo4j/active_node/id_property.rb in neo4j-3.0.0.rc.4

- old
+ new

@@ -49,22 +49,28 @@ raise "Illegal value #{conf.inspect} for id_property, expected :on or :auto" end end def define_property_method(clazz, name) + clear_methods(clazz, name) + clazz.module_eval(%Q{ def id persisted? ? #{name} : nil end - property :#{name} validates_uniqueness_of :#{name} + + property :#{name} }, __FILE__, __LINE__) + end def define_uuid_method(clazz, name) + clear_methods(clazz, name) + clazz.module_eval(%Q{ default_property :#{name} do ::SecureRandom.uuid end @@ -75,10 +81,12 @@ alias_method :id, :#{name} }, __FILE__, __LINE__) end def define_custom_method(clazz, name, on) + clear_methods(clazz, name) + clazz.module_eval(%Q{ default_property :#{name} do |instance| raise "Specifying custom id_property #{name} on none existing method #{on}" unless instance.respond_to?(:#{on}) instance.#{on} end @@ -89,33 +97,70 @@ alias_method :id, :#{name} }, __FILE__, __LINE__) end + def clear_methods(clazz, name) + if clazz.method_defined?(name) + clazz.module_eval(%Q{ + undef_method :#{name} + }, __FILE__, __LINE__) + end + + if clazz.attribute_names.include?(name.to_s) + clazz.module_eval(%Q{ + undef_property :#{name} + }, __FILE__, __LINE__) + end + end + extend self end module ClassMethods - def find_by_id(key) - Neo4j::Node.load(key.to_i) + def find_by_id(id) + self.where(id_property_name => id).first end + def find_by_ids(ids) + self.where(id_property_name => ids).to_a + end + def id_property(name, conf = {}) + begin + if has_id_property? + unless mapped_label.uniqueness_constraints[:property_keys].include?([name]) + drop_constraint(id_property_name, type: :unique) + end + end + rescue Neo4j::Server::CypherResponse::ResponseError + end + @id_property_info = {name: name, type: conf} TypeMethods.define_id_methods(self, name, conf) constraint name, type: :unique self.define_singleton_method(:find_by_id) do |key| self.where(name => key).first end end + def has_id_property? + id_property_info && !id_property_info.empty? + end + def id_property_info - @id_property_info ||= false + @id_property_info ||= {} end + def id_property_name + id_property_info[:name] + end + + alias_method :primary_key, :id_property_name + end end -end \ No newline at end of file +end