Helpers Are Code Too!
I think I’ve talked about this before, and there has been a Railscasts episode about it too, but I want to touch on it again. I know we’re supposed to keep views simple, but that doesn’t mean that helpers can only contain methods.
Rails gives you a helper module for every controller. The problem with modules is that they don’t contain state and are usually used to just put a lot of methods in. But this can grow quickly out of hand when the stuff that you’re building is a little more complex.
Never forget to run tools like Reek on your helpers as well. What do they say? Are your methods too long? Do your methods require too many arguments? Is the complexity too high? Do your methods have feature envy?
I’ve seen quite a lot of Rails projects and helpers are almost always the forgotten parts of the application. Every Rails developer knows about the “Skinny Controller, Fat Model”-principle. Better teams also make skinny models, by using modules and creating macro’s. But helpers are usually ugly. And they shouldn’t!
Helpers are code too! They want your love and dedication!
There are a couple of ways to keep it clean. Sometimes they are called “Presenter Objects” or something similar. It doesn’t matter how you call them, and you don’t have to use any complicated gems or libraries. Regular classes suffice.
Here’s an example of a typical helper:
module PostsHelper
def post_title(post)
header_class = post.published? ? "published" : "normal"
header = content_tag(:h2, post.title, :class => header_class)
content_tag(:div, :class => "post header") do
if post.user == current_user
[ header, edit_post(post), destroy_post(post) ].compact.join(' ')
else
header
end
end
end
def edit_post(post)
link_to('edit', edit_post_path(post))
end
def destroy_post(post)
link_to('delete', post, :method => :delete, :confirm => "are you sure?")
end
end
You might choose a different route, like putting the if-statement in the view. But that’s beside the point. The point is that this is what usually happens when you don’t use objects as they are supposed to be used. Look at the post argument for example. It’s on every frickin’ method! That’s not DRY!
And what if you need to extend it? What if you need approve and reject links as well? What if the destroy link needs to only show when the post has been approved? It’s becoming more and more messy. Time to refactor!
This is an example of how I would do it:
module PostsHelper
def post_title(post)
PostTitle.new(self, post).to_html
end
class PostTitle
attr_initializer :template, :post
delegate :content_tag, :link_to, :current_user, :to => :template
def to_html
content_tag(:div, elements, :class => "post header")
end
def elements
[ header, edit, delete, approve, reject ].compact.join(' ')
end
def header
content_tag(:h2, post.title, :class => header_class)
end
def header_class
post.published? ? "published" : "normal"
end
def edit
link_to('edit', edit_post_path(post)) if my_post?
end
def my_post?
post.user == current_user
end
# etc... (you get the drift)
end
end
Nice! Small testable methods! Readable code! Less repetition. Run Reek on that!
If you’re wondering what the attr_initializer is, it’s a monkey patch, that I’ve described here. The delegate-method is something ActiveSupport offers you. Use it, it’s super effective!
Wait a minute. Did I say “testable”? Yes, I most certainly did! As with any code, this needs to be tested. But it’s not that hard anymore! If you’re using Rspec, you can use the helper specs it provides. But you don’t need to!
The PostTitle-class is a regular Ruby class, and so every test framework can test with it without much effort. You might want to use stubs and mocks for the other helper methods you call. Or subclass PostTitle, define the used helper methods and use this to subclass in your tests. The delegate specifies which other helper methods are used.
Remember that what you program is entirely up to you. You, and only you, have to decide when a simple method is enough, or whether you need to add a class, or something similar. You can also consider using Builder for some parts, if the HTML generation becomes too hard.
The main point is that any part of your application needs to receive the same attention to detail. Don’t hide your dead bodies (of code) in helpers, or anywhere! Be critical everywhere and all the time! Run Reek regularly. It’s a depressing tool and you don’t need to fix every message every time. Use it wisely and pay attention. There is no excuse for ugly code!
In this example, I would use a partial, but when the view logic increases, you should be thinking about extracting it.
Conway’s Game of Life; or: Writing Perl in Ruby
We had a programming exercise this week at work. We were set out to write Conway’s Game of Life, using pair programming and TDD. It was a fun and educational evening. I even did some Scala.
Programmers humor dictates me that from time to time I say things like “In Ruby, that’s only one line!” or “In Ruby, that would cost me just one minute!”. Putting money where my mouth is, I wrote the entire application in just one line of Ruby.
So here it is. It looks more like Perl than Ruby. But it works!
String.class_eval{define_method(:to_grid){(self =~ /\A(\d+)x(\d+)\z/ ?
(0...split('x').last.to_i).map{|_| (0...split('x').first.to_i).map{|_| rand > 0.5 } } :
split("\n").map{|row| row.split(//).map{|cell_string| cell_string == "o" } }
).tap{|grid| grid.class.class_eval{define_method(:next){each{|row|
row.each{|cell| cell.class.class_eval{define_method(:next?){|neighbours|
(self && (2..3).include?(neighbours.select{|me| me }.size)) ||
(!self && neighbours.select{|me| me }.size == 3)}}}} &&
enum_for(:each_with_index).map{|row, row_num| row.enum_for(:each_with_index).map{|cell, col_num|
cell.next?([ at(row_num - 1).at(col_num - 1), at(row_num - 1).at(col_num),
at(row_num - 1).at((col_num + 1) % row.size), row.at((col_num + 1) % row.size),
row.at(col_num - 1), at((row_num + 1) % size).at(col_num - 1),
at((row_num + 1) % size).at(col_num), at((row_num + 1) % size).at((col_num + 1) % row.size) ])
} }} && define_method(:to_s){map{|row| row.map{|cell| cell ? "o" : "." }.join }.join("\n")}}}}}
I didn’t cheat! No semicolons where harmed during the making of the spaghetti code. I did enter some newlines in the code shown above to prevent wild scrollbars from appearing.
You can use it like this:
# generate a random grid grid = "100x30".to_grid # show the grid: puts grid.to_s # get the next generation of the grid new_grid = grid.next # convert a drawn out grid to a grid new_grid.to_s.to_grid == new_grid # returns true
If you want to know how it works, or make an animation of it, it’s all here.
This is what it looks like:

It was a fun exercise, but I don’t think I’ll be writing all my code like this in the future :)
ViewTranslator, a dynamic dispatcher
I’m a sucker for syntax. So once again, here’s a small experiment. It might not be the most useful snippet out there, but maybe it inspires you to do something awesome. The ‘Dynamic Dispatcher’ is a common pattern in Ruby. Here I’ll demonstrate it to add some syntactic sugar.
In views you can automatically scope translations to the view you’re working in.
So this HAML code (in the users#index view):
= t('.foo')
It’s the same as:
= t(:foo, :scope => [:users, :index])
I use this technique a lot.
Anyway, we could clean up it even more, by making a dynamic dispatcher. It would look something like this:
module ViewTranslatorHelper
def vt
@view_translator ||= ViewTranslator.new(self)
end
class ViewTranslator < ActiveSupport::BasicObject
def initialize(template)
@template = template
end
def method_missing(method, options = {})
ViewTranslator.class_eval <<-RUBY
def #{method}(options = {})
@template.t(".#{method}", options)
end
RUBY
__send__(method, options)
end
end
end
And now you can write:
= vt.foo
How does this work?
The vt method returns ViewTranslator instance. It is cached inside an instance variable. The ViewTranslator object inherits from BasicObject (ActiveSupport‘s BasicObject uses Ruby 1.9 if it is on Ruby 1.9, and constructs it’s own when on a lower Ruby version). BasicObject is an object that knows no methods, except methods like __id__ and __send__. This makes it ideal for using dynamic dispatchers.
When we define method_missing every single method we call on it will be passed to there. We could call @template.t directly from here, but we don’t. To know why, we must know how method_missing works. When you call a method on an object, it looks to see if the object knows the method. When it doesn’t know it, it looks to it’s superclass and tries again. This happens all the way until it reaches the top of the chain. In Ruby 1.8 that is Object, because every object inherits from Object. Ruby 1.9 goes one step further and goes to BasicObject. If a method is not found anywhere, it will go to the original object you called the method on and it calls method_missing. Since that usually isn’t there, it goes up the superclass chain until it comes to (Basic)Object. There it exists. It will raise the exception we all know and hate: NoMethodError. You can do this yourself too:
> "any object".method_missing(:to_s) NoMethodError: undefined method `to_s' for "any object":String
You see, even though the method to_s does exist on the string, we stepped halfway in the process of a method call. The error message is a bit confusing, but the we just called a method on the superclass of String. Anyway, by defining method_missing on our own object, it cuts this chain short. To cut it even shorter, I define the method itself, so it doesn’t need to go through this process at all. After it’s defined I call the freshly created method.
Now, to be honest. This is not at all that expensive to use method_missing in this case. The chain is only classes long, so it’s hardly putting a dent in your performance. There are cases were this is very important though. One such case is ActiveRecord. When you call a method on a new ActiveRecord-object for the first time, you reach method_missing. It needs to look at the database to find out if it is an attribute. Looking inside the database is very expensive, so method_missing creates methods for all attributes. If the attribute exists, it will be called, and it’ll be a normal method call from then on.
Thanks for reading. If you found it informative: I love feedback ;)
Qu’est-ce que c’est Rubyesque?
This is a translation of the post I originally wrote down in Dutch for my company.
I recently gave a presentation at my company Finalist IT Group about the philosophy behind Ruby. Code written with this philosophy in mind is called ‘Rubyesque’. It’s not hard science, so we had plenty ingredients for a discussion.
The reason behind the presentation was because we’re in need of more Ruby developers and looked inside our own company for Java developers that want to learn Ruby. Because Java and the philosophy behind it are so radically different from Ruby, we organized a discussion to explore those differences.
About programming and the ‘flow’
The Rubyesque mindset is all about opinions. Opinions tend to vary from person to person. By reading a lot of blogs and code I do see some sort of consensus. This opinion is not always explicitly mentioned, so I don’t pretend to speak in absolute truths or be complete.
Programming is usually compared with other professions to give an idea what it’s like to do it. Ruby programmers tend to compare programming with craftsmanship. I even go one step further. I think programming Ruby is a form of art of playing an instrument. Programming is a creative process. You’re programming to express meaning and intent. The only way to achieve this, is if you know your instrument so intensely that it’s not compromising you’re ability to express yourself.
Every programming language has its own style. You can call it its ‘flow’. It’s wise to go with the flow. It’s easier to use the language as it’s intended to be used than to go against it. For example, don’t try to force inheritance in a language that is intended to be prototype based. Program according to the flow and other programmers can understand and maintain your code better.
About Ruby
Everything in Ruby is aimed towards making the programmer happy. A happy programmer is better motivated to deliver great code and will feel responsible to do so. And better code makes everyone happy.
It’s the machine that is supposed to do the heavy lifting, not the programmer. This means that Ruby isn’t particularly fast, but since machine power is cheaper than man power, it’s not that big of a deal.
Ruby has a couple of traits that make it a joy to work with:
- Dynamic and open to bend it to your liking
- Few rules, so easy to learn
- There are ‘shortcuts’ for common tasks
- Many ways to reuse code, such as mixins
- Optional punctuation to improve readability
- Methods like attr_accessor to become more DRY
Dynamic
In a dynamic language it’s not important to know which type of object you’re dealing with, but it’s more important to know what it can do for you. This is called duck typing. This isn’t only handy in making mock object, but also means that you don’t have to abuse inheritance to comply to some method you’d like to call.
A nice example is the Rack specification. The header object you’re supposed to return needs to have the method each. It doesn’t say that it needs to be a hash. You could use a hash, but if it makes more in your sense to have some other object, it’s fine. You don’t have to inherit from hash, just to implement the each method.
The flow in Ruby is not to perform any check of the objects. If you’re explicitly want an integer, just call to_i inside the method. Any code that checks the type is usually considered to be distracting from the real meaning of the code. It’s the programmer that uses the gem/library responsibility to use the right objects, and not the responsibility of the gem-maker. The naming of methods and variables need to be obvious enough, so that it shouldn’t be a guessing game.
Open
In Ruby, nothing is final. This allows for the ability to add and change anything in any object, including core classes. This is called Monkey Patching or duck punching. This results in even nicer and more readable code, like:
15.minutes.ago
Nobody needs to explain this. Nobody needs to look up any documents to understand what is going on here. Monkey patching can improve the readability of the code immensely.
I understand that this technique may be considered extreme by some people. It doesn’t comply to the strict rules that govern most other languages. Still, these kinds of techniques are very handy and addicting.
Monkey patching is dangerous. It’s your own responsibility to use it responsible. Use tests to ensure that you don’t break anything unintentionally.
Punctuation
Some of Ruby’s punctuation is optional. Ruby programmers love to leave them out. It’s mostly a matter of taste. Readability is key here.
Rubyists rather write this:
class Post belongs_to :author, :dependent => :destroy end
Than the same code with all punctuation visible:
class Post
belongs_to(:author, {:dependent => :destroy})
end
It’s not important that {:dependent => :destroy} is a hash. Nor is it important that belong_to is a method, and that it takes two arguments. It’s much more important that the post belongs to an author and that the post will be destroyed when the author is being destroyed.
By not using all the possible punctuation, it becomes easier for our brains to focus on what is actually written, rather that which objects might be used to express it.
Few rules, many shortcuts
There are only a few genuine language constructs. There are just three elements in the language that have any real meaning. Those are objects, methods and blocks/closures. The only way in which classes and modules are special is by their implementation, but they are still regular objects. There are just a few other constructs, most notably if, while and the logic operators like && and ||.
The rest of the keywords you see are just shortcuts, you can type to perform common tasks. Like defining a class:
class Car < Vehicle # ... end
The Ruby interpreter reads this as:
Car = Class.new(Vehicle) do # ... end
Defining a class is actually just a method called on an object. The first argument is another object (the class to inherit from) and the second argument is a block. You can write it like this if you want to and play with it too, like dynamically making many different classes.
Some other examples:
counter += 1 # this is a shortcut counter = counter + 1 # without the shortcut, but also without punctuation counter = counter.+(1) # without the shortcut and with all punctuation (yes, + is just a method)
@user ||= User.new # this is called a 'teapot'-operator or 'or-or-equals' @user = @user || User.new # assign @user to @user if it exists, otherwise create a new user
exit unless busy or cancelled # 'unless' is a shortcut for 'if !()' exit if !(busy or cancelled) # 'if' at the end of a sentence is also a shortcut if !(busy or cancelled) # for a regular if exit end
There are many more shortcuts. But why? Why are there so many ways to do the same thing? It’s not just readability, but also the ease in which you can translate the ideas in your head to code.
The smaller the difference between your thoughts and your code, the easier it is to program. Ruby gives you full freedom to express yourself how you feel fit. That doesn’t mean it always works out. If you have an unclear image of the problem you’re trying to solve, the code you write will be unclear too. Nothing stops you to write bad code. Ruby doesn’t force you in any way. These things cut both ways.
Exposing intention
Code needs to expose its intent. Ruby code is Rubyesque if it uses the above mentioned techniques to expose its intent. Because Ruby has such clean syntax, most DSLs (Domain Specific Languages) will be written in Ruby. These kinds of DSLs are called internal.
The naming of variables and methods is extremely important. The meaning of the code must be clear the first time you read it.
A fantastic example is Rspec, my favorite test framework.
describe Post do
context "when it's not approved" do
subject { Post.new(:approved => false) }
it { should_not be_publishable }
end
context "when it's approved" do
subject { Post.new(:approved => true) }
it { should be_publishable }
end
end
The entire Ruby bag of tricks is being used to make it as natural as possible to write down your specifications. This example doesn’t like like regular Ruby code, but it still is. It’s nothing more than objects, methods and blocks.
This is very Rubyesque. There is almost no distraction from the meaning of the code. I can plainly read if my code still does what my customer wants and I can run the specs to see if my code does what I specified it to do. And even nicer: it’s incredibly easy! Rspec makes Test Driven Development very easy.
If you’re interested in the code to implement this example, take a look at this gist.
Succinct and Concise
Rubyesque code is succinct. That doesn’t just mean short lines (I try to limit myself to about 80 or 100 characters per line), but also about short methods. The code smell detector Reek will raise a warning if your method is longer than 6 lines. Does this means you are not allowed to write longer methods? Of course not. Is it a good idea? No.
People are better at understanding short sentences. And it’s the people that need to understand the code and maintain. And we’re back to the philosophy behind Ruby. It’s meant to be understandable for people. It’s less important if the computer needs to do some extra work.
Conclusion
Ruby is a free language. You can bend the rules. The goal is to make you happy. Ruby was made to make you happy, to close the gap between human and computer language. Try to do that in the code you write too, it works!
I found that most people coming from languages like Java or PHP find Ruby a weird or magical language. That is only the appearance. Ruby is very easy to learn. It has few rules. Ruby programmers don’t code using rigid rules and dogmas, but experiment solving the same problem in different ways.
I hope you got some idea of what it means to program Rubyesque. I advise everybody to look at the different languages and their philosophies. See what philosophy suits you. If the Ruby philosophy suits you and you have the discipline needed to write Ruby, give it a try! Ruby transformed the way I feel about my job and never regretted learning it one bit.
Monkey Patch of the Month: attr_initializer
So, about one month ago, I promised to share some useful monkey patches every month. Here is the second one. Your own monkey patches are still more than welcome!
I often find myself writing code like this:
class Foo attr_reader :bar, :baz def initialize(bar, baz) @bar, @baz = bar, baz end end
This can be very annoying to maintain. The variable names are repeated four times, within three lines of code!
Ideally, I’d want to write something like this:
class Foo attr_initializer :bar, :baz end
Much better, if you ask me. Here is one example of how to do this.
class Class
def attr_initializer(*attributes)
attr_reader *attributes
class_eval <<-RUBY
def initialize(#{attributes.join(', ')})
#{attributes.map{ |attribute| "@#{attribute}" }.join(', ')} = #{attributes.join(', ')}
end
RUBY
end
end
No piece of code is complete without tests, so this is it:
class AttrInitializerTests < Test::Unit::TestCase def test_attr_initializer klass = Class.new do attr_initializer :foo, :bar end object = klass.new(1, 'b') assert_equal 1, object.foo assert_equal 'b', object.bar end end
