Limiting CPU and memory resources of Paperclip convert jobs
If you're using Paperclip to store and convert images attached to your models, processing a lot of images will probably cause headache for your system operation colleagues because CPU and/or memory peaking.
If you're on Unix you can use nice to tell the Kernel scheduler to prefer other processes that request CPU cycles. Keep in mind that this will not help if you're running into memory or IO trouble because you saved some bucks when you ordered (slow) harddrives.
ImageMagick (the tool which is used by Paperclip to do all that funky ima...
Fix AssociationTypeMismatch
When you're getting this error, one possibility is that you've created a select field for an association instead of the associated object's id. Example:
form.select :unit, Unit.for_select
will be expected to deliver a real Unit object, whereas
form.select :unit_id, Unit.for_select
will make Rails typecast the String value from the select field to the unit's ID.
How to deal with MethodNotAllowed errors
One of the most common production errors are ActionController::MethodNotAllowed errors. They usually happen when someone reloads a form by pressing enter/return in the URL field, or by opening JavaScript links incorrectly.
The attached initializer provides a default way to deal with this.
You'll get the following behaviour:
- if the incorrect request has a
HTTP_REFERERcoming from the same application, set a flash, and redirect back - if the incorrect request has no
HTTP_REFERERor one coming from an external source, set a flash...
Re-enable submit buttons disabled by the :disable_with option
Submit buttons in Rails come with a useful option :disable_with which will disable the button when clicked and change its label to something like "Please wait...".
An annoying side effect of that feature is that when you use the back button to return to the form, the submit button will be greyed out and disabled.
A solution is to re-enable the submit button before leaving the page. This works in Rails 3:
$(window).unload(function() {
$.rails.enableFormElements($($.rails.formSubmitSelector));
});
ERB templates and comments
When you use one line Ruby comments in ERB templates you should never do this (notice the whitespace in front of #):
<% # my comment %>
<div>my html</div>
This leads to strange html output. To avoid long debugging sessions, you should never have a whitespace before the # character (but newline is allowed)
<%# this works as expected %>
<%
# this works, too
# foo bar baz
%>
Git instaweb
Git has a built-in repository viewer for your web browser. a bit similar (but less awesome) than github.
If you have apache installed, simply go to your repository, and enter
git instaweb --httpd apache2
otherwise, simply install lighttpd and just run
git instaweb
This should open a brower automatically pointing to your repository. If not, try to connect to localhost:1234.
You can stop the server with
git instaweb --stop
How to define a custom context menu within HTML (Firefox 8+)
Since Firefox 8 it is possible to define custom context menus (right clicking) with HTML markup.
Declare different CSS background-images for different locales
If you would like to use language specific layout (e.g. background-images) in your applications stylesheets you can achieve this easily by using the lang attribute in your views (ERB):
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<%= I18n.locale || 'en' %>" lang="<%= I18n.locale || 'en'%>">
...
</html>
or in HAML:
%html :xmlns => "http://www.w3.org/1999/xhtml", :"xml:lang" => I18n.locale || 'en', :lang => I18n.locale || 'en'
Then, in your stylesheet you can for example declare different background-images fo...
Login forms: Disable browser prompt to remember the password
In order to prevent the browser from asking whether to remember the password, give a form an autocomplete attribute with the value off:
<form "/session" method="post" autocomplete="off">
...
</form>
Rails example
form_for @model, :html => { :autocomplete => "off" } do |form|
Large forms are slow on the iPad
- Forms with many inputs (600+ in my case) become extremely unresponsive on an iPad, up to the point where it can take several seconds for a control to respond to touch commands.
- This is true for both iPad 1 and iPad 2 models.
- While certain CSS styles can lead to performance issues, removing those styles won't help if the form simply is very large.
- A workaround is to only show a limited number of form inputs at the time, e. g. by toggling groups of form...
Multi-line Ruby block in Haml
There are several options, but most of them are impractical. The best way is to use the :ruby filter:
:ruby
puts javascript_include_tag(
'lib/jquery-1.6.1.min.js',
'lib/jquery-rails-ujs.js',
'lib/jquery-ui-1.8.13.custom.min.js',
'lib/jquery.ui.datepicker-de.js',
'lib/jquery-ui-timepicker-addon.min.js',
'lib/jquery.tools.min.js',
'application.js',
'google-maps.js',
:cache => true
)
...
Improve web font rendering in Windows by autohinting fonts
Web fonts are awesome. After being restricted to Arial for two decades there is finally a cross-browser way to embed fonts into web pages.
Unfortunately while web fonts look awesome on Linux and MacOS, they look horrible on Windows, a problem that gets worse with smaller font sizes.
The culprit is something called font hinting:
...
How to use html_safe correctly
By default, Rails views escape HTML in any strings you insert. If you want to insert HTML verbatim, you need to call #html_safe. However, #html_safe does not "unescape" a string. It merely marks a string as safe for unescaped insertion.
How html_safe works
Calling html_safe on a String returns a new object that looks and acts like a String, but actually is a ActiveSupport::SafeBuffer:
"foo".length
# => 3
"foo".class
# => String
"foo".html_safe.length
# => 3
"foo".html_safe.class
# => ActiveSupport::S...
Micro clearfix mixin for Sass
Clearfix is a hack to clear floating elements without additional HTML markup.
If you only need to support IE8 and above, a great clearfix with few side effects is:
=clearfix
&:after
content: ""
display: block
clear: both
This is a Sass mixin.
Issues clearing with display: table
You will find many clearfix solutions that clear with display: table instead:
=clearfix
&:after
content: ""
display: table
clear: both
The problem with th...
Stub methods on any instance of a class in Rspec 1 and Rspec 2
RSpec 1 (Rails 2)
With the most recent spec_candy.rb helpers you can say:
User.stub_any_instance(:foo => :bar)
user = User.new
user.foo
# => :bar
RSpec 2 (Rails 3)
RSpec 2 comes with this feature built in:
User.any_instance.stub(:foo => :bar)
user = User.new
user.foo
# => :bar
RSpec 3
-------...
Fix multiple CKEditor instances using jQuery adapter - fixed since 4.2
Using the jQuery adapter breaks the built-in save function of CKEditor.
Phenomenon: The page is submitted correctly, but the original values of the form fields were posted instead of what was typed in the editors.
Work around: Basicly instead of initiating the editor using the above example I ended up using the following:
$( 'textarea.editor').each( function() {
CKEDITOR.replace( $(this).attr('id') );
});
Note: This assumes that each field using the editor has its own unique ID.
How to change the order of nested forms being rendered (especially blank forms)
Generally for nested forms, a blank form is placed below all other existing object forms. If you would like to change the position of the blank form(s) you can reorder the object's one-to-many association. For example you can put the blank form on top with the following snippet:
actors = movie.actors
actors.build
actors.unshift(actors.pop(1)) # won't work with Rails 4+
Because build_for_form creates new objects and ap...
Making the rails 3.1. asset pipeline and asset precompiling work in production mode
Recently, we had an interesting lunch-break with the rails 3.1. asset-pipeline in production mode. Daniel Zahn made a blogpost about our journey, precompiling assets, fingerprinting, Haml, Sass & Compass and what he calls "the dark heinous hutch".
Test that a form field has an error with Cucumber and Capybara
You can use the step definition below to say this:
Then the "Last name" field should have an error
Capybara
Then /^the "([^\"]*)" field should( not)? have an error$/ do |field, negate|
expectation = negate ? :should_not : :should
page.send(expectation, have_css('.field_with_errors', :text => field))
end
Using heredoc for prettier Ruby code
You can use heredoc to avoid endlessly long lines of code that nobody can read. Heredoc strings preserve linebreaks and can be used like this:
def long_message
puts(<<-EOT)
Here goes a very long message...
Sincerely,
foobear
EOT
end
<<-EOT will be somewhat of a placeholder: anything you write in the line after you used it will be its value until you write EOT in a single line.
You can use any string to flag your heredocs. To be more verbose you...
Rendering a custom 404 page in Rails 2
Simple: Tell the application controller how to handle exceptions, here a RecordNotFound error.
Do this with the following line:
# application_controller.rb
rescue_from ActiveRecord::RecordNotFound, :with => :render_404
This will call the method render_404 whenever a RecordNotFound error occurs (you could pass a lambda instead of a symbol, too).
Now write this method:
def render_404
render 'errors/404', :status => '404'
end
Finally create a 404 document views/errors/errors.html.haml.
%h1 Record...
Let a Rails 3 application make a request to itself
Ever wondered how Rails talks to itself in a Cucumber feature? In Rails 3 you can do it like this:
def rack_env(path)
{ "rack.input" => {},
"PATH_INFO"=>"#{path}",
"REQUEST_METHOD"=>"GET" }
end
request = rack_env('/users/new')
response = Rails.application.call(request)
status, headers, body = response
puts status # e.g. 200
puts headers.inspect # hash of headers
puts body.body # html of response body
Instead of Rails.application you can also call any Rack application.
When Rails no longer renders changes in view templates or Sass stylesheets
Do you have page caching enabled for the development environment and there are cached pages lying around in public/?
Fix: "undefined method `bytesize' for #<Array>"
I believe that when WEBrick has trouble bringing up your Rails application, the WEBrick component that is supposed to print you a pretty error message has a bug and sometimes fails with this message:
"undefined method `bytesize' for #<Array>"
Starting the application in Passenger gave me a stacktrace in log/development.log that pointed to the actual problem.
Possible causes discovered by looking at the logs
-----------------------------------------------------...