Rails generators are underrated

Every experienced Rails developer should pick up Garrett Dimon’s Frictionless Generators. Generators are an often overlooked piece of the Rails puzzle. The book shines a light on getting the most out of generators in your Rails projects. It’s an amazing-looking digital object too, the illustrations are great.

(Before I go further, it’s worth noting that Garrett Dimon sent me a review copy, acted on my feedback, and is generally a pal.)

You should customize generators and write your own

Conventions, in the form of assumptions that are woven into the framework’s code but also exist as a contract of sorts, are essential to Rails. Following those conventions would not work well if creating a new model, resource, etc. wasn’t made easy and consistent without our friends rails generate resource/model/etc. These generators have been present in Rails since the beginning. I’ve used them hundreds of times and thought nothing of it.

A few years ago, I realized that generators had become a public API in Rails and that re-use was encouraged. The guide is a good start. I was able to knock out a simple generator for a novel, but conventional, part of our application. In the process, I realized a couple of things.

No one likes boilerplate and tedium. Generators automate the tedium of boilerplate. This is particularly helpful to less experienced developers, who are likely a bit overwhelmed with trying to comprehend decades of Rails evolution and legacy code (from their perspective) quickly.

Rails developers are under-utilizing this leverage. Every system that makes it past a few thousand lines of code (or several months in use) develops bespoke conventions. These are easier to follow if you can reduce the mental burden to “when you add a new thingy, run rails g thingy”. Added bonus: starting new conceptual pieces in your app from generators encourages consistency, itself an under-appreciated sustaining element in long-lived Rails applications.

Luckily, someone was thinking the same thing I was…

Garrett knows more about generators than anyone I know

The Rails guides for generators are okay. They whet the curiosity and appetite. But, they aren’t particularly deep. When I first tinkered with generators, I mostly learned by reading the code for rails generate model/resource/etc.

Frictionless Generators does not require one to jump right into reading code. It opens with ideas on the possibilities of developing with custom generators. Then, it moves onto the practicalities of writing one’s own generator and crafting a good developer experience. From there, it’s down the rabbit hole: learning about the APIs for defining generators, implementing the file-creation logic therein, writing help and documentation for them, generating files from templates, and customizing the built-in Rails generators.

Garrett goes into as much depth on generators as any other technical author I know, on any topic. Did you know you can make HTTP requests and use their responses in generators? I did not, but Garrett does! Did you know that generators apply the same kind of “oh, yeah, that’s common sense” convention for copying files from generators into applications? I did not, but Garrett does! I don’t think I’d use all these ideas on every generator, but I like the idea that I can return to Frictionless Generators should I have an idea and wonder how the existing, low-friction APIs can help me.

Further, Garrett offers frequent insights into the developer experience and leverage of building generators. On building generators for “fingertip feeling” so developers can easily (and frequently!) use them:

I like to aim for no more than one value argument and one collection argument to keep generators easier to use. Everything else becomes an option.

On approaching generators as high-leverage side-quests:

Remember that the ease of use is generally inversely proportional to the length of your documentation. Assistance first. Brevity second. Content third. Or, be helpful first, concise second, and thorough third. That said, there are a few other categories of information that can be helpful.


For me, a good technical book balances presentation of technical information, the right amount of detail, and wisdom on how to apply the two in practical ways. Garrett succeeds at striking that balance while keeping things moving and easy to follow.

In short, recommended! Rails generators are underrated, whether you’re aware of their existence or not. Smart teams are customizing generators and writing their own bespoke generators. There’s a book on this now, which you should check out if any of this resonated.


Rails generators reminders

First: use them! Most frameworks have a project boilerplate and that’s it. Rails’ ability to quickly lay down a conventional resource, model, or anything else is a productivity booster. Use it!

Second: experiment with the commands before you run them. Try Harrison Broadbent’s, RAILSG · Ruby on Rails Generator Reference and Command Builder:

RAILSG is a collection of Ruby on Rails generator command references, and command builders.

Third, write your own. When your app gets traction, you’ll probably invent a couple of conventions of your own. Use generators to quickly write new code consistently. Garrett Dimon has become the expert on this, Creating Custom Rails Generators:

Rails generators can help remove significant friction from the process of spinning up new ideas, but you don’t have to limit yourself to the included generators. You can also create custom generators as long as you’re familiar with the available APIs and know where the speed bumps are.

And check out his forthcoming book on the same topic!


Err the Blog, revisited

Before there was GitHub, there was Err the Blog. Chris Wanstrath and PJ Hyett wrote one of the essential Rails blogs of early Rails era. Therein, many of the idioms and ideas we use to build Rails apps today were documented or born.

I’d figured this site was offline, as are most things from the mid-2000s. ‘Lo and behold, it’s still online in its pink-and-black glory. Lots of nostalgia on my part here.


Bundler, not as bad as they say

Of all the new moving parts in Rails 3, the one I see the most grousing over is Bundler. This is not surprising, as its a big part of how your application works and it's right up front in the process of porting or building Rails 3 apps.Bundler: As Simple as What You Did Before:

Bundler has a lot of advanced features, and it’s definitely possible to model fairly complex workflows. However, we designed the simple case to be extremely simple, and to usually be even less work than what you did before. The problem often comes when trying to handle a slightly off-the-path problem, and using a much more complex solution than you need to. This can make everything much more complicated than it needs to be.

I haven't run into anything with Bundler that I couldn't solve with a little critical thinking and maybe a little searching. On the other hand, Bundler has made getting dependencies straight amongst team members and deploying them to production servers far easier than it was before. I'm very glad that while it's not strictly part of the scope of Rails, that Bundler is now part of it.


Using Rails 3.0's notification system

How to use Rails 3.0's new notification system to inject custom log events. Ever wondered what the notification/subscription stuff in Rails 3 is? Wonder no more! I just used this to add performance logging around some Cassandra stuff in our Rails 3 app. Once you get the hang of it, this is really rad stuff.


Rails' Next Top Model

Of all the new and reimagined code in Rails 3, ActiveModel and ActiveRelation rank amongst what I find the most interesting. I’m excited that they potentially lower the bar to implementing one’s own data layer. If you’ve got some custom backend or datastore, writing a nice API around it has previously been quite the endeavor. To get it working is one thing; to make it as pleasant to use for application programmers is another thing entirely. ActiveModel and ActiveRelation have been extracted from ActiveRecord and make the task of building one’s own model layer far easier.

My presentation for RailsConf 2010 focused on what ActiveModel and ActiveRelation provide and how one can use it to write cleaner code in domain models, how to make your models feel more like ActiveRecord objects, and how to use ActiveRelation to build your own persistence layers.

I hope you find the slides educational. Further, I’ve posted the examples on GitHub so you can play along at home. If you’re particularly interested in ActiveRelation, I hope you’ll find the examples useful as a starting point to using that library.


Ogres and APIs

Bringing Merb’s provides/display into Rails 3:

The symmetry relates to another point in API design that I've been interested in lately: progressive expansion. There should be a smooth path from the simple case to the complex case. It should be like an Ogre, it should have layers.

I Heart Complexity

Like I said, I think the market for simple applications is probably saturated and now is the time for Ruby and Rails to go up-market and tackle bigger problems. We’re well equipped to do that, having learned from what sorts of simplicity help reduce tricky problems to tractable problems.

IHeartComplexity.jpg

In my RailsConf Europe 2008 presentation, I play the role of the messenger. I’m not bringing any new science that makes building more involved applications easier. Instead, I’m trying to tie it together into an understandable package. You take the gems described herein (money, acts_as_state_machine and acts_as_versioned) and a couple concepts (domain driven design and queueing) and you can build some really cool applications that solve pretty tricky problems. To me, that’s big fun.

You can check the presentation out on Slideshare or grab the PDF. Also, make sure to check out the code on GitHub. Enjoy!


Refactoring to more code

Refactor my code is a neat site where you can post your code and watch others refactor it. I saw an interesting bit of code whiz past and thought I’d take a crack at it.

Removing conditionals from code is one of the little games I sometimes play while coding. Here, I’ve extracted the logic of the conditional into another class. The resulting class is much more code than the original. So why do that?

Well, I say you get a few benefits:

  • The logic is now far easier to test. It’s a standalone object now rather than a Rails functional test.
  • The flow of what’s being done and tested is more decomposed and easier to follow.
  • Most importantly, the code explains itself. No need for comments (which will undoubtedly go out of sync over time) here!

While I delight in deleting code and writing as little as possible, refactoring this to more code seems the right way. What say you?

Update: Make sure you check out Marcel Molina’s refactoring. Its probably better than mine ;)


Fake Rails environment

For testing some bits inside of ActiveRecord proper.

module Rails
  def self.env
    o = Class.new do
      def production?
        true
      end
    end
    o.new
  end
end

Evil and fun. Uses Class.new, my favorite Ruby method.

Muahahaha.


See me at RailsConf '08

As hordes of Ruby and Rails folks begin the annual migration to Portland for RailsConf, I thought I’d let you know how to find me there this year:

That rounds out the conference activities. But I’d be remiss if I didn’t inform you that FiveRuns would like to buy you a drink or two Friday night at Jimmy Maks from 6 to 8 PM. Please to be joining me there!

What I am perhaps most excited about is the RailsEnvy videos that will premiere this weekend. You see, Jason and Gregg were kind enough to invite me to join them in making the funnies this year. Making them was a blast! I’ve seen the finished product and, in my completely biased opinion, I think you’re going to like it.


Of course, I’d love to chat with you (yes, you) at any point in the conference. So if you see me (and I will probably stand out), come say “Hi!” I’m hoping to have something interesting for those that do…


More fu in your versions

Lazily Announcing version_fu - an update of Rick Olson’s acts_as_versioned that works with dirty attributes. Jordan McKible’s plugin is nascent, but since I have a soft spot in my heart for most things data versioning, I thought I’d point it out.


Rails Scenarios

Rails Scenarios - a sane way to specify really complex fixtures in Rails. Lets you write classes to specify data and helpers to operate on that data. There’s a sane way to compose data and create relationships, as well as support for test/unit and RSpec. Personally, I’m currently in a not-unhappy place with YAML fixtures, but if you aren’t, this is worth a look.


I Like Rails 2

Tonight I gave a presentation on Rails 2 at Dallas.rb. Within, I note some of my favorite new things in Rails 2. Some things small, some things large.

ILikeRails2.jpg

If you weren’t there, I should probably explain a couple of the slides. I think Rails 2 is, despite its whole-numberness, an evolutionary release. It makes the Rails “language” smoother around the edges. Granted, its still somewhat blob-esque, but its getter rounder. I dig it.

Besides that, I think Active Resource, or ARes as they call it in the biz, is going to prove useful mostly behind the firewall in your datacenter. As you build more and more applications, you’ll find you need to use resources across multiple apps. This is exactly where ARes shines – providing a common user service, for example.

You can dowload I Like Rails 2 it if you missed it or, for some reason I can’t even fathom, aren’t even in Dallas.