dbconsole in Rails 3 requires the environment as the first argument
There is a bug in Rails 3's dbconsole
script, which makes the following command open a database console for the development
environment:
rails dbconsole -p test
You need to write this instead:
rails dbconsole test -p
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...
Rails 3.1.0 has been released!
jQuery as new default Javascript library, streaming response support, attr_accessible with roles, prepared statements, easier migrations.
Invoices: How to properly round and calculate totals
While it might seem trivial to implement an invoice that sums up items and shows net, gross and vat totals, it actually involves a lot of rules and caveats. It is very easy to create invoices where numbers don't add up and a few cents are missing. A missing cent is a big deal for an accountant, so it is important for your invoices to list correct numbers.
Note that this is not legal advice. Also note that while this note has a number of code examples in Ruby and MySQL, the concepts apply to all programming languages and data stores.
When ...
Always show all form errors during development
You've been there: A form cannot be submitted, but you don't see a validation error because the field at fault has no corresponding input field on the form. Because this is usually a bug, you insert debug information listing all errors into the form view. And once the bug is fixed, you forget to take out that debug information.
There is a better way. By copying one of the attached initializers into config/initializers
, your forms will always render a small box listing all form errors in the bottom right corner of the screen. This box is n...
Timecop creates records in the past after calling Timecop.freeze
This is a bug in Timecop 0.3.4 or lower. You should upgrade to 0.3.5.
An ActiveRecord is invalid, but has no errors
Did you return false
in a before_validation
callback?
Random list of ActiveSupport goodies
I recently browsed through the ActiveSupport code and found some nice stuff I did not know about:
ActiveSupport::Callbacks
-
ActiveRecord-like callbacks, if you need callbacks in non ActiveRecord objects
ActiveSupport::MessageEncryptor
-
encrypt and decrypt ruby objects
[ActiveSupport::MessageVerifier
](https://github.com/rails/rails/blob/mast...
Ruby GetText will eval scripts containing ActiveRecord classes
When the Ruby parser module of Ruby-GetText comes across a file in one of its search directories (e.g. lib/scripts/
) and finds out that you are defining ActiveRecord classes inside it, it evaluates the whole file. Here is how to avoid that.
What's happening?
Let's say you have the following script which is only run once, manually, via script/runner
:
# lib/scripts/doomsday.rb
class User < ActiveRecord::Base; end
User.destroy_all
In that case we ...
List sizes of MySQL databases
Do you wonder which databases are actually taking up how much space but only have one huge ibdata1
in your /var/lib/mysql
and the directories inside your mysql data directory don't represent the actual database sizes? This is for you!
Run from a mysql root console:
SELECT table_schema AS "Database name", SUM(data_length + index_length) / 1024 / 1024 AS "Size (MB)" FROM information_schema.TABLES GROUP BY table_schema;
This will get you a result like the following:
+----------------------+--------------+
| Database name ...
How to change the font in Sublime Text 2
Open up your "Base File.sublime-settings
" (Preferences Menu → File Settings – User) in Sublime Text 2. Add entries for font_face
, and optionally font_size
, so it looks similar to this:
{
"font_face": "Envy Code R",
"font_size": 11.5
}
Cool: when you save the configuration file, changes will be applied instantly.
Solve issues with Samsung TV as computer screen
We have a big flat screen TV (Samsung LE46c650l1kxxu) in our conference room. Configuring it properly, we were encountering some issues.
This is a list of issues, providing a solution to each.
No sound with DVI/HDMI and separate audio
There are some inputs on the side of the TV. These will not work for split video and audio.
On the back are more inputs you might not have seen. Choose HDMI/DVI as video in and Audio in for HDMI/DVI as audio in. Do not use RCA audio input but the [...
Create RAID on Amazon EC2 EBS volumes
If you use Amazon AWS cloud services you definitively want to utilize software raid for IO intensive stuff such as database data directories and the like.
Here's how you create it:
- Create some EBS volumes within management console or
sudo mdadm --create -f /dev/md0 --chunk=256 --level 10 --raid-devices 4 /dev/sdf /dev/sdg /dev/sdh /dev/sdi
- Create a fs on
/dev/md0
using mkfs*-tools - As soon as this is running, you should do that:
sudo mdadm --detail --scan >> /etc/mdadm/mdadm.conf
Make sure the last line in `/etc/mdadm/md...
Marry Date::Performance and Spreadsheet gems
Date::Performance is a gem that replaces various method in Ruby's Date
class with fast C implementations. Unfortunately it doesn't fully implement an internal method (Date.ajd_to_jd
) which makes your code blow up when you use it together with the Spreadsheet gem.
A solution is to restore the Ruby implementation of this particular method. To do this, copy the attached file to lib/fix_date_performance.rb
to config/initializers
.
How to: Store multiple Vim commands in macros and recall them
Vim allows recording a batch of commands as a macro. This is handy if you need to do the same things over and over.
Here is how:
- Press
q
to enter macro mode. - Press a letter (not a number!) key to assign a slot to your macro.
- You are now recording. Do whatever you want with usual commands.
- Once you are done, press
q
again to stop recording. - You can now run your recorded macro by pressing
@
and its assigned letter key.
Cheats:
- If you want to run a macro repeatedly, type a number before pressing the
@
key. Example: ...
Always store your Paperclip attachments in a separate folder per environment
tl;dr: Always have your attachment path start with :rails_root/storage/#{Rails.env}#{ENV['RAILS_TEST_NUMBER']}/
.
The directory where you save your Paperclip attachments should not look like this:
storage/photos/1/...
storage/photos/2/...
storage/photos/3/...
storage/attachments/1/...
storage/attachments/2/...
The problem with this is that multiple environments (at least development
and test
) will share the same directory structure. This will cause you pain eventually. Files will get overwritten and...
How to grep through the DOM using the Capybara API
When your Cucumber feature needs to browse the page HTML, and you are not sure how to express your query as a clever CSS or XPath expression, there is another way: You can use all
and find
to grep through the DOM and then perform your search in plain Ruby.
Here is an example for this technique:
Then /^I should see an image with the file...
How to look at hidden X screens
When you have a program running in a hidden X screen (like with Xvfb for Selenium tests) you may want to look at that hidden screen occasionally.
First, find out what X displays are currently active:
netstat -nlp | grep X11
This should give you some results like these:
unix 2 [ ACC ] STREAM LISTENING 8029600 4086/Xvfb /tmp/.X11-unix/X99
unix 2 [ ACC ] STREAM LISTENING 8616 - ...
A few hints when upgrading to Ruby 1.9
Note: If you are currently working with Ruby 1.8.7 or 1.9.3, we recommend to upgrade to Ruby 2.1 first. From our experience this upgrade is much smoother than the jump from 2.1 and 2.2, while still giving your the huge performance gains of Ruby 2. Also, if you're on Ruby 1.8.7, we recommend to skip a troublesome upgrade to 1.9.3 and go straight to 2.1.
When trying to make a Rails app run on Ruby 1.9, you're likely to encounter several issues. Here are a few solutions (obviously not exhaustive):
When running `bundle ...
Rails 3: Sending tempfiles for download
When you create a temporary file (e.g. to store a generated Excel sheet) and try to send it to the browser from a controller, it won't work by default. Take this controller action:
class FoosController < ApplicationController
def download
file = Tempfile.new('foo')
file.puts 'foo'
file.close
send_file file.path
end
end
Accessing this controller action will usually raise a 404 not found in the browser and the Apache log will say:
The given path was above the root path: xsendfile: ...
Virtual attributes for date fields
Note that this card is very old. You might want to use ActiveType for your auto-coerced virtual attributes instead.
We sometimes give our models virtual attributes for values that don't need to be stored permanently.
When such a virtual attribute should contain Date
values you might get unexpected behavior with forms, because every param is a string and you don't get the magic type casting that ...
Running the Awesome window manager within Gnome
Note: Consider using MATE instead of Gnome 3 on newer system
Awesome is a very good tiling window manager that provides neat features like automatic layouting of windows, good multi-display support with per display workspaces and more. Unfortunately, it is only a window manager, and lacks a lot of Gnome's conveniences like the network manager, application menus, automatic updates etc.
Fortunately, Gnome allows you to selectively replace only the win...
Show the status of a running dd copy
When you do a bitwise copy using the dd
tool you will not see any output until it completes or an error occurs.
However, you can send a command signal to the process to have it show its progress so far.
From another terminal, simply call (be root or use sudo
):
pkill -USR1 dd
This makes dd
write something like this into the terminal it is running in:
388+0 records in
387+0 records out
396288000 bytes (396 MB) copied, 24.9862s, 15.9 MB/s
You may also pass the status=progress
option to dd
like so:
dd if=... o...
Disable Dell U2410 beeping sound
The first thing to do with any new U2410 should be to disable the incredibly annoying beep when pressing any monitor button. Here is the fastest way to achieve that:
- OSD button (above the power button)
- Menu
- 2 × Up (You should be at “Other Settings” now)
- Right
- 4 × Up (“Button Sound”; the “Power Save Audio” entry is usually grayed out, so this is 1 beep less than from above.)
- Right
- Down
- Tick
Do it this way or your colleagues will stand at your desk after the 12th beep, ready to smack you.