Precompile Assets From Rails 3.1 Engines

Today I finally finished the rails 3.1 upgrade for our open source CMS Alchemy.

An issue I ran into was, that while deploying, the assets from inside the engine weren’t precompiled.

I solved it by telling the main app to also precompile Alchemys assets:

# lib/alchemy/engine.rb
module Alchemy
  class Engine < Rails::Engine

    # Config defaults
    config.mount_at = '/'

    # Enabling assets precompiling under rails 3.1
    if Rails.version >= '3.1'
      initializer :assets do |config|
        Rails.application.config.assets.precompile += %w( alchemy/alchemy.js alchemy/alchemy.css alchemy/print.css )
      end
    end

    # Check the gem config
    initializer "check config" do |app|
      # make sure mount_at ends with trailing slash
      config.mount_at += '/'  unless config.mount_at.last == '/'
    end

    initializer :flash_cookie do |config|
      config.middleware.insert_after(
        'ActionDispatch::Cookies',
        Alchemy::Middleware::FlashSessionCookie,
        ::Rails.configuration.session_options[:key]
      )
    end

  end
end

The important part is:

Rails.application.config.assets.precompile += %w( alchemy/alchemy.js alchemy/alchemy.css alchemy/print.css )

Be sure to put it inside an

initializer

block. So the main app gets loaded before changing the setting.

As Argument you should pass an array of all the assets you want to be precompiled together with the main app ones.

 

4 Gedanken zu „Precompile Assets From Rails 3.1 Engines“

  1. +1, thanks for sharing!
    I was suspecting something easy like that could be done in the engine.rb .

  2. Do you know how to get the initializer block to get called on a rake asset:precompile?
    The engine is loaded on the rake task, but done of my intializers get called, especially the one I want “initializer “split.assets.precompile” do |app|….”

Hinterlasse eine Antwort

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind markiert *

Du kannst folgende HTML-Tags benutzen: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>