Rails 3.1, exclude JS files from asset pipeline - ruby-on-rails-3.1

I know there are a million questions already on this, but I can't get this.
I want to include most of my JS files in the asset pipeline, but I have a few I want to load conditionally (or only on certain pages). These are big, complicated files and will never, ever be used by 95% of the users, so I'd rather not have them loaded for every user. One set of JS files is for a calendar, placed in:
app/assets/javascripts/calendar
So my manifest is set up to include only the top directory (and exclude the calendar subdirectory):
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require_directory .
My config/environments/production.rb:
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# This following config is left over from previous Rails app,
# so not sure if it's now unnecessary ...
# Disable Rails's static asset server
# In production, Apache or nginx will already do this
config.serve_static_assets = false
In the view, I'm using Ryan Bates' nifty_layout to manually include the calendar files:
javascript "calendar/date.js", "calendar/jquery.weekcalendar.js", "calendar/custom.js"
I've tried precompiling in both development and production -- the docs aren't clear where I'm supposed to do this, but it looks like production.
And when I run the page, I get this:
ActionView::Template::Error (calendar/date.js isn't precompiled)
I don't want it precompiled. I want it loaded manually. (Actually, it would be OK to precompile in a file other than the main application.js that is created, but I don't know how to do that.)
What's the solution?
Thanks!

