If you’re reading this article, you’re wasting valuable time that could be spent building robots, in ruby, that battle each other to the death. I can hear you already: “Does such a thing actually exist??” Well no, not really. But there are two consolation prizes:
- it will exist in the very near future, and
- until it does, I’ve created a simplified version to whet your appetite.
Rubots!
“Rubots” is the word you use when you’re referring to Ruby Robots but don’t want to waste precious rubot-coding time pronouncing the full phrase. My goal is simple: to create Ruby-based games where you can code your own player classes to battle against the sample players provided, other players you’ve created, or for the most fun: players created by your Rubyist friends!
The popularity of Rails has brought many people to the Ruby camp. Sadly, many of these people don’t learn how to code Ruby outside of the Rails environment. I got my start through Rails, and there were times I wasn’t sure where one ends and the other begins. I want to get programmers comfortable coding pure Ruby, and there’s no better way than the promise of digital violence.
Prisoner’s Dilemma
My first iteration of this concept is a Rubot implementation of the classic game theory exercise, Prisoner’s Dilemma. The gist is that you’re one of two prisoners who have been placed in separate rooms and questioned by the authorities for a crime. You have to decide whether to cooperate with your partner in crime by not saying anything, or betray them by cutting a deal. There are different rewards/consequences based on how each of the two players decides to act.
You can download it here:
https://github.com/bellmyer/prisoners_dilemma
The README is pretty comprehensive, so I won’t rehash all of it here. The basic idea is that you create player classes that decide whether to cooperate with, or betray, their opponents. The game is played in multiple turns, so you can base your decision on how you and your opponent have behaved in previous turns, or any other criteria you want to consider. Maybe your prisoner gets grumpy around nap time, and from 2-4pm it only betrays its opponent :)
This is meant to be played tournament style, and so I’ve included a basic round-robin script that loads all player classes in the project directory and pits them against each other in a battle royale. This is a great activity for Ruby groups, especially among beginners. Player classes inherit from a prefabbed parent class, and simple strategies can be implemented with even a basic understanding of the language.
Enjoy, and please provide feedback. This will be the first of (hopefully) many games offered in this same style. Rubots unite!



Nested Comments in Ruby on Rails, part 2: Controllers and Views
January 26, 2011Part 1 of this series came out exactly 3 months and 3 days ago. Special thanks to a reader named Edward who prodded me to finally add the controllers and views to this.
Going beyond the model layer for nested comments introduces a new programming idiom: recursion. Some ruby developers may not be familiar with it – especially if your experience is mostly web-related, where the need doesn’t come up as often. Recursion in a nutshell is the act of a method calling itself. If you’ve seen Inception, The ability to have dreams within dreams within dreams means those dreams are recursive. If you haven’t seen the movie, think of russian matryoshka dolls. You won’t experience star-studded special effects with the dolls, but you’ll at least get the idea of recursion.
Unlike russian dolls or most of Leo’s recent work, recursion in software is potentially infinite. Practically speaking though, it’s more like the doll thing. After all, a system only has so many resources, and recursion is expensive in this regard – the method must copy itself in memory at each layer, local variables and all. On the plus side, they tend to be lightning fast compared to standard iteration using loops. And in our case, we’ll be hitting the database at each layer. We’ll ignore the dangers in our simple app, though.
Routing
Let’s start with our routing file:
# config/routes.rb NestedComments::Application.routes.draw do resources :comments do resources :comments end resources :posts do resources :comments end root :to => 'posts#index' endWorking backward, we’re making our Posts controller’s index action our default route. That’s just to get the app functional. Next comes something interesting: nesting our comments inside of our posts. Interesting, but boring. Finally, the main event: nesting our comments within our comments!
Before you get too excited and start pulling out your Nana’s childhood russian doll set for comparision, this isn’t true recursion. It’s well documented that nesting resources any more than two layers deep is painful and unnecessary, so think of this as the lamest russian doll ever.
Controllers
First, our Posts controller, which is less exciting:
# app/controllers/posts_controller.rb class PostsController < ApplicationController def index @posts = Post.all end def show @post = Post.find(params[:id]) end def new @post = Post.new end def create @post = Post.new(params[:post]) if @post.save redirect_to posts_path, :notice => "Your post was created successfully." else render :action => :new end end endWe’re setting up a pretty standard restful resource here, with a couple actions skipped for simplicity. Now the comments controller (get those dolls ready):
# app/controllers/comments_controller.rb class CommentsController < ApplicationController before_filter :get_parent def new @comment = @parent.comments.build end def create @comment = @parent.comments.build(params[:comment]) if @comment.save redirect_to post_path(@comment.post), :notice => 'Thank you for your comment!' else render :new end end protected def get_parent @parent = Post.find_by_id(params[:post_id]) if params[:post_id] @parent = Comment.find_by_id(params[:comment_id]) if params[:comment_id] redirect_to root_path unless defined?(@parent) end endIt’s not much bigger, but there’s a lot going on here! First, since comments are nested, we have to look for a parent. We’re only creating comments in this example, so we only have those related actions. Comments will always be shown on a post page.
The really exciting part is after a successful comment creation. How do we redirect back to the post page? For all we know, this comment could buried down 12 layers of replies. All we really have access to so far is the parent of the object. This necessitates a new model method:
Recursive functions are often short and sweet for two reasons: they’re already complex by nature, and adding more code than necessary would make them unmanageable. Also, they’re getting a lot done in just a few lines. In this case, the second line is the key: if “commentable” (the parent object) is a post, return that. Otherwise, call this same method on the parent, which will in turn check if *it* is a Post, and so on.
I could have written it shorter, like this:
In fact, I did at first. But the extra code that checks and sets an instance variable is caching the result. This way, if we call the same method on an object more than once, it stores the result for future use. Remember, recursion can be expensive – especially when the database is involved.
Views
Finally, it’s view time, with one more bit of recursion for fun.
Or post views are standard scaffolding mostly, with the exception of the show view:
Notice we have the partial app/views/comments/_comment.html.erb. We’re calling this for each of our post’s comments. Nothing too fancy here. Now, for the partial itself:
# app/views/comments/_comment.html.erb <li class="comment"> <h3><%= comment.title %></h3> <div class="body"> <%= comment.body %> </div> <p><%= link_to 'Add a Reply', new_comment_comment_path(comment) %></p> <% unless comment.comments.empty? %> <ul class="comment_list"> <%= render :partial => 'comments/comment', :collection => comment.comments %> </ul> <% end %> </li>This partial is recursive! The comments controller doesn’t have a show method, because we’re never going to view a comment by itself. Instead, the show-like code is in this partial, and at the end it checks to see if *this* comment has comments. If so, it calls the partial again on the whole collection. The end result is a nested, bulleted list of comments. This is not very sexy if you fire up the code yourself, but it’s a great starting point.
Summary
Hopefully this article as done a good job of explaining both recursion, and how to use it to achieve nested comments in your applications. If you’re new to recursion as a concept, haven’t seen Inception, didn’t inherit russian dolls from Nana or receive them as a snazzy graduation present, and my explanation somehow fell short, it’s a well documented programming idiom. There are tons of resources online, so take the time to learn this powerful tool, then learn not to overuse it :)
Please download the code and play with it if you want to learn more – the code is fully test-driven so you can see how that works, which is just as important.
On a final note, I’m tempted to do a follow-up article with ajax and some nicer formatting. Perhaps in 3 months and 3 days…
Tags:comments, nesting, polymorphism, posts, Rails, recursion, recursive, Ruby, ruby on rails
Posted in Database, Rails, Testing | 9 Comments »