Skip to content

Commit

Permalink
Add engine class methods for registering assets
Browse files Browse the repository at this point in the history
Problem:

When developing a plugin for Administrate,
there is not a good way to define custom javascripts or stylesheets
to be included on admin pages.

Existing solutions either use `content_for` at the field level,
or require the end user to override Administrate's javascript partial.

Solution:

Add methods to `Administrate::Engine` to keep track of the assets
that need to be loaded on each admin page.

Plugin developers can now use these helpers in their engine definition:

```ruby
Administrate::Engine.add_javascript "my_plugin/script"
Administrate::Engine.add_stylesheet "my_plugin/styles"
```
  • Loading branch information
c-lliope committed May 10, 2016
1 parent 674dcf0 commit e4cc092
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
4 changes: 3 additions & 1 deletion app/views/administrate/application/_javascript.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ but each page can define additional JS sources
by providing a `content_for(:javascript)` block.
%>

<%= javascript_include_tag "administrate/application" %>
<% Administrate::Engine.javascripts.each do |js_path| %>
<%= javascript_include_tag js_path %>
<% end %>

<%= yield :javascript %>

Expand Down
4 changes: 3 additions & 1 deletion app/views/administrate/application/_stylesheet.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ but each page can define additional CSS sources
by providing a `content_for(:stylesheet)` block.
%>

<%= stylesheet_link_tag "administrate/application", media: "all" %>
<% Administrate::Engine.stylesheets.each do |css_path| %>
<%= stylesheet_link_tag css_path %>
<% end %>

<%= yield :stylesheet %>
22 changes: 22 additions & 0 deletions lib/administrate/engine.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,28 @@ module Administrate
class Engine < ::Rails::Engine
isolate_namespace Administrate

@@javascripts = []
@@stylesheets = []

Engine.config.assets.precompile << /\.(?:svg)\z/

def self.add_javascript(script)
@@javascripts << script
end

def self.add_stylesheet(stylesheet)
@@stylesheets << stylesheet
end

def self.stylesheets
@@stylesheets
end

def self.javascripts
@@javascripts
end

add_javascript "administrate/application"
add_stylesheet "administrate/application"
end
end

0 comments on commit e4cc092

Please sign in to comment.