OK, I didn't realize this was how it works, but I think I figured it out.
Add the files to be manually loaded to config/environments/production.rb like so:
config.assets.precompile += %w( calendar/*.js jquery_calendar/*.css )
I thought this just folded them into the application.js and application.css, but apparently not -- it compiles them as individual files.
Then, you can call the files as you traditionally would (in this case, using nifty_layout):
javascript "calendar/date.js", "calendar/jquery.weekcalendar.js", "calendar/custom.js"

Related

AWS to serve CSS images Sinatra

I am using the asset_sync gem to sync my assets to a S3 bucket. In production i want to use S3 and in development i want to use my local files. So i have setup the following along with a helper
environments/development.rb
configure :development do
set :asset_host, "/"
end
environments/production.rb
configure :production do
set :asset_host, "https://s3-eu-west-1.amazonaws.com/#{ENV['FOG_DIRECTORY']}"
end
helper
helpers do
def aws_asset( path )
File.join settings.asset_host, path
end
end
So in my views i can do this
<%= image_tag( aws_asset "/assets/images/wd.png") %>
Which will result in rendering that image from my local assets if in development or from my bucket when in production
So what if i want to render an image from within my main.css file, such as a background image? I cant do the below for example as its not an erb file
main.css
header{
background: #ffffff url('<%= aws_asset("/assets/images/bgwRpeat.png") %>') repeat-x;
}
So what can I do? Has anyone done this before
Thanks for any help anyone can offer
3 ways come to mind.
Precompile the assets
Before you deploy, precompile the assets and CSS. If you create a file called main.css.erb and then run it through ERB to produce main.css it'll have the right stuff inside. This would be my preference. There are lots of ways to precompile, I prefer Guard but YMMV.
Edit:
Lifted and twisted from the Guard::Erb docs
guard 'erb', :input => 'app/views/stylesheets/main.css.erb', :output => "public/assets/stylesheets/main.css" do
watch (%r{app/views/stylesheets/main.css.erb})
end
Something like that.
Create a route that then compiles the assets
This is similar to how you might use SASS templates with Sinatra (if you don't precompile them). Just do the same as above, set up a route for main.css, run the main.css.erb template through ERB and serve it. Add lots of caching.
Edit:
get "/assets/stylesheets/main.css" do
# remember to look at caching
erb :"stylesheets/main.css"
end
I started writing and I can't remember the 3rd :) In my defence, I've a terrible headache. Perhaps someone else will remember for me.

Why won't Rails find my assets?

When in production mode, rails can't seem to find any precompiled assets from the asset pipeline.
I'm using rails 3.2.0 and ruby 1.9.3 running inside RVM on CentOS. No additional web server is running in conjunction with this application. The application was only recently updated to use the asset pipeline, as it was originally a rails 3.0 app.
After running
rake assets:clean
rake assets:precompile
I see the hashed content in public/assets, as I would expect. The hashes at the end of the files match those I see in the page source.
Yet at runtime, here's what I see for every asset Rails tries to serve:
Started GET "/assets/application-892c6227e631daf9a8e041b1d4d002ec.css" for 75.149.58.169 at 2012-03-14 11:42:43 -0700
ActionController::RoutingError (No route matches [GET] "/assets/application-892c6227e631daf9a8e041b1d4d002ec.css"):
I'm not referring to the folder that each asset is housed in; all references to assets look like these:
//css:
.class {
background: url(asset.png) no-repeat;
}
//erb:
<%= image_tag "asset.png" %>
<%= link_to "page", :class => "class" %>
Asset pipeline pertinent settings in production.rb:
config.serve_static_assets = false
config.assets.enabled = true
config.assets.compress = true
config.assets.debug = false
config.assets.compile = false
config.assets.digest = true
And lastly, asset settings from config/application.rb:
config.assets.enabled = true
config.assets.version = '1.0'
The user starting the rails server process has read, write and execute permissions on public/assets, so I don't think it's a permissions issue. Have I missed a configuration step?
Edit
I noticed that there are no errors stating that assets are not precompiled, so I tried to access a stylesheet from the web page by appending"/assets/application-892c6227e631daf9a8e041b1d4d002ec.css" to the end of the host path:
http://www.myapp.com"/assets/application-892c6227e631daf9a8e041b1d4d002ec.css"
This worked and the stylesheet opened.
Further researching of this issue yielded this SO article:
application.css not being served as an asset
It seems
config.serve_static_assets = false
Is an incorrect setting as long as my Rails application is not running behind Apache or nginx
I had this same problem, but I note that your stylesheet is pointing to the non-fingerprinted, non-cached version of the files. If you are using the asset pipeline, in order to take advantage of it, you need to use the helpers that point to the fingerprinted, cached version of the files. To do this, you'll need to either embed erb in your css file, or use sass.
Incorrect:
.class {
background: url(asset.png) no-repeat;
}
Correct (uses sass):
.class
background: image-url('asset.png') no-repeat
For more info, see here: http://guides.rubyonrails.org/asset_pipeline.html#coding-links-to-assets
If you don't care about the performance issues, you can get away with using the non-cached versions until you upgrade to Rails 4 or Rails 3.2.16, because those versions introduce breaking changes that force you to use the asset pipeline (and its corresponding syntax). If you don't use the new syntax, the non-cached versions will not work at all on production.

Integrating CKEditor with Rails 3.2

Similar to Integrating CKEditor with Rails 3.1 Asset Pipline
I am trying to integrate ckeditor with my rails 3.2 application.
I have all ckeditor files copied under /app/assets/javascripts/ckeditor/*.
I have the following lines in my application.js and application.js is included in my layout file:
//= require jquery
//= require jquery_ujs
//= require ckeditor/ckeditor
//= require_self
Taken it from the answer to Integrating CKEditor with Rails 3.1 Asset Pipline
I can understand that I need to add something like:
config.assets.precompile += your_files
to my development.rb file so that all the ckeditor files are precompiled when the application is loaded.
Although I tried a couple of paths, non worked and I keep getting the following error:
Can someone please tell me the right regular expresion to include all files for precompile, please?
I encountered the same problem and found a solution.Go to the following Link:
http://docs.cksource.com/CKEditor_3.x/Developers_Guide/Specifying_the_Editor_Path
<script type="text/javascript">
var CKEDITOR_BASEPATH = '/assets/ckeditor/';
</script>
<%= javascript_include_tag "application" %>
you don't need to set config.assets.precompile anything.
rails 3.2 fix:
in assets/javascripts/application.js
... blablabla ...
//= require ckeditor_fix #- add this line
//= require ckeditor/init
//= require_tree .
in assets/javascripts create new file ckeditor_fix.js
var CKEDITOR_BASEPATH = '/assets/ckeditor/';
I used this guide to add ckeditor to activeadmin in Rails 3.2 with the asset pipeline enabled:
https://github.com/gregbell/active_admin/wiki/CKEditor-integration
It worked like a charm.
The only additional thing I did was add this line to my environment:
config.assets.precompile += ['active_admin.css', 'active_admin.js', 'ckeditor/init.js']
Note that many of these answers refer to the ckeditor gem ( https://github.com/galetahub/ckeditor/ ), not just the ckeditor project ( http://ckeditor.com ) especially where you see reference to the ckeditor/init.js file.
There are other gems for ckeditor integration, including ckeditor-rails ( https://github.com/tsechingho/ckeditor-rails ) which is a lighter weight, simpler solution.
See also Integrating CKEditor with Rails 3.1 Asset Pipline
Finally an easy working solution.
Download the CKEditor Zip file, extract the files and place them in the sub directory “javascripts/ckeditor”, add the main JS file to the layout..
javascript_include_tag 'ckeditor/ckeditor.js'
..and write a bit JavaScript code which replaces textareas by CKEditor instances:
$(document).ready(function() {
if ($('textarea').length > 0) {
var data = $('textarea');
$.each(data, function(i) {
CKEDITOR.replace(data[i].id);
});
}
});
Credit Source
This is just an addition. I tried all this and it did not work for me so what i did was to change my ckeditor gem to gem 'ckeditor'
And added this to my application.js
//= require ckeditor/init
Then to precompile my assets, i added this to my production.rb file
config.assets.precompile += Ckeditor.assets
and it all worked like magic
STEP 1: Add gem 'paperclip' and gem "ckeditor" in your gemfile.
STEP 2: Bundle Install.
STEP 3: rails generate ckeditor:install --orm=active_record --backend=paperclip
STEP 4: Place config.autoload_paths += %W(#{config.root}/app/models/ckeditor) in application.rb
STEP 5: Place mount Ckeditor::Engine => "/ckeditor" if not present already and run db:migrate
STEP 6: Open application.html.erb and place this <%= javascript_include_tag 'ckeditor/ckeditor.js' %> in header.
STEP 7: Place this in footer(above the body tag) in application.html.erb
<script type="text/javascript">
$(document).ready(function() {
if ($('textarea').length > 0) {
var data = $('textarea');
$.each(data, function(i) {
CKEDITOR.replace(data[i].id);
});
}
});
</script>
STEP 8: Restart the WEBrick SERVER.
That's it.
There are many recent posts on this subject, but none of them (including defining the BASEPATH as suggested above) worked for me, so I thought this might be helpful to some people.
I solved the problem by copying the files from directory with the path
~/.rvm/gems/ruby-1.9.3x/gems/ckeditor-3.7.0.rc3 (the 'x' is app-specific, yours would be different)
to the directory /assets/javascript.
Then I was able to edit the configuration for the toolbar in the config.js file to make the editor have the options I wanted. This works perfectly for me since I always want the same options in this app.
UPDATE
I now have it working with the config.js file in the asset pipeline, where it belongs, but with the reset of the ckeditor code residing in my .rvm gemset. I think there was a conflict because I was trying to redefine their toolbar, named "Easy." When I made a new toolbar & set that one to be active, the pipeline seems to work fine.
ruby-on-rails-3.2 ckeditor
I had a similar while trying to combine multiple stylesheets and javascripts into one in a Rails 3.1 application without asset pipeline, using the stylesheet_link_tag and javascript_include_tag with the cache option. In this case the files are not always loaded in the correct order, and the paths to other ckeditor files like the configuration file "config.js" and language files like "lang/en.js" are not well defined. This means you will get other additional "NetworkError: 404 Not Found" errors while retrieving them, and the configuration and language files are not available, which causes futher fatal errors like the one mentioned above, Uncaught TypeError: Cannot read property 'options' of undefined.
Using a Javascript timeout did not help, and setting the CKEDITOR_BASEPATH did not help, either, at least if you define it in the application.js just before the editor is loaded as I did (maybe the order matters here?). To make it work it is possible to extract the ckeditor javascript from the common cached file (or take it out of the asset pipeline) and load it seperately after the rest of the files with
<%= javascript_include_tag 'ckeditor/ckeditor.js' %>
I fought with this issue for some hours, but the problem was not with CKEditor, but with my code. I included the ckeditor.js script inside my partial view which was rendered via AJAX and yes, you guessed it, wasn't working. Once I moved the script including inside the master layout (_Layout), the issue was solved. Of course, this happened to me while working in ASP.NET MVC. For other web frameworks, I have no solution.
The issue of ckeditor with rails 3.2 is javascript library path not loading for production environment so we need to modify path correctly.
I did following steps :
In application.html.erb
<%= javascript_include_tag "application" , '/assets/ckeditor/ckeditor.js', '/assets/ckeditor/init.js'%>
In production.rb file
config.assets.precompile += %w(ckeditor/init.js)
run assets
rake assets:precompile:all
These steps worked for me with rails version 3.2.8
Have similar issue. For me it was fixed by overriding default precompile task (I used Rails 4 and CkEditor 4).
Add to application.rb config.assets.precompile += ['ckeditor/*']
In application.js //= require ckeditor/init
Create file lib/tasks/precompile_hook and paste text from this answer Precompile hook

Rails 3.1 - How to separate CSS/JS between normal app and active_admin gem

My application is deployed on Rails 3.1 and on Heroku.
1. In production.rb, if I have config.assets.compile = true only then active_admin works. However, in production, I want config.assets.compile = false for normal application CSS and JS. The active admin module will be used only by administrator so it can be slow.
2. Moreover, since I installed active_admin gem my normal CSS has got terribly disturbed.
Hence, I want to somehow split the CSS and JS of active_admin and normal application so that:
1. Only when I hit localhost:3000/admin then CSS and JS of active admin hits and that of normal app does not. When I am on any other URL, then CSS and JS of normal app hits but active admin's does not.
2. I can config.assets.compile = false to normal app CSS and JS while make it config.assets.compile = true for active_admin alone.
Is this possible?
The good news is that you can have .compile set to false for both, and have both run fast!
Active admin uses its own manifests that start with 'active_admin'. By default these won't be precompiled by Rails.
To get them precompiled you need to add these files to the precompile array in production.rb:
config.assets.precompile += ['active_admin.js', 'active_admin.css']
This will create the files in the /assets folder and allow you to set .compile to false all the time.
Don't forget to also set:
config.assets.digest = true

How to set HTTP response (cache) headers in a Sinatra app hosted on Heroku

I have a fairly simple app (just one index.html file and a css file - it really is just a static page) hosted on Heroku.
I use Sinatra to host it on Heroku. The 'app' itself is fairly simple:
require 'rubygems'
require 'sinatra'
get "/" do
File.read(File.join('public', 'index.html'))
end
The question is, how do I set the HTTP response header for the static assets? In particular, I wanted to set the Expires header for caching purposes.
EDIT: I'm looking to add the said header to the static assets (ie, the one that resides under /public, like background images, icons, etc)
Apart from the fact that I wouldn't get through the Sinatra stack just to serve static files, you'd call
cache_control :public, max_age: 60
to cache for a minute. cache_control is a helper that comes with Sinatra.
Otherwise, I'd suggest you have a look at http://www.sinatrarb.com/configuration.html to see how Sinatra is set up so you don't have do deal with serving static files.
Hope this helps.
edit: I just saw you were explicitly asking for the Expires header. I'm not sure, but that should be fairly the same way as Cache-Control. Sorry for the confusion
As an expansion to #awendt's answer, Sinatra can actually handle static files with out needing to explicitly define the route and print the file.
By adding:
set :static, true
..you can add your index.html and stylesheet.css to a public/ folder. Then when you visit http://localhost:9292/stylesheet.css you'll be provided with the static file.
If you want to use another folder name, instead of the default public/, then try:
set :public, "your_folder_name"
If we want to be less explicit we can just create the public/ folder in the knowledge that Sinatra will enable :static for us anyway :)
Source: http://www.sinatrarb.com/configuration.html#__enabledisable_static_file_routes

Resources