Saturday, May 12, 2007

refactoring with test/spec




I have some ugly code to convert a String to a JSON array:


# Split the symbols_sent string into a javascript array

def convert_symbols_sent_into_javascript_array()
str = symbols_sent
n = "["
for i in (0...str.length)
n += "\"" + str[i..i] + "\""
if i < str.length - 1
n += ", "
end
end
n += "]"
@symbols_split = n
end


And I wasn't happy with it, so I'm going to try the Ruby JSON library:


gem install json


With this gem, it's really simple to convert a String to an Array and
then to JSON:


puts "123".split("").to_json


returns:


["1","2","3"]


Sweet.

So, finally, the actual test looks like:


specify "check json conversion of symbols_sent" do
orig_array = @adam.symbols_sent.split("")
json_array = JSON.parse
@adam.convert_symbols_sent_into_javascript_array
json_array.should.equal orig_array
end


Now, to refactor that original code to use the ruby json library:


# Split the symbols_sent string into a javascript array
def convert_symbols_sent_into_javascript_array()
symbols_sent.split("").to_json
end


Wow, that's so much sweeter. And having the specification running as
a test tells me that I did the refactoring correctly.