July 2007
19 posts
depends
Sometimes in an app you need to do something in SQL and not in your app’s language. At t-bot we’re strictly MySql. And occasionally, MySql specific functions/syntax creeps into an app.
First its:
has_many :published_posts,
:conditions => 'published_on < now()'
From an app that allowed users to future date their posts.
Then its:
@post = Post.find :first,
...
render right
One extension to Rails ActionController::Base#render method I don’t like is the new :update parameter. This is used to render inline RJS in an action like:
class CommentsController < ApplicationController
def create
@comment = Comment.new params[:comment]
respond_to do |wants|
if @comment.save
wants.js do
render :update do |page|
...
It's the little things...
Sometimes it’s the little things that really make coding fun.
We used to use a common pattern that helped out with our view code. By adding the link_to_xxx
helpers, we could make our applications more consistent and maintainable:
def link_to_candidate(candidate, msg = nil)
link_to(msg || h(candidate.name), candidate_path(candidate))
end
def link_to_issue(issue, msg = nil)
link_to(msg...
1 tag
simplier restful
One of the biggest features in the latest version of Rails is RESTful routes.
By writing the following in your routes.rb file (assuming you have a UsersController):
ActionController::Routing::Routes.draw do |map|
map.resources :users
end
You get the following named routes for free (excluding named routes that include a :format extension):
GET /users #index
POST ...
Shoulda gets busy with your controllers
A while back we released the Shoulda Plugin to
help with testing your ActiveRecord models. Well, we’ve been using it in more and more
of our projects, and we’ve just finished adding some super cool controller tests.
Check it out!
Controller Macros
Right off the bat, you get some pretty little test helpers:
class UsersControllerTest < Test::Unit::TestCase
context "on GET to...
Disambiguate rails helpers
Here at thoughtbot we strive to make explicit, agile code. We know the specification changes, it’s what we’re machined for. The place that changes the most, and is usually the hardest to maintain are the views. As my comrade pointed out the views usually run wild, so we use helper methods to prevent a long method chain, and keep things a little more readable. Sometimes however that usually...
the more things change...
Recently, like everyone else, we’ve been putting some AJAX in our apps.
Now in Rails you have 2 ways to respond to AJAX requests:
Send HTML back to the client and let client side JavaScript (in the form of Rails helper methods) update the page with the response text. This can be done by rendering partials without layouts in your controller actions.
Send JavaScript back to the client...
when things happen
Recently in a Rails app, I ran into a strange bug.
In this app, we had users and articles. A User could write any number of Article s.
class User < ActiveRecord::Base
has_many :articles
end
class Article < ActiveRecord::Base
belongs_to :user
end
On a User’s personal page we show their recent articles. At first I implemented it using another #has_many like:
class...
against convention
In Rails we have these nice things we can use in our controllers called filters. A filter is simply a method that will get executed before, after or around the execution of a specific action in a controller. After looking at a bunch of different Rails apps, I never liked any of the names given to these filter methods.
For example:
class UsersController < ApplicationController
...
pure class
Specifying your domain model associations in Rails is all done in Ruby and looks nice.
Say in this app users can write reviews (it doesn’t matter what they’re reviewing, but we could say music):
class User < ActiveRecord::Base
has_many :reviews
end
class Review < ActiveRecord::Base
belongs_to :user
end
Now #has_many and #belongs_to are class methods available on...
intention
Now conditional logic asks questions, which sucks, but its always still in code (try to get rid of it though). In Ruby, we have the ability to use the ’?’ in method names e.g. #empty?, #has_key?, etc. I’m to the point now where I want to see a ’?’ method in every conditional.
I don’t want to see some condition like:
if group_membership.group_membership_type == 'Admin'
end
I want...
1 tag
The Legal Alternative
thoughtbot prides itself on exploring a variety of methods of boosting productivity. Recently we discovered an illegal substance at a nearby health food store, and almost all of us have at least sampled its effects. A few of us, however, have continued to consume it. In reality this few of us consists of only me. Join me as I go through the motions of writing, to take up enough space to...
what
Here’s one that might get you Rails developers:
class Comment < ActiveRecord::Base
def before_create
self.spam = false
end
end
Schema:
comments (id, spam)
The above model was in an app that allowed site administrators the ability to flag a Comment as spam. Naturally, this mapped to a boolean column in the comments table.
However, no Comment was ever being...
3 tags
ints or strings
Occasionally when developing an app you have to break out an enumeration. They usually take the form of some name ending in ‘type’ e.g. group type, event type, user type, etc. Now as far as the rules of normalization, I’m behind the fact that these enumerations should not be classes until someone wants to CRUD them. You also end up with brittle code, such as the following, when you prematurely...
a compromise
On a sidebar in the latest edition of Agile Web Development I noticed something. It was a description of a class query method in ActiveRecord::Base called abstract_class?. Just what I was looking for.
Previously, I complained about not being able to do real behavior-based inheritance (the way inheritance should be used) in Rails. To me Student and Teacher are not subclasses of Person...
muck focking
Most of the time in my tests I mock out all external resources, e.g. file systems, network I/O, databases, etc. I recently discovered the #fixture_file_upload method that’s available in Rails tests. File upload was one area I always mocked out because I didn’t even know how to do a file upload in a functional test. With this helper method you can do regular state-based testing with file...
any? != ! empty?
A common Ruby/Rails idiom used in views looks like the following:
<% if @posts.empty? -%>
<p>There are no posts.</p>
<% else -%>
<ul>
<%= render :partial => 'post', :collection => @posts -%>
</ul>
<% end -%>
Say that was from ’/posts’ or PostsController#index.
Alternatively, I’ve seen this:
<% if...
1 tag
Yes, We Heard You
I’m sure you’re aware of this already, but the dramatization of the novelization of this blog has been greenlit, produced, and opens TODAY. It’s been a long time coming, and we’re aware that some of our fans have been worried about artistic integrity. However, I think once you allow the movie to enter you, surround you, and ultimately bear you skyward, you’ll be just as excited as we are about...
no content for you!
Recently we had a feature request in an app: ‘show the login box on every page if you’re not logged in except the sign-up/registration page’.
Since the login box was going to be on just about every page we decided to put it in our application wide layout:
app/views/layouts/application.rhtml
<div id="wrapper">
<div id="sidebar">
<%= render :partial =>...