生产中的动态预编译资产

时间:2017-03-16 10:15:15

标签: ruby-on-rails sass asset-pipeline erb sprockets

我们在代码中使用 css.scss.erb 文件。此文件访问de模型对每个循环进行迭代以创建css文件。有时我们需要重做文件(当模型改变时)。

**stylesheets/utils/_comunicaciones.css.scss.erb**

   <%Producto.all.each do |img| %>
    <%unless img.portada.blank?%>
    ##{$id}--<%=img.id%> {

        &:before {
            background: url('<%= img.portada.url(:icon_lands) %>');

            background-position: $bg-position;
            background-size: $bg-size;
            background-repeat: $bg-repeat;
        }
    }
    <%end%>
    <%end%>

我们在config / initializers / assets.rb中为此insue放了一个config.assets.precompile行。

Rails.application.config.assets.precompile += %w( stylesheets/utils/_comunicaciones.css.scss.erb )
Rails.application.config.assets.precompile += %w( '*.css.scss.erb' )

为了使其在开发模式下工作,我们在模型更改时更改文件。

class  ProductoImagen < ActiveRecord::Base
before_save  :precompilar
belongs_to :producto

    def precompilar
  fichero =  File.read('app/assets/stylesheets/utils/_comunicaciones.css.scss.erb').split('/* #=cambios')[0].to_s + '/*' + " #=cambios " + Time.now.to_s + '*/'
  File.open('app/assets/stylesheets/utils/_comunicaciones.css.scss.erb','w') {|f| f.write(fichero)}
  #Rails.application.load_tasks
  #Rake::Task['assets:precompile'].invoke
end

如何在生产模式下更改文件? 如何重新预编译文件和下次重新加载应用程序?

1 个答案:

答案 0 :(得分:0)

没有必要预先编译你想要的东西。只需在你的HTML中嵌入样式:

<html>
  <head>
    <!-- some static styles -->
    <link rel="stylesheet" href="/application.css">

    <!-- dynamic styles -->
    <style>
        <%Producto.all.each do |img| %>
            ##{$id}--<%=img.id%> {
                background: url('<%= img.portada.url(:icon_lands) %>');
                background-position: $bg-position;
                background-size: $bg-size;
                background-repeat: $bg-repeat;
            }
        }
        <%end%>
    </style>
  </head>

  <body>
      <!-- some html -->
  </body>
</html>

当然,最好将此代码粘贴到partial或helper中。

相关问题