assets in cells

some background information about assets in Rails and how to bundle assets in cell’s view directory.

  1. http://trailblazer.to/gems/cells/rails.html#asset-pipeline

basics

using asset tag helpers

http://trailblazer.to/gems/cells/helpers.html#asset-helpers

asset tag helpers provided by Cell::ViewModel ignore Rails assets prefix (/assets) - they use different prefixes for different assets: /stylesheets for stylesheets, /javascripts for javascripts, etc. as a result sprockets cannot find assets using URLs generated by these helpers.

including ActionView::Helpers::AssetTagHelper into cell doesn’t help.

solution: use original asset tag helpers provided by controller’s view context.

app/cells/my_cell.rb:

class MyCell < Cell::ViewModel
  delegate :wicked_pdf_stylesheet_link_tag, to: :view_context

  ...
private

  def view_context
    parent_controller.view_context
  end

  ...
end

in specs either stub view_context:

app/cells/my_cell_spec.rb:

describe MyCell do
  let(:view_context) { double wicked_pdf_stylesheet_link_tag: nil }
  before { allow(act_cell).to receive(:view_context).and_return view_context }

  ...
end

or specify controller to make view_context available:

describe MyCell do
  controller Billing::AccountingActsController

  ...
end

IMPORTANT! only precompiled assets (having their compiled versions in public/assets/) can be referenced by asset tag helpers - in application layout file asset tag helpers usually reference application manifests only which are precompiled by default (without adding them to precompile array).

all other assets if referenced by asset tag helpers won’t be found by generated script or stylesheet tags - even if they are required in application manifests and thusly included into their compiled versions.

to be able to reference other assets in asset tag helpers it’s necessary to add these assets to precompile array manually in config/initializers/assets.rb. when done it doesn’t matter where you use these asset tag helpers - in application layout file or anywhere else.

in example above it’s necessary to add whatever asset is referenced by wicked_pdf_stylesheet_link_tag asset tag helper to precompile array manually.