LRBlog

Logical Reality Design: Web Design and Software Development

RailsTutorial.org launched

December 14, 2009

rails-tutorial-logo-2The new Ruby on Rails Tutorial book and website by Michael Hartl has launched at RailsTutorial.org.   Hartl is the author of RailsSpace and cofounder of the Insoshi Ruby on Rails social networking platform.

Logical Reality did the logo and layout design work for Rails Tutorial.

 

Back up after hacking incident

October 16, 2009

This blog, along with a dozen or so other CMS-driven sites I maintain, was compromised by a hacker recently. I've finally gotten this one back up and am working on the others.

When ‘rake spec’ and ’spec spec’ produce different results

August 9, 2009

AKA adventures in class loading.

A couple of days ago I did some significant work in authorization in one of my apps, involving creating a Groups class with an HABTM relationship to Person, so I could assign roles to people a group at a time. It all worked out great, and I pushed the product to GitHub. The next day, my collaborator wrote in that my recent contribution broke 119 specs.

I pulled and retested the code, and everything worked perfectly. WTF? After a bit of investigation, I discovered that the specs worked great when I ran 'autotest' or 'spec spec', but that 119 specs broke when I ran the exact same spec suite with 'rake spec'! Double WTF.

Setting constants at class loading

Ultimately, I tracked the problem down to this line and method, in Person.rb:
class Person << ActiveRecord::Base
ADMIN_GROUP = Group.find_by_name('Admin')
def admin?
groups.include? ADMIN_GROUP
end
end

I consider a person an administrator if they are a member of this group, and I was loading it as a constant at the class level in order to avoid having to query the database again every time Person#admin? is called. This worked just fine for me, both in the application, and every time I ran Person#admin?.

But, remarkably, ADMIN_GROUP does not get initialized correctly when I run the tests via rake. I found this via the ruby debugger, running in this particular spec in spec/models/person_spec.rb:


describe Person do
it "should load an admin user from fixture" do
debugger
people(:admin).should be_admin
end
end

When I run the specs and evaluate Person::ADMIN_USER, I get very different results depending on which spec runner I'm using:

Running 'spec spec/models/person_spec.rb':


[11:17:54 CITAlumni]$ spec spec/models/person_spec.rb
spec/models/person_spec.rb:64
people(:admin).should be_admin
(rdb:1) eval Person::ADMIN_GROUP
#

Running 'rake spec SPEC=spec/models/person_spec.rb':


[11:17:13 CITAlumni (48c51f1...)]$ rake spec SPEC=spec/models/person_spec.rb
(in /Users/evan/Development/Ruby/CITAlumni)
FF.....spec/models/person_spec.rb:64
people(:admin).should be_admin
(rdb:1) eval Person::ADMIN_GROUP
nil

How very interesting ... when I use rake, that constant initializes to nil. At some point, I'll actually get around to figuring out why this is so different when the specs are run via rake. In the meantime, the fix was easy:

The Solution

The fix was just to refactor ADMIN_GROUP as a class method with a memoized instance variable. This will at least limit DB queries for the admin group to one per page load; not quite as good as a single DB hit when the class is first loaded, but still a major improvement over querying for the admin group every time Person#admin? is called. I moved it to the Group class at the same time, which was probably the right place for it in the first place:


#app/models/group.rb:
class Group < ActiveRecord::Base
def self.admin_group
@admin_group ||= self.find_by_name('Admin')
end
end

#app/models/person.rb
class Group < ActiveRecord::Base
def admin?
groups.include? Group.admin_group
end
end

And this worked just fine in all environments, solving the problem with 'rake spec'.

The Moral

Be careful with depending on behavior that occurs only during the loading of classes, as it can be environment-dependent!

If anyone out there with uber Ruby skills knows exactly why running specs via rake prevents that class variable from loading correctly, please enlighten us in comments!

Rails fixture strings that are all numbers

June 22, 2009

I ran into this one today: If you need to specify a string in a YAML file (fixtures or the like) but that string is all digits, put it in quotes.

The problem YAML file looked like this:

spec/fixtures/people.yml (broken)


one:
funky_database_id: 0000012345

two:
funky_database_id: 0000012346

The trouble with this is that yaml interprets those values as integers, not strings, and Person#funky_database_id is a string column. So Ruby conveniently loads the value as an integer and runs to_s on it before inserting. Worse, because these start with 0, they get translated from octal. So people(:one).funky_database_id comes out "5349". Definitely not what I wanted.

This works as expected:

spec/fixtures/people.yml (fixed)


one:
funky_database_id: "0000012345"

two:
funky_database_id: "0000012346"

New York Times article about UniThrive

June 13, 2009

One of my clients, UniThrive, was just written up in the New York Times. Go check it out!

An excerpt:

In the photo, the young person’s eyes are brown and kind-looking. She is in need of financial help. A new Web site that brings together the charitable minded and those in need has posted the details of her request.

This is not one of those arrangements where donors can sponsor a needy child or a sorghum farmer in the developing world. The person asking for help is a 21-year-old neurobiology major at Harvard, and she is requesting a loan from Harvard alumni.

Using link_to (or other helper methods) in a controller

May 6, 2009

This one was a big aggravator to me lately. I have one controller that needs to call link_to and url_for, which are normally helper methods you'd call from a view. However, in this case during certain modifications to a record, I actually need to append user-visible HTML links to a block of HTML stored in that object, or possibly another one.

Specifically, I needed to put annotations in the description of a work order object that said, for example "this work order was escalated from Problem Report 293. This was done in a create action that redirected at the end and never rendered a view, so I really did need to generate that link in the controller. And for consistency with the rest of the application, I wanted to generate the link with link_to(@task).

Now, ActionView::Helpers::UrlHelper is not loaded in a Rails controller, even if you've put helper :all in application.rb (application_controller.rb in newer versions). So, when I tried to use link_to in the controller, I got an error:

NoMethodError: undefined method `link_to' for #
/Users/evan/Development/Ruby/eclipticdb/app/helpers/tasks_helper.rb:64:in `task_link'
/Users/evan/Development/Ruby/eclipticdb/app/controllers/tasks_controller.rb:103:in `escalate'
... etc ...

The first fix - but with a problem

A year ago, I fixed this just by adding include ActionView::Helpers::UrlHelper at the top of that controller. This worked great ... for a while.

Lately, I've been rewriting this application into a RESTful style - it had previously been a controller/action style application. In the process, I started linking things with resource paths and polymorphic paths ... a lot of link_to @task and edit_polymorphic_path(@task) sorts of bits. And these started breaking. I began seeing this mysterious error:

Error:

You have a nil object when you didn't expect it!
The error occurred while evaluating nil.url_for

... some code here that calls a link_to ...

Trace of template inclusion: /tasks/_task_panel.html.erb, /tasks/_task_tabbed_panel.html.erb, /tasks/index.html.erb

RAILS_ROOT: /Users/evan/Development/Ruby/eclipticdb
Application Trace | Framework Trace | Full Trace

vendor/rails/actionpack/lib/action_view/helpers/url_helper.rb:71:in `send'
vendor/rails/actionpack/lib/action_view/helpers/url_helper.rb:71:in `url_for'

This one was a real bitch to debug, I have to say. The line in question that was failing in url_helper.rb said this: url = @controller.send(:url_for, options). Clearly, @controller was nil ... which was very bizarre, because I never interact with that instance variable anywhere.

I thrashed around trying to find the cause of this error for quite some time. Eventually I realized that the link_to method was only failing when called from a view in TasksController, and not from any other controller. And then I realized that TasksController was the one where, a year ago, I'd put include ActionView::Helpers::UrlHelper at the top. Somehow, including that helper in the controller was nullifying @controller when those helper method we called from within the view. I removed the include and my polymorphic and resource links all started working again.

Now back to the original problem!

Of course, that then left me back with the problem I'd had a year ago ... needing to use link_to from within the controller and having no way to do it. After a fair bit of googling around I found this post from Neeraj, which had an interesting approach -- but a commenter had suggested a much easier solution:

[sourcecode language='ror']self.class.helpers.link_to[/sourcecode]

I'm not certain where one would find this in the docs, but it does seem to have solved my problem for now. Onward and upward!

New Project Launch: UniThive.org

May 5, 2009

Where have I been the last few months?

Busy building and launching UniThrive.org!

UniThrive LogoUniThrive.org is a fantastic new non-profit startup that seeks to help reduce the cost of higher education by networking college students with alumni, and facilitating direct, zero-interest loans between alumni and students to defray tuition costs.

Technologically, UniThrive is a Rails application that began as a fork of the open-source social networking application Insoshi. Since forking Insoshi, we've nearly doubled the size of the code.

Today, UniThrive is in a live beta test available to students and alumni of Harvard University. Take a look, and check out the UniThrive Blog!

Single Table Inheritance and RESTful Routes

March 17, 2009

I'm converting an old, controller/action/id style Rails application to a more RESTful way of doing things, and ran into a brief roadblock: one of my main tables uses single table inheritance to generate three subclasses of items. I never actually use the superclass "task", I only use the three subclasses "action item", "work order", and "problem report".

So, I ran into this little challenge: all three STI subclasses use the same controller, "tasks", because they all have essentially the same behavior and differ only in minor details. But, when I do a resources map:

map.resources :tasks

Then I get errors in much of my code when I say things like redirect_to @task, because if that task happens to be an ActionItem, it's trying to call action_item_path(@task), which doesn't exist.

I googled around a bit to no result. Striking out on my own, it turns out the answer is as simple as mapping each resource independently, and just overriding the controller in map.resources:

In config/routes.rb

map.resources :tasks
map.resources :action_items, :controller => 'tasks'
map.resources :work_orders, :controller => 'tasks'
map.resources :problem_reports, :controller => 'tasks'

Now, redirect_to @task works just fine regardless of which subclass @task happens to be.

Bypassing mass assignment for update_attributes

March 14, 2009

I've been following this excellent post by M. Hartl and this post by E. Chapweske banishing mass assignment from one of my Rails applications due to launch soon.

I'm following Chapweske's approach of blocking mass assignment by default in all models, by putting this line in an initializer:

ActiveRecord::Base.send(:attr_accessible, nil)

This had the expected side effect of breaking several zillion tests, because tests frequently use things like Model.build() and Model.create!() to generate on-demand fixtures during testing. Hartl has a great bit of code that creates unsafe_build() and unsafe_create() methods in ActiveRecord. You can use these methods instead of build() and create() to function as expected in your tests.

This works great, except that I also use the mass-assignment method update_attributes! in my tests and specs frequently, particularly when I want to spec the effect a change on one model has on an associated models' methods. So, I expanded on Hartl's helper code a bit, to give myself the necessary methods. In case it helps anyone else:

/lib/initializers/unsafe_build_and_create.rb

class ActiveRecord::Base

# Build and create records unsafely, bypassing attr_accessible.
# These methods are especially useful in tests and in the console.

def self.unsafe_build(attrs)
record = new
record.unsafe_attributes = attrs
record
end

def self.unsafe_create(attrs)
record = unsafe_build(attrs)
record.save
record
end

def self.unsafe_create!(attrs)
unsafe_build(attrs).save!
end

def unsafe_update_attributes!(attrs)
self.unsafe_attributes = attrs
self.save!
end

def unsafe_update_attributes(attrs)
self.unsafe_attributes = attrs
self.save
end

def unsafe_attributes=(attrs)
attrs.each do |k, v|
send("#{k}=", v)
end
end
end

Don’t overwrite Rails’ built-in instance variables

February 13, 2009

So I'm hammering away at a project tonight, writing a few specifications for a module.  I've changed very little - or so I think - when five of my specifications start reporting this error:

NoMethodError in 'LoansController POST 'create' with valid parameters should succeed'
undefined method `env' for

This happens on the line where I call post :create in a controller spec.   Undefined method 'env'?   What's that about? I'm certainly not trying to call a method named "env".

It took me a little bit to figure out what was going on.  See, this series of tests needed access to a particular LoanRequest object I was pulling out of fixtures.   So I'd put above the tests:

before(:each) do
... some other stuff ...
@request = loan_requests(:johns_loan_request) # fetch fixture
end

Well, kids, it just so turns out that it's a bad idea to overwrite the @request instance variable in any rails context. Who knew?

Come to think of it, it would be nice to change the accessibility and/or mutability of Rails' basic instance variables and classes to prevent this kind of accidental overwrite by the programmer. Because when you make that mistake, it's invariably a bit of a pain to figure out because the error it causes is obscure.

Maybe I'll have to dig into the code one of these days to see if anything can be done about it.