从控制器内运行构造函数
所以我尝试从控制器内运行生成器 我的想法是,我可以从 Rails 应用程序中生成一个脚手架
以用于测试目的,我创建了一个小型生成器,它创建了一个没有实际内容的初始化程序。我已经从 shell 中运行了这个(rails 生成初始值设定项),
lib/generators/initializer_generator.rb
class InitializerGenerator < Rails::Generators::Base
def create_initializer_file
create_file "config/initializers/initializer.rb", "# Add initialization content here"
end
end
但是当我尝试从控制器运行生成器时出现问题
class GeneratorController < ApplicationController
include Rails::Generators
include Rails::Generators::Actions
def index
generate(:initializer)
end
end
,因此这会带来响应“未定义的方法‘行为’” 然后我做了一些研究,知道轨道发电机是基于雷神 发现行为方法是Thor::Actions模块中的thor方法 http://rubydoc.info/github/wycats/thor/master/Thor /动作:行为
所以我更改了控制器代码以包含该模块:
class GeneratorController < ApplicationController
include Rails::Generators
include Rails::Generators::Actions
include Thor::Actions
def index
generate(:initializer)
end
end
现在错误是“参数数量错误(3 代表 0)”。我现在很困惑可能出了什么问题。
So I'm attempting to run a generator from within a controller
the idea being that i could generate a scaffold from within a rails application
for testing purposes ive created a small generator that creates an initializer with no real content. i've run this from within the shell (rails generate initializer)
lib/generators/initializer_generator.rb
class InitializerGenerator < Rails::Generators::Base
def create_initializer_file
create_file "config/initializers/initializer.rb", "# Add initialization content here"
end
end
but the problem comes in when i attempt to run the generator from a controller
class GeneratorController < ApplicationController
include Rails::Generators
include Rails::Generators::Actions
def index
generate(:initializer)
end
end
so this bring the response 'undefined method `behavior'
then i did some research knowing that rails generators are based apon Thor
and found that the behavior method is a thor method in the Thor::Actions modules
http://rubydoc.info/github/wycats/thor/master/Thor/Actions:behavior
So I changed the controller code to include that module:
class GeneratorController < ApplicationController
include Rails::Generators
include Rails::Generators::Actions
include Thor::Actions
def index
generate(:initializer)
end
end
Now the error is 'wrong number of arguments (3 for 0)'. Am very confused now about what might be going wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否尝试过直接给班级打电话?
这是 Thor 相对于 Rake 的优势,这些都是常规的 Ruby 类。
我必须在我的方法中设置destination_root,例如:
我刚刚开始使用生成器,所以可能有更好的方法。
此后我遇到了一个尚未解决的问题,那就是如果文件已经存在,Thor 会提示用户输入。
Have you tried calling the class directly?
This is an advantage of Thor over Rake, these are regular Ruby classes.
I had to set the destination_root inside my method, example:
I've only just started using generators so there might be a better way.
One issue I ran in to after this, which I have yet to solve is that Thor prompts for user input if the file already exists.