Rails,不允许通过本地gem处理管道中具有自定义扩展的样式表

时间:2014-02-18 03:50:28

标签: ruby-on-rails sprockets

如何通过gem预先处理带有自定义扩展名的CSS文件?

我已经搜索了几个小时来解决这个问题,但还没有找到解决方案。我看了LESS,SASS,CoffeeScript,Ember的宝石以获得更好的想法,但是他们处理它的方式对我来说也不起作用。

宝石的构建类似于coffee-rails宝石。 Rails似乎忽略了我通过gem处理自定义扩展样式表所做的任何设置,只是将stylesheet.css.custom标记链接转为stylesheet.css.custom.css,这会产生404错误。

我已经尝试了很多,但我希望这段代码能够很好地总结我一直在做的事情:

# lib/custom-rails.rb
config.app_generators.stylesheet_engine = :custom

# lib/custom-rails.rb
config.before_initialize do |app|
   Sprockets::Engines #force autoloading
   Sprockets.register_engine '.custom', CustomTemplate
 end

# lib/custom/custom_template.rb
ActiveSupport.on_load(:action_view) do
  ActionView::Template.register_template_handler :custom, Custom::Rails::CustomTemplate
end

我正在使用Rail 4.0.1。

我有什么想法可以让gem来处理样式表?谢谢!

2 个答案:

答案 0 :(得分:1)

我终于明白了。

密钥似乎是sprockets.environment之后的初始化程序:

  initializer 'custom-rails.sprockets_engine', after: 'sprockets.environment', group: :all do |app|
    app.assets.register_engine '.custom', CustomerTemplate
  end

这是发现自己处于类似情况的人的最终代码。我还添加了Tilt模板以使其运行良好。

# lib/custom/custom_template.rb
require 'tilt'

module Custom
  module Rails
    class CustomTemplate < ::Tilt::Template
      self.default_mime_type = 'text/css'

      def prepare
      end

      def evaluate(scope, locals, &block)
        # Code for processing
      end

      def allows_script?
        false
      end
    end
  end
end

# lib/custom/engine.rb
module Custom
  module Rails
    class Engine < ::Rails::Engine
      initializer 'custom-rails.sprockets_engine', after: 'sprockets.environment', group: :all do |app|
        app.assets.register_engine '.custom', CustomerTemplate
      end
  end
end

# lib/custom/template_handler.rb
module Custom
  module Rails
    class TemplateHandler
      def self.erb_handler
        @@erb_handler ||= ActionView::Template.registered_template_handler(:erb)
      end

      def self.call(template)
        compiled_source = erb_handler.call(template)
        # Code for processing
      end
    end
  end
end

ActiveSupport.on_load(:action_view) do
  ActionView::Template.register_template_handler :custom, Custom::Rails::TemplateHandler
end

调试的第一步是未正确处理.custom扩展名。我可以看到它们没有得到正确处理,因为CSS是在stylesheets uri而不是assets uri中提供的。

答案 1 :(得分:0)

由于你没有任何答案,我会给你一个想法:


替换

我认为Rails基本上会覆盖你的新宝石&amp;导致custom文件被“编译”为css。我希望从您的资产管道中排除任何.custom文件(允许您单独编译它们):

#app/assets/application.css
/*
  *= require_self
*/

这将只包含application.css.scss,这意味着您可以使用您的gem来编译其他资产

可能不起作用,但这是我的想法