This is a 5 minutes introduction to create a core patch to Rubinius.
- Write a core library patch to Rubinius is really easy. First we need to decide what we want to write. Run the specs and find a bug, or write your own specs. Im going to write my own spec. I decide to implement the missing spec hypotenuse form Math Module
- A bit of Test driven development :
- Find the math specs file : RUBINIUS_HOME/spec/core/math_spec.rb
- Write the spec :
- create the describe :
describe "Math#hypot" doend
- Add the basic cases :
it "return x**2+y**2" do
Math.hypot(0,0).should_be_close(0.0,TOLERANCE)Math.hypot(2,10).should_be_close( 10.1980390271856 ,TOLERANCE)
Math.hypot(5000,5000).should_be_close(7071.06781186548 ,TOLERANCE)
Math.hypot(0.0001,0.0002).should_be_close(0.000223606797749979,TOLERANCE)
Math.hypot(-2,-10).should_be_close(Math.hypot(2,10),TOLERANCE)
Math.hypot(2,10).should_be_close(Math.hypot(10,2),TOLERANCE)
end
- Add exceptional cases :
it "raise an ArgumentError exception if the argument are the wrong type" do
should_raise(ArgumentError){Math.hypot("test","test2")}
end
it "raise an TypeError exception if the argument is nill" do
should_raise(ArgumentError){Math.hypot(nil)}
end
- run the specs. ruby spec/core/math_spec.rb. Umm 3 fails
- Ok, lets coding
- Find the math module : RUBINIUS_HOME/kernel/core/math.rb
- Write the method
-
def hypot(x,y)
sqrt(x**2 + y**2);
end
- rebuild the core: rake build:core
- run the test again … ummm two fails. not so bad.
- Lets code again :
- The method :
def hypot(x,y) raise ArgumentError unless x.kind_of? Numeric or y.kind_of? Numericsqrt(x**2 + y**2)end
- rebuild the core
- re run the specs … 0 fails !!
- Thats all.
- No !! thats not al. As Tony Targonski point in the comments we have a bug. Ok lets write a case for the bug.
-
it "raise an ArgumentError exception if the argument are the wrong type" do
should_raise(ArgumentError){Math.hypot("test","test2")}
end/pre>
- run again the specs 1 fail !! ohhhh, We have a bug. Dont live with broken windows.
- Replace the "or" with "and"
- re run the spec.... 0 fails again. great just in time to go home.