Archive for the ‘iain.nl’ Category
Gemfile vim syntax file
I’ve updated my Gemfile syntax file, adding a dash of color and making sure it supports all elements of the Bundler DSL. You can get it here. You’ll also need to tell vim to automatically use it when opening a Gemfile by adding this file.
This is how it looks with the ir_black colorscheme:
source :rubygems gem 'rails' gem 'hoptoad_notifier' gem 'newrelic_rpm', :require => false gem 'mysql2' gem 'devise' # ... etc ... platforms :ruby_18 do gem 'system_timer' gem 'fastercsv' end group :development, :test do gem 'rspec-rails', '2.0.0.beta.20' end
Enjoy!
Building Blocks of DDD: Services
As promised, here is an example of how to use the idea of services from Domain Driven Design to help you design your code better. Let’s start with some theoretical stuff, before we dive into some example code.
In Theory
Services are best defined by what they’re not. They’re not entities or value objects. To recap: entities are identifiable objects, that have real meaning in your domain. This might be a user or a post (if you’re making a blog). Value objects are objects that are not defined by their identity, but by their value. An address of a person is usually a good example. It doesn’t matter which address object it really is, as long as it contains the data it is supposed to have. Services are none of these. Services do something with the entities in your domain.
A good example of services are classes. By their very nature, classes are services for initializing objects. In Ruby this is idea is emphasized by the fact that classes are objects too. They have state and behavior, just as any other Ruby object. But their behavior is always aimed at something else, not themselves. Services tend to have no state, or very little at the most.
What’s the advantage of thinking of classes as being services? Well, in my opinion it leads you to organize your code better. Class methods are only allowed to do something with creating instances of that class. If they are not doing that, they shouldn’t be class methods.
It also answers the question: where should this behavior go? If it’s not obvious, it’s probably a service. The ‘fat model, skinny controller’-principle has gotten some news lately. This principle was invented because developers (me included) were putting too much logic into the controllers. It made the controllers skinny and readable; but it had the side affect that everybody jammed the behavior into their models (entities), making them big and unwieldy. Services will help you create small and manageable classes.
In Practice
Time for an example. Suppose you have an admin interface which allows the user to find their entities in many different ways, filtering on attributes and ordering them around until he finds the entities he wants. It might be part of a advanced search box. This filtering business is an excellent candidate for a service.
There are many ways of making a filter service. I’ve made something similar to this recently. I’ll start by making a basic filter, with nothing specific.
module Filter
class Base
class_inheritable_array :filters
self.filters = []
# Call filter to define which filters are available.
# These will all be run in the order you specified
def self.filter(*filters)
self.filters.unshift(*filters)
end
# The params are the parameters you might have entered in your form.
attr_reader :params
def initialize(params)
@params = params
end
# Get all filtered results. This is the public facing method that
# you'd want to call when getting the results of the filter.
def all
apply_filters
scope
end
private
# As part of the contract, set the default scope by overriding this method.
def scope
raise NotImplementedError
end
# Run all the filters, specified in subclasses.
def apply_filters
filters.each { |filter| send(filter) }
end
# Probably every filter should be able to paginate the results.
# remember to call pagination last, because will_paginate won't return
# a real ActiveRecord::Relation object.
def pagination
@scope = scope.paginate(:page => page, :per_page => per_page)
end
def page
params[:page] || 1
end
def per_page
params[:per_page] || 20
end
# Similar to pagination, sorting is something common to all filters,
# The default order is :id, because that will be available on every
# model. You can override it easily however.
def sort(default = :id)
@scope = scope.order(params[:order] || default)
@scope = scope.reverse_order if params[:direction] == 'desc'
end
end
end
Now, you can make filters for every model. This means creating a class that inherits from this base class and implementing the simple contract we put in place. I’ll use the (t)rusty Post model as an example implementation.
module Filter
class Posts < Base
# Here I define the filter methods that will be used for posts.
filter :published, :by_name, :sort, :pagination
# The default scope for posts is a plain Post class without any scope added.
# You can apply some permissions here, for instance.
def scope
@scope ||= ::Post
end
# Only show published posts, when the 'only_published' checkbox has been
# checked in the form.
def published
@scope = scope.published if params[:only_published] == '1'
end
# Provide a simple name field to filter on the name of the post
def by_name
if params[:name].present?
@scope = scope.where('name LIKE ?', "%#{params[:name]}%")
end
end
# I want to sort by the published_at column by default
def sort(default = :published_at)
super(default)
end
end
end
To use this filter, call it from the controller:
class Backend::PostsController < ApplicationController respond_to :html, :json, :xml def index @posts = Filter::Posts.new(params[:filter]).all respond_with @posts end end
As you can see, this places the logic of filtering in its proper place. It’s not part of the model, since it’s not part of initializing objects, or behavior of individual post objects. It’s a separate service, doing something with something else.
These services are incredibly easy to make. Just think about the objects it’s trying to handle. These are probably the arguments of your initializer. Store those methods with an instance variable. All methods you create do something with either these objects or call methods that do so.
Don’t forget to run reek on your code to see if you have any Low Cohesion or Feature Envy warnings. If you get any, than that method probably doesn’t belong here, or you’ve got you’re initial parameters wrong.
Some bonus material
If you wish to simplify the interface even further, you can create a class method on the service to make it even easier (that’s a service to create a service, so to speak).
module Filter class Base def self.all(*args) new(*args).all end # ... rest of the base class ... end end
This reduces the connascence needed to use the service. Not really needed here, but it’s a nice way of cleaning up your interface.
You might ask where do I put this into my Rails application. I make a folder app/services and (because I use RSpec) a folder named spec/services. If you use autotest, you need to tell it to pick up changes in these directories. You’ll need to add the file .autotest to your application root folder, containing this bit of code to do the mapping:
Autotest.add_hook :initialize do |at|
at.add_mapping(%r%^spec/(.*)_spec\.rb$%) { |filename, _| filename }
at.add_mapping(%r%^app/(.*)\.rb$%) { |_, m| ["spec/#{m[1]}_spec.rb"] }
end
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!