Creating rails model with Object.const_set

烈酒焚心 提交于 2019-12-13 13:15:29

问题


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:


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)


来源:https://stackoverflow.com/questions/12237978/creating-rails-model-with-object-const-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!