Domain Driven Design: Building Blocks in Ruby
A few weeks ago I talked about Domain Driven Design in Ruby at the local Ruby user group: Rotterdam.rb. It had a great turnup (even though the weather prevented some from coming) and there was a good discussion going on. Thank you for that! Follow @rotterdamrb to hear about future meetups with free beer and pizza, sponsored by Finalist IT Group!
It was a long talk, so I couldn’t cover all the topics I wanted to cover. I talked about ubiquitous language, bounded contexts, core and support domains, and showed some ways to do this in Ruby, using modules. Basically, I concentrated on techniques to organize essential complexity, while keeping an eye on practical usage with Ruby and Rails.
When you talk about Domain Driven Design, you hardly cannot do that without mentioning the three types of objects that Eric Evans discusses in his book. It’s Entity objects, Value objects and Service objects. Still I managed to do just that. Time to fix it; here is what I failed to mention.
Entities
Entity objects are objects that represent something in the real world and can be referenced as such. Translated into Rails terms these would be instances of (most of) your models. You can reference a post instance by getting it via its id from the database.
These objects are prime candidates for using plugins like friendly_id, making the fact that these objects have a real identity in real life clearer. This is because you can now reference them by name, instead of some database id. To use friendly_id with Rails 3, point your gemfile to the ‘edge’ branch on github.
Value Objects
Objects that don’t have any real identity are called “Value objects”. Any object that is a value object has no real identity, nor is it important to know its identity.
Addresses are a good example. The value of the address (e.g. street, house number, city, country) is important. But it’s less obvious to store this in a database and reference it by an id. This id would be purely superficial and have no meaning in the domain you are designing.
A pure Ruby way to do this with Structs, which I have mentioned before on this blog. If you’re using a document based database, like MongoDB, these would obviously be embedded documents. With ActiveRecord you can use the composed_of-method. Allow me to demonstrate that:
# Attributes of Person include: # # * first_name string # * name_infix string # * last_name string # * male boolean # class Person < ActiveRecord::Base composed_of :name, :mapping => Name.members composed_of :gender, :mapping => Gender.members end
class Name < Struct.new(:first_name, :name_infix, :last_name, :gender)
def to_s
[ first_name, name_infix, last_name ].select(&:present?).join(' ')
end
def first_name
super.presence || title
end
def title
I18n.t(gender.key, :scope => :titles)
end
end
class Gender < Struct.new(:male) def to_s I18n.t(key, :scope => :genders) end def key male ? :male : :female end end
By defining to_s on these structs you can output their gender or name in views without doing anything special:
%dl[@person] %dt= Person.human_attribute_name(:name) %dd= @person.name %dt= Person.human_attribute_name(:gender) %dd= @person.gender
In this example, Person is actually an aggregate of the entity Person and two value objects, called Name and Gender. Although all attributes are flattened out in your persistence layer (in this case, your database table); they do have a deeper structure in your code. And it’s easier to test too!
Services
Things that aren’t really a ‘thing’ in the domain you’re designing are usually services. They are not really part of any entity or value object, but do something with them.
In Rails, these would be observers or plain Ruby objects lying around. Maybe it’s time to call them what they are and place them in app/services.
Every Rails developer knows the pattern “Fat Model, Skinny Controller”. This is a pattern to remember that you shouldn’t put model logic in your controller but in your model. But this pattern is often taken too far. There are people that give the params-object, or worse, the entire controller-instance, to the model and do their shit there. This is not right. Use a service for that.
Pagination and searching are good candidates for a service. But this blog post is on the long side, so I’ll save an example implementation of that for another time. No post is complete without a promise to a follow-up that never comes, right?
Conclusion
It’s the same as I said during my talk: Rails helps you by keeping accidental complexity at a minimum. You can use the techniques described in Domain Driven Design to organize essential complexity and make your application more maintainable. Just be careful not to over-engineer it, that would defeat the purpose. Always be critical of your own code and continue to ask yourself the same question: “Does this make my code better?”
Customizing IRB, 2010 edition
TL;DR: Check out my new .irbrc-file!
Customizing my work environment is a nerdish hobby of mine. I spend far to much time tweaking my terminal. While I’ll save my terminal customizations for another time, I’ll show you my IRB tweaks in this post.
There are several tools to improve your IRB, and some of them have been around for ages. But the arrival of Bundler makes it difficult to use them. Bundler creates a bubble in which you have to specify your dependencies explicitly. Furthermore, with project specific gemsets, provided by the ever so awesome RVM, we need to install these IRB extensions for every project.
This means that you cannot be sure that extensions like Wirble are available in your new and shiny Rails console. There is only one way around that: add them to your Gemfile. This is what I usually add:
group :development do gem "wirble" gem "hirb" gem "awesome_print", :require => "ap" gem "interactive_editor" end
Extension Loading
To load the IRB extensions without blowing up in your face when they’re not available, I gently try to load them, and configure them only when that is successful. You can download my .irbrc on github. Here is what it looks like:

When you start IRB, it shows a line with the extensions loaded. If it’s gray, it’s not appropriate (like rails2 in this example), loaded extensions are green and extensions that are not available are in red.
Showing Queries in ActiveRecord 3
As you can see, the queries done by ActiveRecord are displayed in the same way as they are displayed in your log files. In Rails 2, you would’ve done this by redirecting the log output to STDOUT. In Rails 3 you need to subscribe to the ‘sql.active_record‘-notifications.
This could in theory also be done for other Rails 3 compatible ORMs like Mongoid, but I haven’t looked into that yet.
Hirb
Hirb formats objects into pretty tables, as you can see in the picture above. It also provides some scrolling possibilities like the command line tools less and more. Very handy!
Wirble
The first IRB extension anyone uses. Wirble provides you with history and syntax highlighting.
Awesome Print
While Wirble colorizes the output to improve readability, it can get cluttered really fast, especially when you’re dealing with nested hashes and arrays. AwesomePrint helps to untangle your object mess:

Print Methods
The ‘pm‘-extension I found on the intertubes some time ago, lists the methods and what arguments they take on any given object. You can filter it, by providing a regex. This is what it looks like:

It’s not a gem, but a snippet pasted directly into my irbrc, so it’s always available.
Interactive Editor
Open vim (or any other editor) from IRB, edit your code, save it, close your editor and the code gets executed. Open vim again and your code is visible and editable again. Very awesome! Check it out!
More
Yeah, there more. There’s bond, which makes autocompletion better, and utility belt, and more. I can’t remember to use them all, so I haven’t included them into my irbrc. They certainly are cool enough for you to check out! Also, a lot of great tips are here on Stack Overflow.
If you have any good tips, please share them! Oh, and the other OSX tweaks I use are on github.
PS. For those that don’t know how to load this: put the .irbrc file in your home directory and it will load automatically.
Using Sass with jQuery UI
Want to build a quick website or backend? Want to make it look good, but without adding too much effort in it? Then this recipe is for you!
The jQuery UI framework contains some nice styles and some nice javascript to accompany it. But the class names you’re ought to be using are awkward. Nobody wants to add “ui-widget-header” to their classes. We have standards; we want semantical html and css, even if we don’t want to be doing much styling ourselves.
Editing the css file that jQuery UI gives you is not an option; that would be a hideous mess even before we get started. Luckily, Sass can help us. Sass introduced the “@extend” method since version 3, which we can (ab)use.
We need to convert the css file jQuery gave us to Sass. I’m a big fan of sass, not scss, so I’ll be using that:
sass-convert --from css --to sass \ path/to/jquery-ui-1.8.2.custom.css > app/stylesheets/_jquery_ui.sass
I’ve included an underscore so it won’t be compiled to a real css file when I run my application. I’ve also configured Sass to load my sass files from app/stylesheets.
Next, create your own sass/scss file and use @extend:
| screen.sass | screen.scss |
|---|---|
@import jquery_ui .project-header @extend .ui-widget @extend .ui-widget-header @extend .ui-corner-all |
@import "jquery_ui";
.project-header {
@extend .ui-widget;
@extend .ui-widget-header;
@extend .ui-corner-all;
}
|
Now you just need to add the class “project-header” to the appropriate HTML element, include the compiled “screen.css” tag in your layout and you’re done!
Be sure to use the javascript too, for nice interactions. The javascript will add classes dynamically to certain elements. They will still work.
So what really happens? Well, @extend appends your own selector to the jQuery selector you specified. So the compiled jQuery css would’ve looked like this before:
.ui-widget-header {
border: 1px solid #aaaaaa;
/* more... */
}
But after doing our @extend-trick, it will now compile to:
.ui-widget-header, .project-title {
border: 1px solid #aaaaaa;
/* more... */
}
Sass parsing is incredibly smart. Really smart. The original jQuery css will be changed automatically. Awesome! And without hardly any effort from my side!
For more awesomeness in styling: Have a look at compass. It will be worth your time!
About structs
Recently I talked about a monkey patch called attr_initializer, allowing you to write code like this:
class FooBar
attr_initializer :foo, :bar
def to_s
"your #{foo} is #{bar}"
end
end
FooBar.new('foo', 'bar')
But there is a way of doing it without a monkey patch. Use the Struct.
FooBar = Struct.new(:foo, :bar) do
def to_s
"your #{foo} is #{bar}"
end
end
FooBar.new('foo', 'bar')
Pretty cool.
Update
As was pointed out in my comments by Radoslav Stankov (which you can’t see anymore, because I switched to Disqus), you can also do this:
class FooBar < Struct.new(:foo, :bar)
def to_s
"your #{foo} is #{bar}"
end
end
FooBar.new('foo', 'bar')
I use this one more often, actually.
One final note: the parameters here aren’t stored as instance variables, they can only be accessed through their accessor methods.
Cheating Performance With A Little Javascript
This little trick works with most websites with a menubar. When you have a menu that changes color pending on which page you are, you can cheat a bit on the perceived performance of loading pages. And all with just a little bit of Javascript. Intercept the links to change the state to active, before actually loading the page. The menu will feel much more responsive!
Imagine you add a class to the menu item that is active, like this:
<nav id="menu"> <ul> <li><a href="foo.html">Foo</a></li> <li class="active"><a href="bar.html">Bar</a></li> <li><a href="baz.html">Baz</a></li> </ul> </nav>
Then all you would need to do is something like this with jQuery:
$(function() {
$('nav#menu a').click(function(){
$('nav#menu li').removeClass('active');
$(this).blur().parents('li').addClass('active');
});
});
I’ve added a blur()-command in between, so the dotted lines disappear earlier.
Try it out, you can really notice the difference. It works best when the menu items don’t move, but only change appearance.
Update
Because I switched to Disqus, some nice comments have gone. Stefan Borsje, of Pressdoc fame, replied with this concern:
To be honest, I don’t like it very much. It really changes a basic way the web works; you click on something, the page loads (and optionally shows an activity indicator) and you get to see the result. With this method you already get see part of the result even before the actual loading fase, which could easily confuse users by letting them think the page is already done but nothing has changed.
I agree that you should be careful applying this technique. But the clicking of the link is done instantly, so the user would see the page loading immediately, thus he/she wouldn’t think the page is done. This technique works best if your pages are speedy enough, but can use just a bit more oomph.