09 Jul, 2007

Published at 11:29AM

Tagged with development, programming, rails, reflection, and ruby

This post has 0 comments

Code abstraction and Rails

Sometimes I have a hard time abstracting code when developing in Rails. I mean, the act of abstraction itself isn’t the problem, it’s how far to go with it—or more accurately, when to stop.

When I first started doing web development, I wasn’t too concerned with abstraction. I barely even knew what it was. Like most beginners, if I got something to work, I was satisfied… until I wanted to update something. It was an obvious pain to modify and update code, since I had to remember (or search) for all instances to stay consistent. Then (in addition to object-orientation), I realized that anything I was duplicating I should extract out so I could reuse it—brilliant! (It’s weird to think I was at a point where I didn’t think like that.) So I began to abstract only to prevent duplication. Now, with Rails, I can’t help but abstract everything. Ruby is so readable by nature, it’s stupidly tempting to want to continue that.

I enjoy immediately knowing what’s going on in any of my methods, just by reading them. Typically, I set them up that way. Sometimes, though, it seems like I’m tracing through all of these abstracted methods, and I don’t know if that’s a good thing. As an example, here’s a method I wrote to publish content out to XML:

1
2
3
4
5
6
def publish_xml_for(root_id)
  content = Content.find(root_id)
  create_publish_directory_for(content)
  output_xml_for(content)
  flag_as_published(content)
end

Anyone can look at that and know what’s going on. I’m not necessarily reusing any of those methods (yet, anyway), I just like how readable it is. But altogether, the publish_xml_for method works as a compilation of 5 or 6 methods (the methods inside of it are also abstracted to be very readable—it never ends).

Also, I find myself writing private methods within the controller class—would it be better to add these to some sort of extension in the lib directory? I don’t do that very often, so I have yet to build up habits as to when that should happen. I’ve written some tag extensions for polymorphic tagging, but that’s about it.

Comments

Do you have something to say about this post?
Retype the image to the right Spam Hint: Are You Human? Textile Formatting Tips

or

Ryan Heath | Site Management A Ruby on Rails production.

This site is a Formed Function. Formed Function LLC | @formedfunction | Get in Touch