将css(带变量)打印到文件中

时间:2018-05-08 16:07:29

标签: css ruby-on-rails file service render

我有一个生成epub的服务,因此我需要生成一个嵌入epub的css文件。

我在epub/style.css.erb下创建了一个css视图,但由于逻辑在服务中而不在控制器中,似乎无法调用render_to_string。实际上,该服务包含在sidekiq作业中,该作业也可以从模型的after_update调用,因此这会进一步妨碍render_to_string

我可以像EpubController一样创建并从那里调用render_to_string方法。但是从位于app/services/epub_export.rb下的我的服务中,如何向控制器发送/接收输出的参数?这种方式闻起来就像我打破了MVC模式。

但我也不喜欢古典的方式,例如

File.open(@css_path, 'w') do |f|
  f.puts "@charset utf-8;"
  f.puts "/* Styles for GEPUB Sample Book */"
  f.puts "h1"
  f.puts "{"
  f.puts "  text-align: center;"
  f.puts "  color: #0000ff;"
  f.puts "  font-weight: normal;"
  f.puts "  font-family: #{@font_family};"
  f.puts "}"
end

或者有替代方案吗?

1 个答案:

答案 0 :(得分:1)

我一直在控制器外的异步作业中使用render_to_string来生成pdf。这看起来像是:

class FooService

  ...

  def pdf
    ActionController::Base.new.render_to_string(
      pdf:        "pdf_name", 
      template:   'path/to/template',
      locals:     {presenter: self},
      page_size:  'Letter',
      encoding:   "UTF-8",
      margin: {
        top: 20,
        bottom: 20
      }
    )
  end

  ...

end

您是否尝试过这些方法?