Last active
January 4, 2016 04:09
-
-
Save ekhall/8566682 to your computer and use it in GitHub Desktop.
Complex code smell?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe 'Created Node Class' do | |
before(:all) do | |
@name = 'Patient' | |
@token = {model_name: @name, properties: [:first, :second]} | |
@klass = NodeFactory.get_node_class(@token) | |
end | |
it 'queries the graph and instantiates itself the correct number of times' do | |
@@obj = 0 | |
@klass.class_eval do | |
old_initialize = instance_method :initialize | |
define_method :initialize do |*args, &block| | |
result = old_initialize.bind(self).call(*args, &block) | |
@@obj += 1 | |
result | |
end | |
end | |
these_objects = Random.new.rand(10...20) | |
these_objects.times.map.with_index do |_,index| | |
Neo4j::Node.create({name: "name_#{index}"}, @name.to_sym) | |
end | |
Neo4j::Node.create({name: 'other'}, ':Not_Patient') | |
@klass.instantiate_from_graph | |
expect(@@obj).to eq(these_objects) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Mgdb | |
class CleanRoom | |
instance_methods.each do |m| | |
undef_method m unless m.to_s =~ /methods|object_id|method_missing|respond_to?|^__/ | |
end | |
end | |
class NodeFactory | |
def self._node_class(klass) | |
@node_class ||= Kernel.const_set(klass, Class.new(Neo4j::Node)) | |
end | |
private_class_method :_node_class | |
def self.get_node_class(args) | |
klass_name = args.fetch(:model_name) | |
properties = args.fetch(:properties) | |
klass = _node_class klass_name | |
klass.class_eval do | |
extend Mgdb::Cypher | |
extend Mgdb::ObjectSpaceHelpers | |
properties.each do |prop| | |
define_method prop.intern do | |
instance_variable_get("@#{prop}") | |
end | |
define_method "#{prop}=".intern do |value| | |
instance_variable_set("@#{prop}", value) | |
end | |
end | |
end | |
@node_class | |
end | |
end | |
module Cypher | |
def instantiate_from_graph | |
klass_name = self.name.rpartition(':').last # Removes Kernel:: | |
nodes = Neo4j::Label.find_all_nodes(klass_name) | |
nodes.each.map {self.new} | |
end | |
end | |
module ObjectSpaceHelpers | |
def obj_count | |
ObjectSpace.each_object(self).count | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment