Close and Go BackBack to Viget

Ruby on Rails

Protip: Use Your Factories in Development

Clinton R. Nixon
Clinton R. Nixon, Senior Developer, August 17, 2008 1

I’ve been training a new Rails developer recently, and I’ve found it rewarding. His questions are great: without already-built habits, he thinks of ways to do things I never would.

Last week, he said, “I need to test this view with some real data to make sure it looks OK. We have all these factory methods to use in our unit tests. Can we use those in development?” I almost said no, but then I realized it was a pretty great idea.

We’re using FixtureReplacement on this project, but this technique will work with any factories. We opened script/console and typed the following:

require 'fixture_replacement'
include FixtureReplacement
require RAILS_ROOT + '/db/example_data'

With that, I could use, for example, our create_completed_order method to make a purchased cart with multiple items in it so we could see how the admin interface was looking. It’s no replacement for good testing, but for quick view checks, it’s a pretty cool trick.

Named Scope Caching

Brian Landau
Brian Landau, Web Developer, August 07, 2008 3

When working on high-traffic Rails sites, it often becomes necessary to find ways to improve performance with caching. One place we’ve found this is most convenient and easy-to-do is by caching an ActiveRecord result set for models that change rarely or not at all. An easy example of this is a Category model.

Often times, you have a categorization hierarchy that will never or rarely change over the life of an application. Ideally you would fetch the results once from the database and never have to again. So how do we go about caching this? First let’s look at our model and create a named_scope for it:

class Category < ActiveRecord::Base
  acts_as_tree
  named_scope :find_top_level, :conditions => 'categories.parent_id IS NULL',
                              :order      => 'categories.name'
end

Next, we need to create create a method that fetches the results for our new scope and caches it in a class variable. It should also only do caching if in production environment (alternatively or additionally, we could use the ActionController.perform_caching config value), as this can cause problems in tests.

def self.top_level
  unless ('production' == RAILS_ENV) && ActionController.perform_caching
    @@top_level_cache = self.find_top_level
  else
    @@top_level_cache ||= self.find_top_level
  end
end

Finally, we need to create a method to invalidate our cache when records are saved or deleted. Since we know this isn’t happening often (if at all), this should rarely be performed but is a good safeguard so we know our cache is current.

after_save :reset_cached_finder
after_destroy :reset_cached_finder

def reset_cached_finder
  @@top_level_cache = nil
end

This is something that we could easily see doing in a number of models for a number of finders. Since this involves a lot of similar code, it would be great if we could create some meta code that would allow us to define these caches with a simple one liner.

Continue reading "Named Scope Caching"

Helper Testing Independence

Brian Landau
Brian Landau, Web Developer, July 07, 2008 0

Testing helpers is a topic we’ve covered a couple times already here on the Viget Extend blog. I’ve additionally submitted a patch to Rails for adding some helper assertions to ActionView and other helper related testing goodness. But until that gets accepted and committed, I thought I’d hold everyone over with a helper testing plugin.

Independently Testing Helpers

The main tenet here is that helper functionality should be tested outside of another context (i.e. the controller). To achieve that, we need to create helper tests that live independent of our other tests. As Justin pointed out, Rails actually provides a class to assist in this, ActionView::TestCase.

The plugin I’ve created has two generators that help in creating these tests. The first, helper_tests, can be used to generate tests for your existing helpers. It creates a test file for each helper in the test/helpers directory and a test method for each public helper method. You can also pass it a list of helpers you wish to generate tests for and it will skip those that you don’t name.

Usage:

> script/generate helper_tests [SampleHelper Admin::AnotherHelper ...]

The other generator, helper, creates a helper -- and a helper test for the name provided. It will also accept a list of methods for the helper and generate them, as well as tests for each one.

Usage:

> script/generate helper HelperName [methods ...]

All generated helper tests will be run with rake test now along with all the other tests. Also a rake test:helpers task is provided to run just the helper tests.

Bonus Assertions!

That’s right ... I’ve also rolled in assert_tag_in, assert_tag_not_in, assert_select_in, assert_hpricot_in, and assert_hpricot_not_in assertions to the ActionView::TestCase class. These work exactly like their ActionController counterparts, except for the Hpricot ones, of course. These work by simply passing them the HTML string, and either a CSS selector or a XPath selector. The method then looks for an element matching the selector.

In the future, I’d like to spiffy assert_hpricot_in up by making it more like assert_select but it’s still useful to all Hpricot lovers out there as-is.

The Helper Me Test plugin:

The plugin is up on GitHub: http://github.com/vigetlabs/helper_me_test/tree/master

The clone URL to install with: git://github.com/vigetlabs/helper_me_test.git

As always comments, suggestions, or whatever are welcome, as well as forking it and adding your own twist.

Helpers vs. Partials - A Performance Question

Ben Scofield
Ben Scofield, Development Director, June 25, 2008 4

Have you ever looked in your development log and seen something like the following?

Processing FoosController#show (for ...) [GET]
  Session ID: BAh7CDoOcmV0dXJuX3R...
  SQL (0.000869) SHOW TABLES
  SQL (0.000931) SHOW TABLES
  Image Load (0.000465) SELECT images.* FROM ...
  [...]
Rendered entries/_detail (0.00221)
Rendered entries/_detail (0.00103)
Rendered entries/_detail (0.00118)
Rendered entries/_detail (0.00092)
Rendered entries/_detail (0.00107)
Rendered entries/_detail (0.00069)
Rendered entries/_detail (0.00215)
Rendered entries/_detail (0.00113)
Rendered entries/_detail (0.00113)
Rendered entries/_detail (0.00098)
Rendered entries/_detail (0.00098)
Rendered entries/_detail (0.00087)
Rendered entries/_detail (0.00079)
Rendered entries/_detail (0.00086)
Rendered entries/_detail (0.00079)
Rendered entries/_detail (0.00087)
Rendered entries/_detail (0.00076)
Rendered entries/_detail (0.00081)
Rendered shared/_nav (0.00207)
Rendered shared/_analytics (0.00011)
Rendered shared/_footer (0.00188)
Completed in 1.63867 (0 reqs/sec) | Rendering: 0.40653 (24%) ...

These sorts of entries in the log have always felt like a code smell to me - even when some sort of markup reuse is obviously necessary (so you can't just do it inline), I can't help but think that there's some significant cost to rendering the same file over and over again. So after a long time of thinking about it, I finally got around to doing some benchmarks comparing generating markup in a helper method, rendering a partial repeatedly for a collection, and rendering a partial with the :collection key. For each method, I use apache benchmark to hit a page 1000 times (with 2 simultaneous requests); each request generated 1000 divs like this:

<div>
  <span>index</span>
  <a href="#">link</a>
</div>

Here's what I found:

Method Time per Request    Requests/Second   
Helper 186.998 ms 10.70
Partial 438.244 ms 4.56
Partial for collection    266.068 ms 7.52

So it looks like there is a cost to rendering a partial repeatedly, but that cost can be reduced by using the :collection key, and reduced even further by generating the markup in a helper method. Of course, the helper method can be a smell of its own, but if performance is an issue it may be worth a look.

Note: This is an unscientific test, so feel free to respond with your own benchmarks.

Announcing the ActionButton Plugin

Brian Landau
Brian Landau, Web Developer, June 19, 2008 1

When creating web application there’s often a need for single links that have a destructive or “unsafe” effect. In accordance with HTTP specs, GET’s (e.g. links) should not be used for this. The issues that 37signals had with unsafe links prove the importance of this.

This is also important if your application is RESTful. Rails offers a few good solutions, but none of them are ideal. There’s link_to_remote, but this requires the user to have JavaScript enabled and doesn’t allow for progressive enhancement. Then there’s submit_to_remote, which requires you to wrap it in a form tag yourself and also doesn’t allow for progressive enhancement. Last, you have button_to, which is almost ideal, but it uses a submit button that offers less options for styling than a button tag.

And this is where the idea for a button tag helper came in. (See this blog post for a good description of why the button element rocks). Thus, ActionButton was born.

With it, you can create a form with a single button element. The form can be set to point to any url just as you would with a normal form. The button and the form can have different id and class attributes, making them easy to target via JavaScript. But you don’t need to set these; by default it will create classes and ids that are sensible. Of course, all the normal HTML options are available, too.

The plugin will also install a modified version of the lowpro library. The ujs_remote_form helper provided creates a snippet of lowpro JavaScript that can be used to make a form (or set of forms) submit via an AJAX call.

So how would I use this?

Well, if you have a list of blog posts in an admin section and you want to add delete buttons next to each of them and you want them to look the same in every browser, this is how you would do it.

<%= action_button 'delete_post', "#{image_tag('icons/delete.jpg', :alt => 'delete')} Delete", 
post_url(post), {:method => :delete, :number => post.id} %>

Then when you’re ready for some AJAXy goodness, you can either use the Rails built-in helper of the plugin’s lowpro one:

Built-in:

Add this for each post:

<%= observe_form "delete_post#{post.id}-form", :on => 'submit', 
:confim => 'Are you sure you wish to delete this post?' %>

Lowpro:

Add this for the whole page of posts:

<%= ujs_remote_form 'button.delete_post', :confirm => 'Are you sure you wish to delete this post' %>

So where do I get this plugin of button joy?

It’s up on github right now!

If you have any questions, comments or suggestions, send them my way. It’s great to get feedback, but if you really feel I messed something up, just fork it and make the changes you feel it needs.

A Development Community for Viget Labs and Beyond

Every team member here at Viget Labs strives to be an innovator. We members of the development team are no different - that's why we're constantly engaging in community discussions and exploring the unknown that is the next generation of open-source web applications.

Viget Is Hiring!

Viget has job openings for Ruby Developers, Interns, and Front-End Developers. Learn More »

Upcoming Events

Jack Speaks at WebExpo - September 16
Jack's Talking Agile Sept. 16-19

Recent Comments

I have used several different strategies for achieving this, and have settled on the plugin seed_fu to accomplish this task. Because it uses plain ruby files you have quite a few more options for manipulating your seed data as opposed to using fixtures. I have found that this lets me create seed data that is much less brittle than fixtures can be. You can find seed_fu on...