Inspired by the Stop hating Java post by my friend Andrzej I started to identify the pros and cons of a pattern called Dependency Injection in the Ruby/Rails world. Before I explain the pattern, let me discuss the problem – a dependency.

What is a Dependency?

Let’s say we’re working in a casual Rails controller instance. Whenever we access an object (or class) instance different to the current controller instance (i.e. self), we’re creating a dependency. Dependency here means the controller needs to know class and method names in another domain. Here are some typical dependencies found in many controller actions.

def show
  @comments = Comment.find(:all)

Here, the action knows both where and how to find the comments. It’s a dependency to the model layer.

def update
  # ...
  logger.notice "Comment #{@text} updated."

In this example, we have a strong dependency to the logger component – looking into the Rails code we can see that the #logger method in turn creates a logger instance, so we have to know about instantiation and usage of the logger.

%h1 Welcome, #{current_user.name}

This partial uses a helper method #current_user, which in turn queries controller and request in order to find the current user instance.

What’s the Problem with Dependencies?

Now, the examples above are code you’re gonna find in almost any Rails application – and there’s nothing wrong with that! However, problems might appear as soon as you want to test components separately.

For instance, what if I’d like to test my logging code within the controller, like asserting that the correct message is logged when something special happens?

it "logs correctly" do
  put :update
  assert_equal "Comment Yo! updated.", 
    @controller.logger.last_notice

I’d have to mock the logger instance to make it “testable”, here, to provide the #last_notice method.

Let’s say the original #logger method looks like this.

  def logger
    @logger ||= Rails::SmokeSignalLogger.new
  end

To mock the logger, people overwrite the respective method in the test case.

ActionController.class_eval do
  def logger
    @logger ||= Test::MockedLogger.new
  end

Code like this changes the logger for the entire test suite and might break other tests. A common solution is to reset the original method after each test. In other words, we change a global property for a local test – and this is wrong.

Another Problem: Configurability

In addition to the testing problems we get with dependencies, what if my colleagues love the way I program and plan to use one of my modules in their software (highly improbable). However, they don’t want the SmokeSignalLogger since they’re not speaking Indian, but they want to use another logging layer JungleDrumsLogger?

As soon as my component is imported in their application they’d probably monkey-patch my code to “configure” it.

NicksControllerMethods.class_eval do
  def logger
    @logger ||= 
      JungleDrumsLogger.new(:flavor => :coconut)
  end

I personally consider monkey-patching a code smell.

What’s a component?

Ok. I showed a couple of examples about dependencies and I used the word component a lot. The reason for this is: The Dependency Injection pattern is only applicable in software systems consisting of separated components. The idea is that outer components inject dependencies into smaller components.

A component as it might be a piece of software like a controller instance, an ActiveRecord row instance or a logger object. I see three attributes to make something a component.

  • First, a component has a limited scope of interest. It’s field of work is bounded to some special duty (logging messages, rendering a comments box, …).
  • Second, a component instance cannot access properties of other components, unless you’re providing a way to do so. For example, the logger may not access variables of the controller and vice-versa.

Dependency Injections in Rails

To get back to our examples, let’s see how we could apply DI to get rid of the logger dependency. Don’t let the controller create it itself, but do that on the outside and pass – “inject” – the object into the controller.

One flavor of DI is called Constructor Injection and would imply we inject the logger in the constructor.

class ActionController < ...
  def initialize(..., logger)
    @logger = logger
  end

Obviously, the outer framework would have to take care of creating and passing the logger.

  logger = BushDrumsLogger.new
  controller = ActionController.new(..., logger)

A second form is called Setter Injection where the controller exposes a writer for the injected attribute.

class ActionController < ...
  attr_writer :logger

Both the using frameworks or the test case can set the logger without overriding any code at all.

  controller.logger = TubeMailLogger.new

Cells and DI

One huge problem I see with Rails and DI is: currently, there are not enough components. We got one monolithic ActionController instance, a couple of row models and a global view instance – that’s it. This doesn’t make Rails a bad thing, or thousands of well-running apps out there!

However, the missing components in Rails make it hard to write reusable software and test these in isolation. That’s why we got the Cells gem – it provides reusable view components for Rails and goes perfectly together with DI.

Say we have a sidebar widget that displays the recent comments from your blog. A cell encapsulates that part of the page, the data aggregation and the rendering (read this post if you need a quick introduction to Cells).

