Code Monkey home page Code Monkey logo

asset_packager's Introduction

= AssetPackager

JavaScript and CSS Asset Compression for Production Rails Apps

== Description

When it comes time to deploy your new web application, instead of 
sending down a dozen JavaScript and CSS files full of formatting 
and comments, this Rails plugin makes it simple to merge and 
compress JavaScript and CSS down into one or more files, increasing 
speed and saving bandwidth.

When in development, it allows you to use your original versions 
and retain formatting and comments for readability and debugging.

This code is released under the MIT license (like Ruby). You're free 
to rip it up, enhance it, etc. And if you make any enhancements, 
I'd like to know so I can add them back in. Thanks!

* Formerly known as MergeJS.

== Credit

This Rails Plugin was inspired by Cal Henderson's article 
"Serving JavaScript Fast" on Vitamin:
http://www.thinkvitamin.com/features/webapps/serving-javascript-fast

It also uses the Ruby JavaScript Minifier created by 
Douglas Crockford.
http://www.crockford.com/javascript/jsmin.html

== Key Features

* Merges and compresses JavaScript and CSS when running in production.
* Uses uncompressed originals when running in development.
* Generates packages on demand in production

== Components

* Rake tasks for managing packages
* Helper functions for including these JavaScript and CSS files in your views.
* YAML configuration file for mapping JavaScript and CSS files to packages.
* Rake Task for auto-generating the YAML file from your existing JavaScript files.

== Updates

November '08:
* Rails 2.2 compatibility fixes
* No more mucking with internal Rails functions, which means:
  * Return to use of query-string timestamps. Greatly simplifies things.
  * Multiple asset-hosts supported
  * Filenames with "."'s in them, such as "jquery-x.x.x" are supported.
* Now compatible with any revision control system since it no longer uses revision numbers.
* Packages generated on demand in production mode. Running create_all rake task no longer necessary.

== How to Use:

1. Download and install the plugin:
   ./script/plugin install git://github.com/sbecker/asset_packager.git

2. Run the rake task "asset:packager:create_yml" to generate the /config/asset_packages.yml
file the first time. You will need to reorder files under 'base' so dependencies are loaded 
in correct order. Feel free to rename or create new file packages.

IMPORTANT: JavaScript files can break once compressed if each statement doesn't end with a semi-colon.
The minifier puts multiple statements on one line, so if the semi-colon is missing, the statement may no 
longer makes sense and cause a syntax error.

== Examples of config/asset_packages.yml

Example from a fresh rails app after running the rake task. (Stylesheets is blank because a 
default rails app has no stylesheets yet.):

--- 
javascripts: 
- base: 
  - prototype
  - effects
  - dragdrop
  - controls
  - application
stylesheets: 
- base: []

Multiple packages:

---
javascripts:
- base:
  - prototype
  - effects
  - controls
  - dragdrop
  - application
- secondary:
  - foo
  - bar
stylesheets:
- base:
  - screen
  - header
- secondary:
  - foo
  - bar

3. Run the rake task "asset:packager:build_all" to generate the compressed, merged versions
for each package. Whenever you rearrange the yaml file, you'll need to run this task again. 

Merging and compressing is expensive, so this is something we want to do once, not every time
your app starts. Thats why its a rake task. You can run this task via Capistrano when deploying
to avoid an initially slow request the first time a page is generated. 

Note: The package will be generated on the fly if it doesn't yet exist, so you don't *need* 
to run the rake task when deploying, its just recommended for speeding up initial requests.

4. Use the helper functions whenever including these files in your application. See below for examples.

5. Potential warning: css compressor function currently removes CSS comments. This might blow
away some CSS hackery. To disable comment removal, comment out /lib/synthesis/asset_package.rb line 176.

== JavaScript Examples

Example call (based on above /config/asset_packages.yml):
  <%= javascript_include_merged :base %>

In development, this generates: 
  <script type="text/javascript" src="/javascripts/prototype.js?1228027240"></script>
  <script type="text/javascript" src="/javascripts/effects.js?1228027240"></script>
  <script type="text/javascript" src="/javascripts/controls.js?1228027240"></script>
  <script type="text/javascript" src="/javascripts/dragdrop.js?1228027240"></script>
  <script type="text/javascript" src="/javascripts/application.js?1228027240"></script>

In production, this generates: 
  <script type="text/javascript" src="/javascripts/base_packaged.js?123456789"></script>

== Stylesheet Examples

Example call:
  <%= stylesheet_link_merged :base %>

In development, this generates:
  <link href="/stylesheets/screen.css?1228027240" media="screen" rel="Stylesheet" type="text/css" />
  <link href="/stylesheets/header.css?1228027240" media="screen" rel="Stylesheet" type="text/css" />

In production this generates:
  <link href="/stylesheets/base_packaged.css?1228027240" media="screen" rel="Stylesheet" type="text/css" />

