eco*_*gic 10 customization ruby-on-rails scaffold ruby-on-rails-3
我正在尝试自定义我的脚手架生成器,我想在同一目录中为视图设置一个新的部分,特别_item是在index和show中都被调用.我可以获得所有模板,但我无法生成此文件
rails g scaffold foo name:string
Run Code Online (Sandbox Code Playgroud)
我试图将_item.erb放入/lib/templates/erb/scaffold/(与其他文件一起),但它被忽略了 - 有人有线索吗?
我在rails 3上使用ruby,但如果解决方案对rails 2也有效,请告诉我.我也使用simple_form(因此我已经有_form部分),但我认为解决方案即使没有它也应该有效.
And*_*ing 15
我遇到了这个问题希望找到答案,因为如果您想要:默认的rails支架生成器非常残缺:
唉,我卷起袖子,弄清楚如何让铁轨脚手架发电机支持我在当前项目中使用的上述要求.
如果您想在键入时完全控制脚手架模板,请rails g scaffold Foo ...继续阅读!
默认的rails scaffold生成器是模板引擎特定的,并且硬编码它寻找的一组固定的视图文件.
使用自定义生成器并将其连接到脚手架模板生成.
我在下面包含了一个生成器lib/templates/scaffold,它将生成所有文件的脚手架视图,包括模板,部分和子目录,无论模板引擎如何.
IMO这应该是默认的rails行为,而不是我们必须跳过这样的篮球..
请执行下列操作:
lib/templates/scaffold.注意没有erb子目录!!# config/initializers/generators.rb
Rails.application.config.generators do |g|
# ...
g.template_engine :all
g.fallbacks[:all] = :erb # or haml/slim etc
end
Run Code Online (Sandbox Code Playgroud)
# config/application.rb
config.generators do |g|
# ...
g.template_engine :all
g.fallbacks[:all] = :erb # or haml/slim etc
end
Run Code Online (Sandbox Code Playgroud)
# lib/generators/all/scaffold/scaffold_generator.rb
require 'rails/generators/named_base'
require 'rails/generators/resource_helpers'
module All # :nodoc:
module Generators # :nodoc:
class ScaffoldGenerator < Rails::Generators::NamedBase # :nodoc:
include Rails::Generators::ResourceHelpers
source_root File.join(Rails.root, 'lib', 'templates', 'scaffold', File::SEPARATOR)
argument :attributes, type: :array, default: [], banner: "field:type field:type"
def create_root_folder
empty_directory File.join("app/views", controller_file_path)
end
def copy_view_files
available_views.each do |view|
template view, File.join("app/views", controller_file_path, view)
end
end
protected
def available_views
# use all template files contained in source_root ie 'lib/templates/scaffold/**/*'
base = self.class.source_root
base_len = base.length
Dir[File.join(base, '**', '*')].select { |f| File.file?(f) }.map{|f| f[base_len..-1]}
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
没有保修:)
我希望这可以帮助那些想要用部分重构他们的脚手架视图并支持多个模板引擎的人.
小智 4
刚刚找到了。
它是硬编码的。您可以更改它:
def available_views
%w(index edit show new _form)
end
Run Code Online (Sandbox Code Playgroud)
在我的索引模板中,我这样做:
<thead id="thead_js">
<%%= render 'thead' %>
<!-- CUT TO _thead.html.erb -->
<tr>
<% for attribute in attributes -%>
<th><%%= sortable( <%= attribute.name %>, <%= attribute.human_name %> ) %></th>
<% end %>
<th> </th>
</tr>
<!-- END CUT TO -->
</thead>
Run Code Online (Sandbox Code Playgroud)
然后,刚刚创建了一个 rake 任务来读取该评论并创建新文件。
丑陋但有效。
| 归档时间: |
|
| 查看次数: |
2432 次 |
| 最近记录: |