In one of my Rails projects, I maintain a user-visible log of updates to the database by recording entries into a table that looks like this (from schema.rb):
Whenever a record is created, updated, or deleted, I create and save an instance of LogEntry, containing for example {:table => 'task', :action => 'update'} and in the 'changes' column I save a serialized hash showing which attributes of the task object changed before and after save. In addition, I save which logged-in user made these changes, and when.
This is convenient, it gives my client a log that's much more user-accessible and allows them to easily back-trace who did what to the database and when, which is important for their process and certain certifications.
When I upgraded the project to Rails 2.1 a couple of weeks ago, most of the code still worked fine, but the hashes showing the object changes were no longer showing up in views of the log. The culprit turned out to be Rails 2.1's new dirty feature. Why? Because it adds the method 'changes' to ActiveRecord::Base. This is a great new feature that lets you know what has changed to an ActiveRecord object since you loaded it from the database, with all kinds of benefits like doing more selective updates, or not writing to the database at all if no changes have occurred, thus reducing system load if you call save! a lot.
Unfortunately, the new method 'changes' was obscuring my attribute 'changes' in some circumstances, and at the very least confusing the heck out of me, the programmer.
The solution, of course, is not to name your fields anything that corresponds to any Ruby core method or any method of ActiveRecord::Base. I fixed my problem with a migration to rename the column 'details':
def self.up
rename_column :log_entries, :changes, :details
end
def self.down
rename_column :log_entries, :details, :changes
end
This morning we launched a refreshed site and an all-new online store for one of my clients, CordobaSzekely Productions.
Robert Cordoba and Deborah Székely are dance instructions and multiple-time national champions at the U.S. Open West Coast Swing Championships. They teach West Coast Swing and other dances all around the US and the world, and market a line of dance instructional DVDs.
Their former site had gotten a bit long in the tooth, so this was a just a quick refresher, keeping the former graphics design but bringing the HTML and CSS up to contemporary standards. Their online store was completely reimplemented using the open-source Zen Cart, where formerly they'd used the proprietary (and often difficult to use) Miva Merchant.
Sometimes you may want to generate a selector with a fixed set of options. In one recent task of mine, we needed a selector for an integer 1 through 10, but the client wanted them labeled also with text to identify how the numbers mapped to the words "High" "Medium" and "Low". (We were selecting the priority level of a task in a project management application). Essentially, I want to generate this HTML output:
These are fixed name/value pairs, so it made sense to me to store them as a constant hash in my Task model:
However, I was rather dismayed to discover that this didn't produce the results I wanted, because Ruby hashes (in Ruby 1.8.6) do not preserve order. This is what came out:
That's not what I wanted! I knew that select will also take arrays, but of course I needed separate name/value pairs, which I can't get with just straight arrays. I spent a while playing around with OrderedHash, which exists in Rails but is essentially undocumented and, as it turns out, does not support any useful functions of Hash like merge! and insert! that might make it easy to construct my list of options.
The Fix: Array of Arrays, or Array of Hashes
The documentation is not entirely clear on this, but if you send an array of 2-element arrays to select, rails will use the two elements of each inner array as if they were key and value pairs, and because the entire structure is an array it will preserve order. So, to get the results I wanted, I just need to change my constant to this:
As it turns out, the way ActionView processes the options is fairly general: if you pass it any enumerable object, it will iterate that object, and for each element will check to see if that element supports the methods :first and :last (and isn't a string). If so, it will generate an option with the text set to element.first and the value set to element.last. If it was a string, or didn't support first and last, both the text and value of the option are set to the element itself.
Testing it
Here's a handy function I use for testing it the presence of a selector. You pass it the name of your selector, the name of hash or array of options (in the any format supported by select), and optionally the value of an item that should be pre-selected, and it will assert the existence of each of those things. If you need to handle selectors with multiple selections, you can just wrap the last assertion in a loop.
Drop this in test/test_helper.rb
# Assert existence of form select input
# the
#
# or as an array like this:
# [ 'foo', 'bar' ] will be asserted to match
#
# first assert that the select tag exists
selector = { :tag => "select", :attributes => attributes }
assert_tag selector
option_values.each do | opt |
if !opt.is_a?(String) and opt.respond_to?(:first) and opt.respond_to?(:last)
assert_tag({:tag => "option", :attributes => { :value => opt.last },
:parent => selector, :content => opt.first })
else
assert_tag({:tag => "option", :attributes => { :value => opt },
:parent => selector, :content => opt })
end
end
# check for the pre-selected option, if any
if options[:selected]
assert_tag :tag => "option", :attributes => {:selected => 'selected',
:value => options[:selected] }
end
end
As an example of how to use it, here's my method for testing the task priority selector pictured above:
# asserts a
Where the array specified in the Task model looks like this:
It's a scourge that inflicts nearly every website: the dreaded empty page stating "Your search returned no results." Or even worse, the search results page with a header "Search results" and zero content, the footer immediately following the header. This is not only useless, but also confusing to the user, because it takes the reader several seconds to even realize that the search returned no results.
For example, I just got this one on the otherwise lovely workingwithrails.com when I searched for RoR developers in Pasadena, CA:
This is lame, lame, lame. A search results page with no results is guaranteed not to be useful to the user! From a user interface perspective, it's akin to redirecting a user to a login page after they try to access some resource, and then sending them back to the front page or a super-lame "thank you for logging in" page afterwards. The user should always see a useful page, and should never have to waste clicks getting back to what they wanted.
It's not only bad UI, it's also entirely unnecessary, because in Rails you can fix this for good with two lines of code.
Avoid wasted pages and annoyed users with redirect_to: back
If your user's search doesn't find anything, don't make them waste their time at a whole page that tells them only that. Instead just send them straight back to the search page. Better yet, redirect them back to wherever they came from, since they might well be able to invoke search from any number of different contexts in your application. You don't need a whole page to tell them the search didn't find anything - a flash notice is more than sufficient:
Redirecting back with a flash after an empty search:
def search
@results = YourModel.execute_some_search(params[:some_parameter]);
if @results.size == 0
flash[:notice] = "No items found matching '#{params[:some_parameter]}'"
redirect_to :back
end
end
Testing redirect_to :back
Testing redirect_to :back isn't completely trivial, because of course there's no previous page when you render a page in a test context. So, when you try to run a controller that redirects back, you'll see an error. The easiest thing to do is to artificially set a previous page. I have these two methods in test/test_helper.rb:
def fake_referer
@request.env['HTTP_REFERER'] = 'http://previous_page'
end
def assert_redirected_back
assert_redirected_to 'http://previous_page'
end
Then anytime I am working on a controller that involves back redirects, I drop fake_referrer in my setup method and then use assert_redirected_back. For example, in a search controller test (this is from a controller that has an action called 'contents' for searching items by text content - the search itself uses ferret):
def setup
super
fake_referer
end
def test_contents_search_fails
get :contents, :contents => "some&junk*that(will@never)match$anything"
assert_not_nil flash[:notice]
assert_redirected_back
end
I am excited about this, but perhaps not for the same reason most other people were. I am excited because Firefox 3 is the first version to implement the CSS rule "display: inline-block". Inline-block allows you to generate chunks of content of rectangular shape that will flow inline in your content (like text, images, or tables) but whose contents act like a block, and whose borders and margins are respected in the flow.
Let's make it clear what I mean.
The beauty and versatility of display: inline-block
Setting a CSS element's display: property to inline-block tells the browser to treat the element as a rectangular block, with internal flow just like any other block, and to respect the padding, border, and margins, but to flow that rectangle with other inline content - exactly the way the browser would flow an image. In addition, you can specify the width and height of inline-block items. This is a crazy useful concept from a layout perspective: it would allow you to make buttons out of text that lay out horizontally, or to layer images on top of each other inside a small span or div.
Here's an example of a series of list items set with border, padding, and a width and height. The code first:
Here's how Safari renders the above code (correctly):
And here's how Firefox 2 renders it (incorrectly):
Horrific - FF2 simply ignores inline-block, causing the list elements to render in their default display mode, block. What's galling about this is that for several years Firefox has been the only browser that gets it wrong! That's right, even Internet Explorer 6 gets this right ... at least on some elements, specifically those that are natively display: inline, like spans and anchors.
The Firefox bug report was filed way back in the days of Firefox 1 nine years ago. Yes, you read that right. It sat there, unfixed, while every other browser in the world implemented it.
Anyway, today web developers everywhere can rejoice. Now, at last, the released version of every major browser supports display: inline block. So, with only another year or two waiting while FF2 users upgrade to FF3, designers will be able to start using this singularly useful CSS rule (at least in cases where IE supports it as well).
A parting example
A parting example of the kind of cool trick you can play with inline-block: text flowing inside a sized box that is itself flowing inside text.
Code for flowing text inside flowing text:
<div style="font-size: 250%; width: 600px;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
<span style="width: 130px; height: 40px; font-size: 9px; display: inline-block;
padding: 1em; border: 1px solid black; overflow: hidden;">
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
dolore eu fugiat nulla pariatur.
</span>
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.
</div>
How it renders in a compliant browser ... including IE6!*
*Well, more or less. IE6 gets it reasonably close.
Apparently I can't stop playing, because today I built and uploaded a third design for the LRDesign main site: "Blue Art". This one required the IE PNG fix from Twin Helix for IE 6.0 compatibility.
I think there are still a few annoying bugs in the stylesheet switcher on IE; once I clean those up I plan to write a post explaining how to easily set up this kind of stylesheet switcher in a Rails project.
For quite a while I've wanted to decorate the main Logical Reality site with multiple, switchable themes, implementing each with pure CSS on top of semantic HTML markup, a la the CSS Zen Garden. Last night I finally got a start on that, implementing a simple stylesheet switcher and a grunge theme with textures from Urban Dirty.
To check it out, load the main site and click the "Change Skin" link in the upper left.
Looking for used cars on Craig's List, my girlfriend and I found what appears to be a classic web escrow auto scam: Web Auto Trades. An ad we responded to (a used Honda Accord at a surprisingly low price for the mileage) claimed to be using their service, which included a "five day guarantee" if you didn't like the car, and said we wouldn't have to meet the seller in person. These are all signs of a typical scam: buyer beware!
Other scam signs: though their snazzy flash-based website presents them as worldwide experts in escrow services, a google search for their domain name results in zero hits, and the domain has only been registered for five days and lists no telephone contacts:
Registrant:
Domain Privacy Group, Inc.
c/o webatrades.com,
5160 Yonge St. Suite 1800
Toronto, ON M2N 6L9
CA
Domain name: webatrades.com
Administrative Contact:
Domain Privacy Group, Inc. privacy-356772@domainprivacygroup.com
c/o webatrades.com,
5160 Yonge St. Suite 1800
Toronto, ON M2N 6L9
CA
Fax:
Technical Contact:
Domain Privacy Group, Inc. privacy-356772@domainprivacygroup.com
c/o webatrades.com,
5160 Yonge St. Suite 1800
Toronto, ON M2N 6L9
CA
Fax:
Registrar of Record: Netfirms Inc.
Record expires on 2009-05-21.
Record created on 2008-05-21.
Database last updated on 2008-05-28 12:54:04.
If you are finding this post because you googled their address after considering buying a car from someone using their service, I strongly consider you to avoid doing business with them, or at least to investigate the company much more thoroughly. Check with your state's attorney general's office to see if they've heard of them or have any complaints, and also consider checking with the BBB. Be very careful not to have your money taken by escrow scams, which this company gives every appearance of being.
Here's a screenshot of their front page, in case they pop up somewhere later under a different name.
Update: How to Avoid Escrow Fraud
Here are some useful links on escrow fraud, what it is, and how to avoid it:
Yesterday I switched the way permalinks are formatted on this blog, and apparently that hosed the feed URL, breaking my FeedBurner connection. I had to completely delete the feed and start a new one, so if you were subscribed before you will need to re-subscribe using the link on the right.
That link will take you to a feedburner page. If you were expecting a regular XML feed to subscribe in your browser, just click the "view feed xml" link in the box on the right of that page.
With the Insoshi social networking platform rapidly gaining in popularity, I thought it might be useful to folks to know how to install it on the ever-popular Dreamhost shared account. If you need a Dreamhost account, please consider using the promo code "LRDESIGN" when you sign up. It will save you $50 on your first year of membership, and will help me with my site hosting expenses so I can keep this blog going.
So, there are still some possible drawbacks to this approach, but I was able to get a running install of Insoshi on my Dreamhost account with this sequence. You might want to read to the bottom of this post to learn about the difficulties with acts_as_ferret and Dreamhost before you commit to running your insoshi site on DH. Hopefully these problems will have a solution soon, and I'll update this post if/when they do.
If you use this method and it works (or doesn't!) please let me know in comments.
1) Set up a domain
Use the DH control panel to create a new fully hosted domain for your Insoshi site, for example yourdomain.com or insoshi.yourdomain.com. I will use "insoshi.yourdomain.com" through the rest of this post to indicate the domain that you want to use to run insoshi. I set up http://insoshi.lrdesign.com/ in the process of writing this post, but I can't guarantee that it will stay up.
When you set up the domain:
Make sure that fastcgi support is selected.
Set "specify your web directory" to point to /home/username/insoshi.yourdomain.com/public/
2) Set up mysql databases
In the dreamhost panel, select "Goodies -> Manage MySQL"
Scroll down to "create a new mysql database"
I used these example settings:
database name: insoshi
use hostname: mysql.yourdomain.com (use "new hostname" to create this if you do not already have it)
New user: insoshi
New password:
If you want to run tests, you should create a second database called insoshi_test; you can leave the other settings the same.
3) Download the tarball of the current insoshi distribution:
cd
wget http://insoshi.com/home/tarball
You'll get a tarball with a name like "insoshi-insoshi-e1fd8b8e440c9f3ab34161d4e87de78e956c1012.tar.gz". Unzip the tarball and copy the contents to the directory you want the website to appear in:
tar xzf insoshi-insoshi-e1fd8b8e440c9f3ab34161d4e87de78e956c1012.tar.gz
cp -r insoshi-insoshi-e1fd8b8e440c9f3ab34161d4e87de78e956c1012/* insoshi.yourdomain.com/
4) Set up your database.yml file
cd ~/insoshi.yourdomain.com/config
cp database.example database.yml
Edit ~/insoshi.yourdomain.com/database.yml and make it look like the following, where is the password you chose in the previous step:
# Warning: The database defined as 'test' will be erased and
# re-generated from your development database when you run 'rake'.
# Do not set this db to the same as development or production.
test:
adapter: mysql
database: insoshi_test
username: insoshi
password:
host: mysql.lrdesign.com
port: 3306
This will migrate the database and do some insoshi-specific setup. It's also an excellent way to check that you've configured your database.yml correctly.
cd ~/insoshi.yourdomain.com
rake install
If it works, you should see a bunch of migrations (22 as of the current version of insoshi). If not, go back and figure out what's wrong with your database.yml file.
Generate a dummy rails app and copy the dispatch scripts to your insoshi install:
cd ~
rails dummy
cp dummy/public/dispatch.* insoshi.yourdomain.com/public/
Edit ~/insoshi.yourdomain.com/public/.htaccess file to enable fastCGI. Change the line with dispatch.cgi to look like this:
RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
change your permissions on the public and dispatch files:
cd ~/insoshi.yourdomai.com
chmod 755 public
chmod 755 public/dispatch.*
I also had to make my log files writeable:
chmod a+w log/
chmod a+w log/*
7) Start the ferret server
I was not able to get insoshi to run in production mode on Dreamhost at first
because in production mode it needs the ferret server (text search) to be
running or it will refuse to load some of the models. (In test and development
mode, acts_as_ferret will access the ferret databases directly, so this problem only appears in production). Based on this post, I found I could get it working by running:
script/ferret_server start -e production
At this point, I was able to load Insoshi in my browser.
Unfortunately, there are still some problems
I am pretty confident that the approach to running ferret_server above will not be a long term solution, because Dreamhost kills any processes that you leave running for more than a few hours. So ferret_server will go down after a while, and with it your site, so this will probably only get your insoshi site up for a few hours before you have to restart ferret_server. This basically means there's no good way to use the rails plugin acts_as_ferret on a DH shared account, and unfortunately Insoshi depends on AAF.
Possible Workarounds
You could try putting the startup command in a cron script, to restart ferret_server when Dreamhost kills it, for example:
0,15,30,45 * * * * cd ~/insoshi.yourdomain.com; script/ferret_server start -e production
would attempt to start the ferret server every fifteen minutes. But that might run afoul of Dreamhost server policies (does anyone know for sure?), and in any case your site would still be down in between the time DH killed the ferret_server process and your cron job started again.
You can also alter config/ferret_server.yml to have ferret treat production mode the same as development, directly accessing the ferret database and bypassing ferret_server entirely. However, if you get concurrent access with multiple users, you are very likely to get a corrupted ferret database with that approach.
Hopefully, some permanent solutions?
The Insoshi guys are working on replacing ferret with Sphinx, and that may be a permanent solution to this problem.
You also may want to consider lobbying Dreamhost to allow users run persistent processes like ferret_server. If you are a Dreamhost subscriber you can vote for this feature by following this link to Dreamhost's Policies Suggestions and voting for "Be able to run simple, persistent scripts!".