Fluent interface for numbers Kata
Taking the lead from Kevin Rutherford, I’ve had a crack at Mike Feathers’ numeric literals kata in Ruby. The idea is to allow the following sort of thing:-
assert_equal 24, twenty.four assert_equal 2100, two.thousand.one.hundred assert_equal 1019000, one.million.nineteen.thousand
My solution (with tests, obviously) is here. Mike poses two questions
What qualities does a grammar need to have to create an embedded DSL which doesn’t allow nonsensical constructs?
In my example I couldn’t be bothered: seven.eleven evaluates to 18, and I don’t particularly care. A solution that takes care to enforce a strict grammar goes against the grain in Ruby, in my opinion.
If you really need to be strict then you’d probably be better going down the External DSL route, rather than implementing an Internal DSL in Ruby.
What is the minimal number of classes needed to implement it?
I went for zero. Well – kind-of. I just added methods to Object and Number. That’s the nice thing about Ruby: you don’t need that much code. Steve Yegge would be pleased.

0 Comments:
Post a Comment
<< Home