Max Ivak
Max Ivak

Reputation: 1549

Include gem's assets in Rails 4

I've created a gem (not engine) that has some js files in it:

lib/assets/javascripts/mygem.js

In my application, I want to include this js into application.js:

# app/assets/javascripts/application.js

// require mygem  # DOESN'T WORK

This doesn't work.

Is it possible to include assets from gems? Or I should write a generator for a gem which will copy all assets from gem into application assets folder.

Upvotes: 4

Views: 1515

Answers (1)

Max Ivak
Max Ivak

Reputation: 1549

Add Engine class to the gem and require it in gem:

# lib/mygem/rails/engine.rb
module Mygem
  module Rails
    class Engine < ::Rails::Engine

    end
  end
end

 

# lib/mygem.rb:
module Mygem
  require 'mygem/rails/engine'

end

Now assets from the gem are available in application:

Gemfile:

 gem 'mygem'

app/assets/javascripts/application.js

//= require mygem

Read about adding Assets to Your Gems:

http://guides.rubyonrails.org/asset_pipeline.html#adding-assets-to-your-gems

Upvotes: 5

Related Questions