This is a multi-part series. The first in the series is here.
Tower of Hanoi — Rules on Rails
In part 6 we changed the algorithm of Tower Of Hanoi to work without requiring the stack – it instead “more naturally” put sufficient state and logic into the model that the model could start and stop and continue as needed. I believe with Ruby 1.8.x, this is required to have Rails be able to work with the Tower of Hanoi. So we should try it out and see how well it works :-)
require'hanoi_7'classHanoiController<ApplicationControllerdefsay@hanoi=session[:hanoi]if(@hanoi==nil)then@hanoi=createHanoisession[:count]=0session[:consoleLog]=""end@hanoi.initApp(self)@isDone=@hanoi.doNextMove_IsDone()#clear the app because otherwise it will be part of the attempted serialization#could also override the marshaling code, but this is simpler@hanoi.initApp(nil)#clear out the session variable, but @hanoi is still valid through#the rest of this interactionsession[:hanoi]=@isDone?nil:@hanoi@count=session[:count]||=0@count+=1session[:count]=@countif(@isDone)thenrender(:action=>'say_done')endenddefappendLog(outString)logger.info("Append to Log: "+outString)@consoleLog=session[:consoleLog]||="\n"@consoleLog=@consoleLog+outString+"\n"session[:consoleLog]=@consoleLogenddefnoteChangeenddefcreateHanoihanoi=RulesTowerOfHanoi.newhanoi.initHeight(5)hanoi.setup_disksreturnhanoienddefgetAsciiTowersresult=""lines=Array.new@hanoi.stacks.each_with_indexdo|eachStack,i|0.upto(10)do|j|eachDisk=eachStack[j]if(eachDisk==nil)thennewLine=" "*12elsenewLine=eachDisk.to_sendnewLine<<" "*(12-newLine.length)currentLine=lines[j]||=""lines[j]=currentLine+" "+newLineendendlines.reverse.each{|line|result+=line+"\n"}returnresultendend
1234567891011121314151617181920212223242526272829
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"xml:lang="en"lang="en"><head><title>Foo <%= @page_title %></title><metahttp-equiv="Content-Type"content="text/html; charset=UTF-8"/><metahttp-equiv="refresh"content="1"><%= javascript_include_tag :defaults %>
</head><body<%if@page_class%> class="<%= @page_class %>"<% end %>>
<h1>Tower of Hanoi (Move <%= @count %>) </h1>It's <%= Time.now %>.
<br/>Done = <%= @isDone %>
<br/>Render =
<pre><%= controller.getAsciiTowers %>
</pre>Log =
<pre><%= @consoleLog %>
</pre></body>