Injecting the logger, ouch!

If we needed a special logging mechanism for the widget we could pass it into the component. I don’t know why a widget displaying comments would need to log, but let’s assume it.

%h1 My great blog
 
#sidebar
  = render_cell(:sidebar, :comments, logger)

The cell could then use the external logger without creating a dependency.

class SidebarCell < Cell::Base
  def comments(logger)
    logger.notice "Displaying comments at #{Time.now}!"
 
    render
  end

The additional arguments from the #render_cell invocation are directly passed as method arguments – this is what we call state-args in Cells.

It’s obvious that another project using that sidebar component could inject a completely different logger instance.

Testing with DI

The limited scope of a cell makes it pretty easy to test. Not only can we test that object-oriented “partial” in complete isolation but also can we pass in a mocked logger easily.

it "should render beautifully" do
  render_cell(:sidebar, :comments, mock_logger).
    should have_selector("ul")
end
 
it "should log correctly" do
  logger = ArrayLogger.new
  render_cell(:sidebar, :comments, logger)
 
  logger.last.should match /Logging/
end

No need to change or reset any global here, just throw-away instances and we’re done!

Conclusion

I can’t think of a cleaner solution for dissolving dependencies like these. The DI pattern makes it easy to keep your components dumb. The problem is that you first have to identify your dependencies, then refactor to components and inject instances from the controller (or wherever else).

Especially in Rails, Cells help to build a real MVC application with a data-aggregating ActionController (I call this FrontController) and fine-grained view components that get additional dependencies from the outside.

When Michał pinged me about the upcoming Railscamp 2011 in Wisła in the polish mountains it was a matter of minutes until I signed up and registered for this awesome event. The polish Ruby community is amazing, so I knew we will have good times there.

We met in Krakow one day beforehand, had yummy beers the whole day and crashed at a nice place, the Moon Hostel I can really recommend.

The next day we headed to Wisła in Michał‘s nice german VW and after a 4 hours ride, delicious drinks, Bad Religion “30 Years Live” on the stereo and several pee breaks he could finally join me drinking. Michał insisted on me having beers during the whole ride so I was in a good mood already ;-)

0048

Meet the Crew

The Railscamp was taking place in a cool “forest hotel” 10 minutes footwalk outside of Wisła. It had about 20 four-bed rooms, and a couple of bigger rooms for hanging out. The Cells & Apotomo Gems Team (that’s us) sponsored a couple of beer boxes, we just put them in front of the hotel and welcomed all incoming nerds with fresh beer.

0050

This was absolutely cool since I met a lot of Ruby folks I knew from earlier events or from the internets, like Pawel, Bumi or Andrzej.

Finally, about 60 Rubyists from Poland, Germany and even from England (Yay!) had arrived, everybody had dinner, everybody was drinking constantly. Being good nerds, the beautiful waitress girls who served us were being watched permanently.

0053

I can’t remember if we did any tech talk this night. I talked to great people, listened to music, we had drinks the whole night and we all could feel the Ruby love.

0075

Yeah, there was love.

0084

Ruby programmers are not afraid of showing friendship. A kiss on your cheek is considered pleasant, especially when your name is Bastek.0088

Late at night and quite drunk we went to bed. The comfy beds made us sleep very well.

0094

On a Saturday nite…

The next morning, Michał, Schorsch and I had a walk into the city to get some food and coffee. It wasn’t raining, but cloudy and a chilly wind was blowing from the north. Talking about gems, hangover and polish girls we found a nice place for coffee.

0097

We spent the rest of the day with playing soccer in front of the hotel (where the beer boxes sat). Before dinner, I had the chance to rant about Rails and REST – finally!

Dinner was happening outside at the barbeque place and that was indeed amazing. Great BBQ food, burgers, wine and beer, good chats. Suddenly, the party started again and people got crazy.

0115

After José played some songs on his acoustic guitar Bastek and I conquered the stereo. It didn’t take long and 20 nerds were dancing, urging the three or four girls to participate in such a thrilling event.

0129

Polish people are great. Everytime I go to Poland, I instantly feel the sincere hospitality that makes me wanna stay there!

0130

Ela and Agata were amazed that german boys started the dance.

0132

It was an awesome funny night. Especially when Bumi started handing vodkas to random people for at least an hour the dancefloor turned into burning hell.

0139

The party lasted at least till four. Some folks prefered strange sleeping places. I mean, we had warm beds, so why would I wanna crash on the toilet seat???

0151

Finally, we got to sleep.

0156

Sunday – No depression!

I got the chance to catch a ride with people from Krakow on monday morning so we spent the sunday night at the hotel watching movies, drinking and talking BS. Since we had to get up very early, four of us decided to make a night of it.

0173

I will never forget Julian from the UK, seven in the morning, sitting at the breakfast table: “Guten Morgen, drei Bier bitte.” where he ordered three other beers in perfect german.

Tell me why I like Mondays

The nice guys from Applicake took Julian and me to Krakow, made me sleep on their office couch and even gave me food and coffee. They’re awesome.

0178

I got invited to stay at Ela+Bart’s place for the night. Agata came over and we had a delicious dinner at the mediterranean yoga table in their appartment. Laughing fit included.

0183

Bart was so generous and gave me a free pair of socks since I ran out of clean stuff. Thanks Bart, I still wear them with pride!

0191

Tuesday and going back home

The next morning I had to deliver a quick talk about my gems Cells and Apotomo at the Applicake office. After another delicious coffee and saying goodbye to all my polish friends in Krakow Agata took me to the train station and I headed off to the airport.

0217

It was a fantastic “weekend” in Poland and I will definitely keep coming back there! Polish people even made me going Web 2.0 (“That’s so nineties…!”) and sign up at twitter, flickr and facebook! I’m mainstream now!

0046

Beautiful Poland!

Here are more pictures.

Are Class Methods Evil?

Two things I like in programming: Object instances and abandoning global things.

I especially appreciate any DCI effort in the community helping us getting away from classes back to thinking about objects and clean responsibilities.

In order to explain my thoughts about DCI, here’s a first post about class methods, which seem to be a crucial problem in this newer approach.

A tweet from my good friend Michał Łomnicki recently made me think about class methods in Ruby. What he was basically saying is that class methods suck.

I’m more and more against using class methods. It often leads to procedural-like programming.

From a rant perspective I’ll second that and agree. However, class methods have a certain purpose, so let’s discuss it in this post.

What Is a Class Method?

Class methods are global methods. You may access and call them from anywhere since you don’t need an object instance.

class User
  def self.find(id)
    # ...
  end
end

In order to find a certain User instance you call the class method #find on the User class. I personally find this a handy thing.

michal = User.find(1)

As we’re creating a fresh instance we command the class to do so. And since there is no user instance around, yet, we have to use a class method rather than an instance method.

What’s the Problem With Class Methods?

Now, class methods come in handy – you don’t have to think about the context as they’re available everywhere. Consider the following misuse of a class method.

class User
  def self.email_to(id, email)
    user = User.find(id)
    Emailer.send(email, "Hello, #{user.name}")
  end

It’s obvious that #email_to has to be refactored to an instance method. Nevertheless, I see code like that quite often. Just for completeness, here’s a better version.

class User
  def email_to(email)
    Emailer.send(email, "Hello, #{name}")
  end

Object-oriented vs. Procedural

What makes the class method example being bad style is that we’re in an object-oriented environment. Maybe we can break that down to the advise “Use object instances wherever possible.”

In the example, the programmer didn’t see that the email behaviour (aka method) is tied to an instance rather than to a class. His user code will look like the following.

User.email_to(1, "michal@snatch.pl")

If subsequent method calls like this would follow, this could be considered procedural code as we’re not working on object instances but on globally available methods. And, yeah, I personally don’t like global things when it comes to programming.

Avoiding Class Methods

Right now, I can come up with two reasons for having class methods.

  • The programmer didn’t analyze his problem sufficiently, does not see the coupling to an instance and simply pushes the behaviour into a class method. That happened in the last example.
  • There simply is no object instance available at this system state and we’re urged to use a class method.

On first sight, there seems to be no way out for the latter.

Abandoning Class Methods?!

There are strong opinions on the net that class methods shouldn’t be used at all (except for the constructor, of course). I’m still unsure here.

Anyway, in a lot of cases class methods can be replaced with instance methods on factory or builder objects.

michal = user_factory.find(1)

This implies a user_factory instance is around. So my question is: Where would this come from? There must be some kind of initial class method call somewhere in the chain of actions. I’d love to see some reactions and comments on that.

Class Methods and DCI

The reason I’m writing this here is that I like the DCI approach where you dynamically extend objects at runtime according to system state.

Object instances include required behaviour and then, they die. No pollution on class layer.

This works great with instance methods but there are big problems when it comes to class method usage (see the next post). So – are class methods evil?

We were discussing the design of search resources in a REST architecture after the REST talk at the EuRuKo. Usually, search resources process GET requests, compute a subset of searched items and return a representation of the respective items.

The following GET request illustrates this.

http://articles/search?type=shirt&color=red&size=s

It’s absolutely common to allow more parameters.

http://articles/search?type=shirt&color=red&size=s& \
  gender=female&limit=10&amount=20&

Where’s the search resource?

Now, let me state two facts about these URLs.

  • From a REST perspective, those two search queries refer to two different resources. Remember: Resources are addressed with unique URLs, and when URLs differ you’re addressing differing resources.
  • Within Rails, this doesn’t matter that much since both URLs are processed in the same controller. This is cool. A controller per definition is meant to expose a set of resources.

Long URLs and REST

After having discussed the meaning of resources the question that came up was

“Isn’t such a long URL with lots of query parameters comparable to clumsy XML-RPC arguments?”

Well, I’d say: No way.

  • Dynamic resources have to receive input in a certain manner – this makes them dynamic. Query parameters were designed to let users specify parameters. There’s nothing wrong with allowing input.
  • However, if you decide your URLs are getting too long you have to redesign your search resource architecture!

Exposing named queries

The REST cookbook – a fantastic write-up which I do strongly recommend – suggests to identify commonly used search criterias and expose those queries as separate resources.

Say we’re annoyed with the long “search red female shirts” URLs. Why not donate a dedicated resource?

http://articles/shirts/female?color=red&size=s

While this is just an example, it demonstrates how commonly used parameters were consolidated in a new URL base. Again, from the REST point-of-view, this points to a completely separate resource.

However, in Rails, this can simply be mapped to the search controller while providing the remaining parameters in the route definition.

match 'articles/shirts/female' => 'articles#search', 
  :defaults => { :gender => 'female',
                   :type => 'shirt' }

Controllers and Resources

Don’t give me a hard time about the routing – what I wanted to discuss is the way of thinking about resources: You’re free to map different URLs to one controller. One of main architectural concepts in REST is that it’s up to you how you design your resources and how to expose them.

Query parameters don’t kill your mother and choosing named URLs is free – it’s absolutey “RESTful”.

Just released Cells 3.6 – Cells are view components (aka portlets or widgets) for Rails. The new version runs with Rails 3.0 and 3.1 and it has no cool new features!

The view inheritance code got obsolete for 3.1 since Rails itself implements it, so Andrzej Krzywda and I decided to introduce a Strategy for separating different version portions in Cells. This makes it pretty easy to maintain two versions since the version-dependent code is abstracted into separate strategy files.

In the following version we will allow rendering specific template formats.

render :format => :js

This involves a slight refactoring of Rails’ internal rendering cycle and it’s highly probable that this fix will be merged into Rails 3.2 itself.

Now, go and have fun with Cells and Rails 3.1!

The third episode demonstrates using more than one widget in a page. As I write a task counter widget and a list widget we discuss

  • rendering multiple widgets
  • simple event bubbling
  • observing non-local events

In the 2nd episode we learn a bit about states and #render:

  • What is a state?
  • Different ways for rendering views and states
  • The #render API
  • Nesting states where others use partials
  • Passing arguments into states using state-args
  • Understanding #replace

Anything more?

Finally, I started screencasting about Apotomo. The episode 1 discusses

  • Setting up a basic widget
  • Rendering widgets in controller views
  • Triggering and catching events

Let me know what can be improved!

The representable gem helps to keep parsing and rendering representations in one place. Once defined, it gives your model #to_xml, #from_xml and more. The initial version was released today, let’s see how it helps cleaning up your representation code.

Let’s write a Blog app!

Since your imaginery blog app has a REST API you want to provide a post resource serving and consuming article representations. Here’s a sample XML representation of an arbitrary blog post.

<post>
  <id>1</id>
  <posted_at>2011-05-09</posted_at>
 
  <comment id="1">
    <text>This is stupid!</text>
  </comment>
  <comment id="3">
    <text>No, awesome post!</text>
  </comment>
</post>

Basically, a post representation contains comments in addition to some meta data.

The Problem: Two places need to know about your Representation.

In, say, a Rails app, you’d have to tweak the models’ #to_xml method in order to render an XML representation. Alternatively, you’d use a Builder template.

If, and only if, you stick to the Rails conventions, #from_xml will work out-of-the-box. Otherwise, you have to write a manual parser as discussed earlier. Note that the <comment> tag contains an attribute not compliant with Rails.

You usually end up with some model code, maybe even a template and a hand-made parser. This distributes representation knowledge over the entire MVC framework. While this won’t kill your mother it still makes things more work to manage.

Defining a Representation

The representable gem is designed to prevent you from doing that. You simply define the representation in one place and it does the REST (I still love the word-play).

1
2
3
4
5
6
7
8
require 'representable/xml'
 
class Comment # < ...
  include Representable::XML
 
  representable_property :text
  representable_property :id, :from => "@id"
end

The Representable::XML module allows to define plain properties (line 6) and attributes (line 7).

Nesting Representations

The post representation uses the compositing feature in representable in order to embed comments.

1
2
3
4
5
6
7
8
class Post # < ...
  include Representable::XML
 
  representable_property :id
  representable_property :posted_at
  representable_collection :comments, 
    :tag => :comment, :as => Comment
end

Wow, you can define nested compositions with representable (line 6). This is easy, so how do we work with it?

Rendering Documents

You want to render a document representing your post now.

Post.find(1).to_xml 
  # => "<post><id>1</id>comment id=\"1\"..."

Representable takes care of rendering. No magic included.

Parsing Representations

What if you allow people to POST an XML document to the blog post resource?

@post = Post.from_xml(request.body)
@post.comments
# => "[#<Comment:0x8545a08 @text=\"Your blog sucks.\">]"

Again, representable deserializes the incoming representation and creates the respective objects for you. Representable doesn’t know anything about databases or your underlying data layout, though. It just creates fresh instances for compositions making it your job to process it.

Other media types?

Representable comes with XML and JSON support, you just have to mix in the respective module.

@comment.to_json
  # => "\"{text => ..."

How does it help?

Representable is a completely abstract module for rendering and parsing representations and mapping document fragments to object attributes. Nothing more.

It makes working with representations object-oriented where you had view templates and parsers before. While representable makes that workflow as simple as possible it also allows distributing your representation code, since it can be pushed into Ruby modules. Maybe it makes sense to use it on both client and server, in Rails and Sinatra?

Representable is also used in Roar to make life easier when working with REST representations and embedding or consuming hypermedia. We will discuss how representations and HATEOAS work in the next post. Cheers.

A couple of days ago Pavel Gabriel and I released a refreshed version of the test_xml gem.

test_xml helps you asserting that XML is the way your specification wants it. It provides some simple assertions and runs with Test::Unit, MiniTest, RSpec2 and Cucumber. It’s perfect for testing REST services emitting XML representations. Internally, it uses Nokogiri for node matching.

Overview

Say your expecting the following XML document from your service (or whatever).

<company>
  <id>1</id>
  <name flavor="funny">Applicake</name>
</company>

Now it is pretty tedious testing this against a string with regexps while skipping newlines or whitespaces and so on. Use test_xml for that!

assert_xml_equal expected, "<company><id>1</id>
  <name>Applicake</name></company>"

As you’re using assert_xml_equal this will fail – the subject is missing the flavor attribute and thus is not equal!

We can do that in RSpec as well!

  expected.should equal_xml expected

This will work. Obviously.

Testing structure, ignoring content

Sometimes you might want to test the tag structure without respecting the content or attributes.

assert_xml_structure_equal expected, "<company>
  <id>One million</id>
  <name>Railslove</name></company>"

Turns out to be true.

Asserting parts, only

Sometimes you might want to check that your XML contains some markup block, which doesn’t need to be the very image of your specification.

assert_xml_contain expected, "<company>
  <name flavor="funny">Applicake</name>
</company>"

Works! This is especially helpful if you’re interested in certain blocks of your markup and not the entire document.

Assertions?

What we got is

  • assert_xml_equal
  • assert_xml_contain
  • assert_xml_structure_equal
  • assert_xml_structure_contain

Pretty obvious what they’re doing, isn’t it? Use ‘em in RSpec if you feel like it.

Give it a try!

Now go and check out the test_xml gem and feel safer when rendering XML. Testing FTW!