How does one reference compiled assets from the controller in Rails 3.1?

后端 未结 6 1355
鱼传尺愫
鱼传尺愫 2020-12-09 03:50

I\'m using the PDFkit in my controller to build out a series of PDFs, zip them up, and then send them to the user.

In order to control the output styles, I tell PDFK

相关标签:
6条回答
  • 2020-12-09 04:11

    Rails.application.assets is poorly documented but it provides access to Rails' hook into Sprockets, as a Sprockets::Environment object. Rails uses Sprockets to basically run the whole asset pipeline, and this is where you should hook in for things like this:

    kit.stylesheets << Rails.application.assets['application.css'].pathname
    

    https://github.com/sstephenson/sprockets says of it:

    Accessing Assets Programmatically

    You can use the find_asset method (aliased as []) to retrieve an asset from a Sprockets environment. Pass it a logical path and you'll get a Sprockets::BundledAsset instance back:

      environment['application.js']
      # => #<Sprockets::BundledAsset ...>
    

    Call to_s on the resulting asset to access its contents, length to get its length in bytes, mtime to query its last-modified time, and pathname to get its full path on the filesystem.

    0 讨论(0)
  • 2020-12-09 04:12

    view_context.asset_path 'application.css' should do the trick.

    0 讨论(0)
  • 2020-12-09 04:15

    The best way to get the compiled name is from the manifest that is generate when you compile.

    You can make a controller method that serves the raw name in development, and then accesses the manifest in production to map the correct name.

    The location of the manifest by default is:

    File.join(Rails.public_path, config.assets.prefix, 'manifest.yml')

    But it looks like you can access this as a hash at config.assets.digests

    config.assets.digests[css_file_name_as_string]

    0 讨论(0)
  • 2020-12-09 04:20

    Rails.application.assets['application.css'].pathname always returns the original path of the raw asset, not the precompiled file, so the top answer did not work for me.

    However, calling to_s on the bundled asset instead of pathname does seem to correctly return the body of the precompiled asset, so you can just use an inline style instead of using kit.stylesheets <<:

    <style> <%= Rails.application.assets["application.css"].to_s %> </style>

    0 讨论(0)
  • 2020-12-09 04:20

    One solution is to pull the CSS inline in your view.

    In HAML, this could look like:

    %style
      = Sass.compile(File.read(File.join(Rails.root, 'app', 'assets', 'stylesheets', 'sass', "application.scss")))
    

    Or in ERB:

    <style>
      <%= Sass.compile(File.read(File.join(Rails.root, 'app', 'assets', 'stylesheets', 'sass', "application.scss"))) %>
    </style>
    
    0 讨论(0)
  • 2020-12-09 04:21

    I think stylesheet_path("application") is what you're looking for

    0 讨论(0)
提交回复
热议问题