Open source is a great thing. I love the fact that you can simply ignore feature requests by users and anybody will give you a hard time about it – hey, it’s just open source. Even better, people will start implementing things on their own if you make them wait long enough.

This is what happened with Christian Höltje and Jake Goulding who initiated a first version of rspec-apotomo. Thank you, guys!

It’s now possible to test your Apotomo widgets in isolation using RSpec. Yay! Let’s see how that works.

Using the Gem

Bundler is your friend, just add this one-liner to your Gemfile.

group :test do
  gem 'rspec-apotomo'
end

Whoops, this wasn’t a one-liner.

I’m your Generator!

To create a sample spec, just run the generator shipped with the gem.

$ rails g rspec:widget comments
  create  spec/widgets/comments_widget_spec.rb

Spec it!

Even the spec is pretty self-explanatory.

describe CommentsWidget do
  has_widgets do |root|
    root << widget(:comments)
  end
 
  it "should render :display" do
    render_widget(:comments).should == "No Comments!"
  end
end

All we have to do is setting up a widget tree with #has_widgets, just as know from controllers. The #render_widget method does exactly the same as in your application views – it renders and returns the markup. Easy.

Testing Events

Now, Apotomo would be boring without its interactivity.

describe CommentsWidget do
  # ..
  it "should respond to :post events" do
    trigger(:post, :comments).should == ["Thanks!"]
  end
end

#trigger first fires the event (first argument) from the source (second argument). It then returns an array of all return values from widgets responding to that event.

We’re now waiting for proposals how to simplify testing multiple responses – maybe some comfy matcher? I’m excited.

Let us know what you think of this new gem.

BTW- Cells and Apotomo is a lot of work, if you like my gems consider donating.

Why didn’t I do this earlier? Here’s the official Cells cheatsheet with all the information you need at hand when writing sweet view components in Rails.

It discusses the following topics.

  • Generator
  • Options processing
  • Rendering
  • Control Flow & Initialization
  • View Inheritance & Builders
  • Caching
  • Configuration
  • Test::Unit

There’s still some work to do and if something is missing feel free to fork and commit!

Enjoy your day!

Recently I sat in a job interview, we were TDDing a data structure. That was fun, but it turned out that one big minus for me was that I insisted on testing a private method.

I still believe that when writing a class that’s reused in multiple places (maybe as a gem) you have to test both the public and the internal API.

Here’s a very abstract example to discuss.

Example: A Helper.

Let’s say we were writing a helper method to join two strings and format them appropriately. I know, the example is more than stupid.

1
2
3
4
5
6
7
8
9
10
11
class Hello
  def welcome(name)
    name = sanitize(name)
 
    "Hey, #{name}!"
  end
 
private
  def sanitize(string)
    # do whatever you want
  end

The welcomeing process involves tWO steps. First, it removes unwanted chars from the name string using a private method (line 3). Then, the greeting is joined and returned (line 5).

To render the string, you’d do something like

Hello.new.welcome("<b>Ryan</b>")
  #=> "Hey, Ryan!"

Testing the public API

Now, since we ship this really useful helper in its own gem we have to test the public API thoroughly.

it "does not sanitize good names" do
  welcome("Ryan").should == "Hey, Ryan!"
end

Naturally, we’d also test edge cases to see if the complex internal logic works. For example, what if the name contains unsolicited markup?

it "removes HTML" do
  welcome("<b>Ryan").should == "Hey, Ryan!"
end

And so further and so on. Testing the public API with edge cases usually is a good thing. In my gems, I have so called API tests” which test the public interface, only.

Testing in Public – Guilty as Charged!

Testing your public API, only, brings certain benefits

  1. It’s less work as you’re testing less methods, resulting in fewer test cases.
  2. You don’t have redundancies in your tests. All egde cases are asserted on the public API, only, and you don’t do that on your private methods, again.
  1. Your test are more stable since they don’t have to change after an internal refactoring. Given the case you’d rename #sanitize you don’t have to touch your test as you did not test the #sanitize method at all.

Apparently, I can see those advantages and this is where I agree with my interview mate. However, what if a private method yields a certain level of complexity? What if my #sanitize method goes crazy, removes HTML, swipes out SQL injections and donates to Greenpeace at once, all-in-one?

I don’t want to run all those tests through the public API – and there is absolutely no point against testing a private method.

Let’s Go Private!

Testing private methods often makes sense, and I push those tests into so called “Unit Tests”. This might be a different context, scenario, or test file, depending on the test framework I chose.

it "removes HTML" do
  sanitize("<b>Ryan").should == "Ryan"
end
 
it "removes SQL" do
  sanitize("\DESTROY *\Ryan").should == "Ryan"
end

This approach creates redundancy. Some of the cases may have also been covered in the public test, yet. There’s a thin line between redundancy and better-maintainable code.

Anyway, when testing a private method we get benefits as well.

  1. Bugs can be spotted much faster when writing a provoking test against the concerned private method. As I know the bug is somewhere in #sanitize, why should I run through the entire public method stack?
  2. Tests are less complex and thus easier. Testing #welcome, only, obfuscates my output and my test. If I want to test if the sanitizer works, I don’t want to be greeted with an annoying “Hey!” in every test case.
  1. Private tests are focused on the problem the separated methods solves and don’t involve outer methods, which might introduce bugs as well.

Test Privates – Or Not?

When I started with “API” and “Unit” tests I created tons of redundancy. As I kept refactoring lots of tests would break resulting in a bit of work. So reducing private tests seemed to make my tests more stable towards refactoring.

However, if there is a private method that makes me feel nervous due to its complexity (I’m talking about 5 lines of code, not 45), I tend to write “Unit” tests against it.

What are your experiences? Are there any rules-of-thumbs, pros or cons I forgot? Let us know and feel free to comment!

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?