Created
January 19, 2012 13:31
-
-
Save daronco/1640062 to your computer and use it in GitHub Desktop.
Organize javascripts and stylesheets like views in rails 3.1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Call the helpers 'javascript_include_tags_for_action' and 'stylesheet_link_tags_for_action' in the headers section | |
of your layout to automatically include javascript and stylesheet files for the current controller and action. | |
The files are included only if they exist. It is first included the file for all the actions of acontroller (e.g 'events/_all.js') | |
and then the file for the current action (e.g. 'events/show.js'). | |
You can organize javascripts and stylesheets like views are organized. | |
Assuming you have the controllers "Events" and "Spaces": | |
- app/ | |
- assets/ | |
- javascripts/ | |
- events/ | |
- _all.js | |
- index.js | |
- show.js | |
- spaces/ | |
- _all.js | |
- edit.js | |
- index.js | |
- stylesheets/ | |
- events/ | |
- _all.css | |
- spaces/ | |
- edit.css | |
- index.css | |
- show.css | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%html | |
%head | |
... | |
-# Automatically includes js's and css's for the current controller and action | |
- javascript_include_tags_for_action | |
- stylesheet_link_tags_for_action | |
... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ApplicationHelper | |
# Ex: asset_exists?('news/edit', 'css') | |
def asset_exists?(asset_name, default_ext) | |
!YourApplication::Application.assets.find_asset(asset_name + '.' + default_ext).nil? | |
end | |
# Includes javascripts for the current controller and action | |
# Example: 'assets/events/_all.js' and 'assets/events/show.js' | |
def javascript_include_tags_for_action | |
["_all", params[:action]].each do |action| | |
asset = "#{params[:controller]}/#{action}" | |
concat(javascript_include_tag(asset)) if asset_exists?(asset, "js") | |
end | |
end | |
# Includes stylesheets for the current controller and action | |
# Example: 'assets/events/_all.css' and 'assets/events/show.css' | |
def stylesheet_link_tags_for_action | |
["_all", params[:action]].each do |action| | |
asset = "#{params[:controller]}/#{action}" | |
concat(stylesheet_link_tag(asset)) if asset_exists?(asset, "css") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment