简体   繁体   English

Rails创建一个新的脚手架生成器

[英]Rails creating a new scaffold generator

I'm going to be working on a project that has a very large data model but doesn't require the views to look too unique. 我将要开发一个数据模型非常大但不需要视图看起来过于独特的项目。 I think a good way to speed up the work involved would be to create a generator that acts a lot like scaffold, but uses things like simple form and bootstrap classes instead. 我认为,加快工作速度的一个好方法是创建一个生成器,其作用类似于支架,但是使用简单形式和引导类之类的东西。 Not very different from scaffold, juts a few minor changes. 与脚手架差别不大,突出了一些小的变化。 Any ideas how I could go about doing this? 有什么想法我可以去做吗?

I recently built a scaffolding generator. 我最近建造了脚手架发电机。 Two important things I did: 我做了两件事:

This helped me understand the way gems work, and gave me a bit more flexibility when it comes to asset management, etc. 这帮助我了解了宝石的工作方式,并在资产管理等方面给了我更多的灵活性。

With that said, Rails generators make use of Thor. 话虽如此,Rails生成器利用了Thor。 The most important thing to know is that you'll need to somehow load the file (I'd suggest making use of an initializer and the lib directory) and that the file will run every publicly defined method. 要知道的最重要的事情是,您将需要以某种方式加载文件(我建议使用初始化程序和lib目录),并且该文件将运行每个公共定义的方法。 This is a little weird and unexpected, but it helps keep the code clean. 这有点怪异和意外,但它有助于保持代码的干净。

For instance: 例如:

class CustomerGenerator < Rails::Generators::Base
    argument :foo, :type => :string, :default => 'foozball'
    def create_view_files
        template 'path/to/your/view.html.erb',"app/views/view.html.erb"
    end
end

This would automatically call create_view_files , and you'd have access to the :foo argument as foo in the class as well as in the templates. 这将自动调用create_view_files ,您将可以在类以及模板中以foo的形式访问:foo参数。

To escape erb tags, use <%%= %> instead of <%= %> - the latter will actually be evaluated, which allows you to do stuff like <%%= @<%= foo %> %> . 要转义erb标签,请使用<%%= %>而不是<%= %> -后者将被实际评估,这使您可以执行<%%= @<%= foo %> %> This would, in our default case, evaluate to <%= @foozball %> . 在我们的默认情况下,这将评估为<%= @foozball %>

You may want to take a look at nifty generators to get everything in line, but this is the basics of how the actual generator works. 您可能想要看一看漂亮的生成器以使所有内容保持一致,但这是实际生成器如何工作的基础。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM