5

自定义rails项目模板

 3 years ago
source link: http://blog.ilibrary.me/2019/11/08/%E8%87%AA%E5%AE%9A%E4%B9%89rails%E9%A1%B9%E7%9B%AE%E6%A8%A1%E6%9D%BF
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
欢迎转载,请支持原创,保留原文链接:blog.ilibrary.me

Rails可以通过命令直接生成一个项目,里面包含了一些常用gems. 大部分时候我们还是会要去改项目配置,添加gems, 语言,时区, 更改gem source等。这些重复的工作可以通过自定义模板实现。

我写了一个项目模板,把自己常用的gem,dockerfile和一些设置写进了模板了。

使用的时候把代码下载下来,然后运行rails new your_app -m <path_to_template/activeadmin_template.rb>就可以通过生成新的项目。

自己创建模板

自己创建模板也非常简单,新建一个rb,然后通过thor命令去修改你想要修改的文件。

  1. comment_lines, 按行注释内容。

     comment_lines 'Gemfile', /rubygems.org/ # 注释掉Gemfile里面带rubygems.org的行
    
  2. insert_into_file, 插入内容,注意自己添加换行。

     #"在group :development, :test do"之前插入"gem 'test'", 如果是想在之后,则把before换成after
     insert_into_file "Gemfile", "gem 'test'\n",before: "\ngroup :development, :test do\n" 
    
  3. copy_file, 拷贝文件.

     # 把docker/.dockerignore拷贝到项目根目录
     copy_file "docker/.dockerignore", '.dockerignore' 
    
  4. inside, 指定操作路径, 相当于路径切换

    inside 'config' do
         copy_file 'unicorn.rb' # 从模板'config/unicorn.rb'拷贝到'config/unicorn.rb'
    end
    
  5. gsub_file, 替换内容

     # 把config/webpacker.yml里面check_yarn_integrity的true换成false
     gsub_file 'config/webpacker.yml', 'check_yarn_integrity: true', 'check_yarn_integrity: false'
    
  6. remove_file, 删除文件
  7. template, 通过模板生成文件。这个比copy_file强大。

    模板文件, @app_name是默认可用的变量

    <!DOCTYPE html>
     <html>
         <head>
             <!-- this ERB will be processed when we generate our app -->
             <title><%= @app_name.humanize %></title>
             <!-- this will end up as ERB in the generated file and
        not processed during application generation -->
             <%%= stylesheet_link_tag    "application", media: "all" %>
             <%%= javascript_include_tag "application" %>
             <%%= csrf_meta_tags %>
         </head>
     <body>
         <h1>Welcome to <%= @app_name.humanize %>!</h1>
         <%%= yield %>
     </body>
     </html>
    

    通过模板命令替换生成文件, 这生成的是动态内容。

    inside 'app' do
         inside 'views' do
             inside 'layouts' do
                 template 'applicaiton.html.erb'
             end
         end
     end
    

更加详细的rails template使用方法可以参考Rails Application Templates


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK