简体   繁体   中英

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. 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. 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.

To escape erb tags, use <%%= %> instead of <%= %> - the latter will actually be evaluated, which allows you to do stuff like <%%= @<%= foo %> %> . This would, in our default case, evaluate to <%= @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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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