2017-03-16 35 views
1

我们在我们的代码中使用了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中放置了一个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 

我应该怎么做才能在生产模式下更改文件? 如何重新预编译文件,然后重新加载应用程序?

+0

预编译的资产应该保持原样;预编译(不重编译)。由于可能存在不一致(在写入时读取),强制执行资产编译和运行时并不是一个好主意(也不是一个好习惯)。您应该将它们放在视图中,这些视图会在运行时编译并提供。您也可以使用[Rails缓存](http://guides.rubyonrails.org/caching_with_rails.html)。 – Wikiti

+0

好的,只有在管理工作时重新编译。在几次。感谢您对该问题的看法。但它可以做到这一点? –

+0

我不确定资产管道是否可以被运行时访问。您可能需要创建一个新的控制器来提供这些文件,并在demmand上进行预编译。 – Wikiti

回答

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> 

当然,这将是更好的部分或帮手粘贴此代码。

+0

是的,我知道这个选项。但我认为最好把代码和样式分开。 –