== Different CSS Media

All options for stylesheet_link_tag still work, so if you want to specify a different media type:
  <%= stylesheet_link_merged :secondary, 'media' => 'print' %>

== Rake tasks

rake asset:packager:build_all        # Merge and compress assets
rake asset:packager:create_yml       # Generate asset_packages.yml from existing assets
rake asset:packager:delete_all       # Delete all asset builds

== Running the tests

This plugin has a full suite of tests. But since they
depend on rails, it has to be run in the context of a
rails app, in the vendor/plugins directory. Observe:

> rails newtestapp
> cd newtestapp
> ./script/plugin install ./script/plugin install git://github.com/sbecker/asset_packager.git
> rake test:plugins PLUGIN=asset_packager # all tests pass

== License
Copyright (c) 2006-2008 Scott Becker - http://synthesis.sbecker.net
Contact via Github for change requests, etc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

asset_packager's People

Contributors

jakimowicz avatar rainux avatar sbecker avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

asset_packager's Issues

Cannot build production package

Hi,
I've installed your plugin and uses it for development, but on attempt to create production package i see following error

 $ rake asset:packager:build_all
 (in /Users/alec/Documents/Projects/Workspaces/my_projects/cyberberry_geeks)
 rake aborted!
 No such file or directory - /Users/alec/Documents/Projects/Workspaces/my_projects/cyberberry_geeks/tmp/base_packaged_uncompressed.js

How can i solve it?

issue include jquery.cookie

I have the jquery.cookie.js file in my public javascripts folder and here is my yml, It seem to include the rest of the .js files but for some reason does not include the jquery.cookie in the development environment pages, it does seem to include it in the base_packaged.js file?

--- 
javascripts: 
- base: 
  - jquery.tools.min
  - jquery.cookie
  - application
stylesheets: 
- base:
  - custom
  - screen
  - formtastic
  - jquery-ui-1.8.2.custom
#  - reset
#  - ie

no such file to load -- asset_packager (LoadError)

installing with rails plugin install git://github.com/sbecker/asset_packager.git

i see this error:

~/.rvm/gems/ruby-1.9.2-p180/gems/activesupport-3.0.7/lib/active_support/dependencies.rb:239:in `require': no such file to load -- asset_packager (LoadError)

undefined local variable or method `config' for Synthesis::AssetPackag

Hi,
I'm getting this error when I try to run my app. Any suggestion ?

