Creating rails model with Object.const_set

2019-06-26 03:30发布

I am playing around in the rails console with Neo4j and tried to create a model class like this:

Object.const_set("TestNode", Class.new(super_class=Neo4j::Rails::Model))
node = TestNode.new

if i then try to save the instance with node.save I get a bunch of errors:

node.save
NoMethodError: undefined method `each' for nil:NilClass
from /Users/oskbor/.rvm/gems/jruby-1.6.7.2/gems/neo4j-2.0.0-java/lib/neo4j/rails/attributes.rb:57:in `init_on_create'
from /Users/oskbor/.rvm/gems/jruby-1.6.7.2/gems/neo4j-2.0.0-java/lib/neo4j/rails/node_persistance.rb:16:in `create'
from /Users/oskbor/.rvm/gems/jruby-1.6.7.2/gems/neo4j-2.0.0-java/lib/neo4j/rails/callbacks.rb:39:in `create_with_callbacks'
from /Users/oskbor/.rvm/gems/jruby-1.6.7.2/gems/activesupport-3.2.8/lib/active_support/callbacks.rb:417:in `_run__1980184148__create__1722973119__callbacks'
from org/jruby/RubyKernel.java:2076:in `send'
...

Everything works if I create the TestNode class like normal:

class TestNode < Neo4j::Rails::Model
end

What is wrong with the first way to create the model class TestNode?

The goal I have in mind is to be able to create new models on the fly using metaprogramming and then be able to persist instances to the neo4j database.

1条回答
Rolldiameter
2楼-- · 2019-06-26 03:44

As Andreas Ronge commented, some callbacks are not fired when using Object.const_set. Evaluating a string works, so this was my solution:

name ="Classname"
super_klass ="Neo4j::Rails::Model"
string_to_eval = "class #{name} < #{super_klass}; end;"
eval(string_to_eval, TOPLEVEL_BINDING)
查看更多
登录 后发表回答