Fix LoadError with Rails 3 applications on Passenger
After switching to Rails 3 you may get a LoadError
with the following message when trying to use your application via passenger:
no such file to load -- dispatcher
Your Passenger version is most likely out of date.
Update the gem, then install the apache module again:
sudo gem install passenger
sudo passenger-install-apache2-module
Follow any instructions. Update your /etc/apache2/httpd.conf
with the lines given at the end of the installation process to use the version you just installed.
Migrating to RSpec 2 from RSpec 1
You will need to upgrade to RSpec >= 2 and rspec-rails >= 2 for Rails 3. Here are some hints to get started:
- In RSpec 2 the executable is
rspec
, notspec
. - RSpec and rspec-rails have been completely refactored internally. All RSpec classes have been renamed from
Spec::Something
toRSpec::Something
. This also means that everyrequire 'spec/something'
must now berequire 'rspec/something'
. - In
spec_helper.rb
,Spec::Runner.configure
becomesRSpec.configure
- It has become really hard to extend specific example groups ...
Shell script to quickly switch Apache sites
I prefer the application that I'm currently working on to be reachable at http://localhost/
.
So when I switch to another project, I use this handy shell script to set one site as the current one. Call it just like this:
apache-site makandra-com
Note that it disables all other sites in your Apache configuration so you would not want to use this on production machines.
Furthermore it will also enable the default
site if that was available.
When you call apache-site
with no arguments, it will list all available sites.
...
On memoizing methods that return a scope
Be careful when memoizing a method that returns a scope, e.g.:
def variants
scoped(:conditions => { :name => name })
end
memoize :variants
Because of the way memoize
is implemented, that method now no longer returns a scope but its loaded target array.
The best solution is to use the Memoizer gem instead.
A workaround is to roll your own memoization:
def variants
@va...
Working around the ancestry gem's way of object destruction
The ancestry gem allows you to easily use tree structures in your Rails application.
There is one somewhat unobvious pitfall to it: its way of applying the orphan_strategy
which defines how it handles children of an object going to be destroyed.
What's this all about?
In many cases you might want to disallow destruction if there are any child nodes present. The restrict
strategy does the trick but raises an exception when destroy
is called:
has_ancestry :orphan_st...
Install the Nokogiri gem on Ubuntu servers
You need to install the following packages before you can build the Nokogiri gem:
sudo apt-get install libxml2-dev libxslt1-dev
Resolve Aspell errors with your Rails application
If you get an error message like that you are missing the Aspell files a specific language:
No word lists can be found for the language "de"
Solve it by installing the proper package, e.g. on Ubuntu:
sudo apt-get install aspell-de
apotonick's hooks at master - GitHub
Hooks lets you define hooks declaratively in your ruby class. You can add callbacks to your hook, which will be run as soon as you run the hook.
Even with bundler your gem order can be significant
Even when you're using bundler, it might be significant in which order your gems are listed in your Gemfile
. This can happen when gems are running around calling require
or require_dependency
on other gems or application classes when loaded (don't do that!).
A known culprit of this is the (otherwise wonderful) resource_controller gem, which requires ApplicationController
when loaded. When your ApplicationController
requires later-loaded gems when loaded, Rails will not boot.
He...
An obscure kernel feature to get more info about dying processes
This post will describe how I stumbled upon a code path in the Linux kernel which allows external programs to be launched when a core dump is about to happen. I provide a link to a short and ugly Ruby script which captures a faulting process, runs gdb to get a backtrace (and other information), captures the core dump, and then generates a notification email.
Inline if-then-else in MySQL queries
It can be useful to have a Ruby expression like condition ? positive_case : negative_case
in MySQL queries:
UPDATE users SET monthly_debit = IF(subscriber, 19, 0)
Precedence of Ruby operators
[ ] [ ]=
**
! ~ + -
* / %
+ -
>> <<
&
^ |
<= < > >=
<=> == === != =~ !~
&&
||
.. ...
? :
= %= { /= -= += |= &= >>= <<= *= &&= ||= **=
defined?
not
or and
if unless while until
begin/end
For more information see Table 18.4 in The Pragmatic Programmer's Guide.
Generate a strong secret from the shell
A good tool to generate strong passwords and secrets is "apg". You can get it with
sudo apt-get install apg
To create a strong secret for sessions, hashed Paperclip paths, etc. say
apg -m128 -a1 -E\'\"
Arguments explained:
- The
-m
parameter defines the secret length -
-a1
makes apg choose from all 7-bit ASCII characters instead of just the alphabet -
-E\'\"
excludes quote characters so you can easily paste the secret into a Ru...
jsmestad's pivotal-tracker at master - GitHub
Ruby gem that provides an AR-style interface for the Pivotal Tracker API.
Install the Paperclip gem on Ubuntu servers
You need to install the following packages before you can build the Paperclip gem:
sudo apt-get install imagemagick librmagick-ruby
Be careful with Array(...)
A popular ruby idiom I keep stumbling upon is
def do_some_thing_for(values)
values = Array(values)
values.each { ... }
end
The intent is to allow the user to pass in arrays as well as scalar values, since
Array("foo") == ["foo"]
Array(["foo", "bar"]) == ["foo", "bar"]
But Array()
actually calls to_a
on its arguments, which may not always do what you expect. For example
Array("foo \n bar") == ["foo \n", "bar"]
Save ActiveRecord models without callbacks or validations (in Rails 2 and Rails 3)
Rails 2
You can use
record.send(:update_without_callbacks)
or
record.send(:create_without_callbacks)
This can be used as a lightweight alternative to machinist's make
or FactoryGirl's create
, when you just need objects in the database but don't care about any callbacks or validations. Note that create_without_callbacks
does not return the object, so you might want to do
record = Record.new.tap(&:create_without_callbacks)
Rails 3
Rails 3 no longer comes with update_without_callbacks
or `crea...
Use Sass without Rails
You don't need a Rails application to use Sass. Even when you're working on a static site you can generate your CSS through Sass.
- Install Sass with
sudo gem install haml
- Create a folder
sass
in the folder, that stores your stylesheets, e.g.mkdir css/sass
- In a separate terminal window, run
sass --watch css/sass:css
. This will watch your sass files for changes and rewrite stylesheets as required.
This even works on Windows.
Note about your .gitignore
You might want to change our [typical .gitignor...
Security issues with hash conditions in Rails 2 and Rails 3
Find conditions for scopes can be given either as an array (:conditions => ['state = ?', 'draft']
) or a hash (:conditions => { 'state' => 'draft' }
). The later is nicer to read, but has horrible security implications in some versions of Ruby on Rails.
Affected versions
Version | Affected? | Remedy |
---|---|---|
2.3.18 | yes | Use chain_safely workaround |
3.0.20 | no | ... |
Run a rake task in all environments
Use like this:
power-rake db:migrate VERSION=20100913132321
By default the environments development
, test
, cucumber
and performance
are considered. The script will not run rake on a production
or staging
environment.
This script is part of our geordi gem on github.
Ruby: How to collect a Hash from an Array
There are many different methods that allow mapping an Array to a Hash in Ruby.
Array#to_h
with a block (Ruby 2.6+)
You can call an array with a block that is called with each element. The block must return a [key, value]
tuple.
This is useful if both the hash key and value can be derived from each array element:
users = User.all
user_names_by_id = users.to_h { |user| [user.id, user.name] }
{
1 => "Alice",
2 => "Bob"
}
Array#to_h
on an array of key/value tuples (Ruby 2.1+)
Converts an Array ...
Cheating Rails: Calling render() outside your Controllers
Do that for noble reasons only.
Rename hash keys
If you want to rename a key of a Ruby hash, this could help you out.
Just put it into something like config/initializers/hash_move.rb
.