=> Booting WEBrick
=> Rails 2.3.5 application starting on http://0.0.0.0:3000
/var/lib/gems/1.8/gems/rails-2.3.5/lib/rails/gem_dependency.rb:119:Warning: Gem::Dependency#version_requirements is deprecated and will be removed on or after August 2010. Use #requirement
/var/lib/gems/1.8/gems/asset_packager-0.2.0/lib/synthesis/asset_package.rb:6: undefined local variable or method `config' for Synthesis::AssetPackage:Class (NameError)

Thanks in advance

rails 2.3.8 deprecation warning

DEPRECATION WARNING: Rake tasks in vendor/plugins/asset_packager/tasks are deprecated. Use lib/tasks instead. (called from [...]/vendor/isolated/gems/rails-2.3.8/lib/tasks/rails.rb:10)

Google Closure: Error(22): Too many compiles performed recently. Try again later.

We have several apps that get deployed in serial. When using Google's Closure service to compile JS, the resulting JavaScript files contained only the following:

Error(22): Too many compiles performed recently. Try again later.

This was obviously causing catastrophic failure with our JS. To avoid this problem, perhaps asset_packager should check for the presence of this string in resulting JS files and re-try after a set period?

How to package stylesheets with local images?

I'm using jquery plugins. Each is a separate folder in my javascript directory. These folders contain css files and images that are referred to from the css files.
When asset_packager combined these files the path to the images is not adapted to find the images in their original folder. An example:
Part of my .yml file:

  • ../javascripts/tools/styles

Given the following files
javascript/tools/styles.css => in this file a reference to url(tooltip.png) refers to the following file:
javascript/tools/tooltip.png

After packaging the image reference hasn't changed and the image can't be found.

Can this be accomplished?

Thanks

Run build_all whenever assets changed

The problem:

  • it is easy to forget to run the build_all rake task
  • this creates hours of chasing one's tail trying to find the bug in deployment for things that worked fine in development.

A solution:

  • Store the most recent datetime of any asset and use that to detect whether anything has been updated since the rake task last ran. Automatically rebuild the assets in this is detected.
  • Two ideas for storing the most recent datetime:
  • As an extension to the file name (eg. base_packaged_200904051314.css)
  • As the actual datetime stamp (last modified) of the of the base_packaged.css file

package broken when hash is followed by jquery plugin

JS package is broken when merging a hash followed by a typical jquery plugin.
Example:

<first.js>
Tools={
myfn: function() {}
}

<second.js>
(function($){...})(jQuery)

after packaging this essentially produces the following:
Tools={...}(function($){...})(jQuery)

which, upon execution, crashes with the following error:
({myfn:(function () {...}) is not a function

...and the rest of the package may be broken as well to a varying extent.

to fix that, one must explicitly separate the hash and the plugin with a semicolon:

<first.js>
Tools={
...
}; //<-- !!!


bottomline is - that sucks

Move tasks directory

The Rails 3 requires the "tasks" directory to be inside "lib". This can be safely moved out since it works on previous versions as well.

Rails 3: Have to use Rails.env instead RAILS_ENV

The helpers (with the should_merge? method) always consider the env to development, consequently the compressed files are never included in production.
The RAILS_ENV var does not exist anymore in rails 3.
You may should Rails.env instead.

assets in subdirectories…?

I'm compulsively organized—organized to a fault, some might say—and I was trying to organize my JavaScript files according to the section of the site they pertain to:

javascripts
javascripts/application.js
javascripts/section1/base.js
javascripts/section2/base.js
etc.

but they don't seem to be loading at all with the configuration I have set up:


---
javascripts:
- section1:
  - application
  - section1/base

Is there any support for nested assets on the horizon? Or does such a thing already exist and I'm a complete moron?

Any help or just a general reply would be great!

Dallas

Helpers should return safe html

All HTML strings should be marked as safe on Rails 3; otherwise, the tags will be escaped.

You can do this by calling the "html_safe" method before returning the strings.

prototype-1.7_rc2 unable to place inside of asset_package

I have to exclude prototype.js (v 1.7_rc2) from the asset package, and load it with javascript_include_tag in order to get prototype to load. The rake task asset:packager:build_all succeeds with prototype in the package, but it still fails to load.

Create timestamped assets.

I really like your tool and it works great with the default rails cache busting approach of adding a timestamp after ?. However when you use with the amazon CDN the ?timestamp part of the URL is not taken into account.

It would be great if the asset packager could help busting the CDN cache without requiring additional steps to the current workflow. One approach would be to:

  1. save the build timestamp into a configuration file, asset_manager_auto.yml
  2. create a file with a timestamped name
  3. in production when generating the link automatically append the timestamp, for example base_1562827.css, base_1562827.js

I can help with the implementation once we reach a consensus on an approach that works...

file list from package

I've run into an interesting use case where I'd like to get back an array of files included in the package (instead of the style tags).

For instance, if the method were called stylesheet_files_merged, one could do:

# in development
stylesheet_files_merged(:base) = ["/stylesheets/screen.css", "/stylesheets/header.css"]

# in production
stylesheet_files_merged(:base) = ["/stylesheets/base_packaged.css"]

I took a look through the source, but the right combination of methods didn't jump out at me. Any advice?

Can't load non-file resources

If you have a js file that's rendered through a controller, or use the js_named_routes(http://github.com/jsierles/js_named_routes ) plugin, there doesn't seem to be a way to get them packaged.

Perhaps instead of opening files, it could call for the resources the regular way (through a url) then build them from there. That way it would work for absolutely any method of serving resources.

Escaped link/include tags on Rails 3.0.3

It's simple to fix in lib/synthesis/asset_package_helper.rb:

sources.collect {|source| javascript_include_tag(source, options) }.join("\n").html_safe

... and ...

sources.collect { |source| stylesheet_link_tag(source, options) }.join("\n").html_safe

Issue with using inline_attachment when asset packager plugin is installed

Hi,

I am new to Rails and my question may be very trivial.

I have asset_packager plugin installed in my app. I installed JasonKing's inline_attachment plugin for sending out emails with inline images. But when I try to send a email I am getting a error message (undefined method 'request') and this error seems to happen in 'compute_public_path' in asset_package_helper class of asset_packager plugin and it is working fine when asset packager is uninstalled.

Is there any workaround for this? Please let me know if you need more details.

Thanks,
Sivakumar.

Javascript line continuations in strings causes errors

vendor/plugins/asset_packager/lib/jsmin.rb:113:in `action': Unterminated string literal (RuntimeError)
    from vendor/plugins/asset_packager/lib/jsmin.rb:195:in `jsmin'
    from vendor/plugins/asset_packager/lib/jsmin.rb:205

Which is caused by code such as:
styleSheet.addRule(
'.typeface-js-selected-text',
'-ms-filter:
"Chroma(color=black)
progid:DXImageTransform.Microsoft.MaskFilter(Color=white)
progid:DXImageTransform.Microsoft.MaskFilter(Color=blue)
alpha(opacity=30)" !important;
color: black;
font-family: Modern;
position: absolute;
white-space: pre;
filter: alpha(opacity=0);'
);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.