ActiveRecord with NOT NULL columns
Using ActiveRecord with an unchangeable legacy database schema poses some interesting challenges. Most of the work is a new style (for me) of composing adapters to make non-Rails stuff work within Rails' conventions.
ActiveRecord uses the database's native NULL to indicate an unset attribute [Ruby's nil]. This becomes a problem when the column definition enforces NOT NULL on columns that you may or may not be setting values.
Using Your Fixture Data in Development
So you've spent hours putting together some sensible data for your tests in a bunch of tediously crafted YAML files, and you're staring at a blank development database. If only there were an easy way to slip that data from the test database back into development . . .
Diagrams to Migrations using OmniGraffle
Once you go through the pain of setting up SQL Fairy (CPAN, yikes!), you can be designing your database visually with OmniGraffle in collaboration with other non-Railsy folks, and then generate your Ruby migration and stick it directly into your Rails project.
More Irb Tips
I was talking to someone (can't remember who) at Rubyconf and
they brought up #local_variable. This method shows
you the names of all the local variables in scope.
Funny, I don't remember this function, and if I did know it, I
had forgotten about it. So, I fired up irb and type
it in to see what I get back:
local_variables #=> ["_"]
x = 5 #=> 5
local_variables #=> ["_", "x"]
Hmmm, this is interesting. I know there is a variable in irb
that contains the value of the last expression, but it is not easy to
remember. But, it looks like _ will do the same thing.
I'm always doing math expressions where I need the value of the previous
expression. So now, instead of up-arrow and add to the equation, I can
use _.
5/7.0 #=> 0.714285714285714
2*_ #=> 1.42857142857143
Of course, you can you this for any irb expression, and best of all, it is a variable name I can actually remember. :)
Quieting irb's Return Value
It's easy to be overwhelmed by irb's automatic printing of return values, especially when dealing with collections of ActiveRecords in Rails' script/console.
Autovivification with Hashes
For you Perl folk, you may be familiar with the term autovivification. In essence, that is where an empty data structure gets automatically created if it is referenced, but does not exist.
For example, consider a hash. Let's say we want a two dimensional hash such that we can write:
1 2 |
points = Hash.new points[1][2] = 5 |
The problem here is that points[1] must return
a hash, and this hash is in turn accessed with the key '2'. It
would be the same thing if we wrote:
1 2 3 |
points = Hash.new tmp = points[1] tmp[2] = 5 |