背景:
- 目前正在写一个gem
它的特点之一是在
rails generate my_gem_name:install
运行时,它(应该)覆盖默认的 javascript 脚手架生成的文件(由 生成rails generate scaffold some_model_name
):app/assets/javascripts/some_model_name.coffee
从:
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/
到:
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ SomeJavascriptCode.doSomething({model: 'SomeModelName'})
问题:
- 如何编写上述 Rails 生成器(从上面),它将覆盖由
rails generate scaffold some_model_name
. - 请注意,所需的 javascript 文件(如上所示)具有动态内容;那
{model: 'SomeModelName'}
应该与正在生成的模型名称正确更改和匹配。
尝试:
我意识到有两个步骤可以解决这个问题:
只是能够覆盖脚手架生成的 javascript 文件
然后,做一些事情,使所述生成的 javascript 文件的内容具有“动态”内容。
第一步:
尝试编写一个生成器,将我的模板文件复制到 Rails 的
AssetsGenerator
模板中,最终(希望)覆盖它。# lib/generators/my_gem_name/install_generator.rb module MyGemName class InstallGenerator < Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) class_option :javascript_engine, desc: 'JS engine to be used: [js, coffee].' def copy_js_scaffold_template copy_file "javascript.#{javascript_engine}", "lib/templates/coffee-rails/assets/javascript.#{javascript_engine}" end private def javascript_engine options[:javascript_engine] end end end # lib/generators/my_gem_name/templates/javascript.coffee console.log('JUST TESTING!!!!!!!')
我暂时使用路径lib/templates/coffee-rails/assets/javascript.coffee来测试它,因为默认
javascript_engine
是coffee
. 可能这应该取决于--javascript_engine
),但似乎无法使其工作。我从这个LINK得到了这条路径,然后通过引用THIS:似乎模式正在流动:lib/templates/gem_name/generator_name/template_file_name.rb
从这个LINK,我也尝试使用路径(但没有用):
- lib/templates/rails/assets/javascript.coffee
- lib/templates/rails/assets/coffee/javascript.coffee
第二步:到目前为止还没有尝试,因为我想先做上面的第一步。
我上面的所有尝试都不起作用:即在两者rails generate my_gem_name:install
都运行之后,然后运行rails generate scaffold some_model_name
仍然会产生原始的默认 javascript 文件,而不是预期的console.log('JUST TESTING!!!!!!!')
内容(如上所述)