Adding Stats (Ruby on Rails)

Introduction

This entry is based on the Building Browsergames blog entry: Adding Stats (PHP)

It doesn’t hurt to have at least skimmed through the original blog entry about the PHP version before proceeding to the the Ruby on Rails version below.

Setting The User’s Defaults

Now, having skimmed through the PHP version of this, you can ignore most of what happened there. We don’t have to do anything special to use our templating system, it just works. We don’t need to go get the ID of the user after creating a new one, ActiveRecord handles that for us. As soon as we’ve done a User.create or User.new plus a save of the record, the ID will already be filled in for you to use. So where does that leave us?

Rails subscribes to a pattern for developing applications known as Model-View-Controller, I’ll link it to the Wikipedia entry for the topic because frankly I couldn’t find any short simple explanation of it. So hopefully as you see me use it through this series of tutorials you’ll pick up the basics by osmosis. The way MVC is relevant to this is that there is no way we are going to add new stats to a user or assign default values within the registration page or any other page. In Rails, those are views and they exist not to contain game logic but rather to simply display information and take input from the user. That’s it. Code to change the user belongs in the User model, so that’s where we’ll put it.

In this case what we want to do is assign a new set of default values (since the defaults we set in the migration that added the stats isn’t what we wanted). We could add another migration to alter the default values but that’s only necessary if we’ve got existing users we need to fix in the database and the only user’s we’ve got are test ones. If you only need to fix new users, we can just add a before_create function to the User model (app/models/user.rb):

def before_create
  self.attack = 5
  self.defense = 5
  self.magic = 5
end

Here’s the User model with our new code in place. Note that virtually all the code here came from restful_authentication when it created the User model in the first place. We just added the code above to it:

require 'digest/sha1'
 
class User < ActiveRecord::Base
  include Authentication
  include Authentication::ByPassword
  include Authentication::ByCookieToken
 
  validates_presence_of     :login
  validates_length_of       :login,    :within => 3..40
  validates_uniqueness_of   :login,    :case_sensitive => false
  validates_format_of       :login,    :with => RE_LOGIN_OK, :message => MSG_LOGIN_BAD
 
  validates_format_of       :name,     :with => RE_NAME_OK,  :message => MSG_NAME_BAD, :allow_nil => true
  validates_length_of       :name,     :maximum => 100
 
  validates_presence_of     :email
  validates_length_of       :email,    :within => 6..100 #r@a.wk
  validates_uniqueness_of   :email,    :case_sensitive => false
  validates_format_of       :email,    :with => RE_EMAIL_OK, :message => MSG_EMAIL_BAD
 
  # HACK HACK HACK -- how to do attr_accessible from here?
  # prevents a user from submitting a crafted form that bypasses activation
  # anything else you want your user to change should be added here.
  attr_accessible :login, :email, :name, :password, :password_confirmation
 
  # Authenticates a user by their login name and unencrypted password.  Returns the user or nil.
  #
  # uff.  this is really an authorization, not authentication routine.  
  # We really need a Dispatch Chain here or something.
  # This will also let us return a human error message.
  #
  def self.authenticate(login, password)
    u = find_by_login(login) # need to get the salt
    u && u.authenticated?(password) ? u : nil
  end
 
  protected
 
  def before_create
    self.attack = 5
    self.defense = 5
    self.magic = 5
  end
end

Extra Credit

  1. In this entry you saw one of the hooks ActiveRecord provides for us to perform actions at certain points within the lifecycle of an object (i.e. before_create). There are actually eight hooks in total for you to use. Visit one of several public repositories of Rails documentation (e.g. http://api.rubyonrails.org/) and read the documentation for ActiveRecord::Callbacks to see them all.
  2. As was mentioned in the previous extra credit item, http://api.rubyonrails.org/ is only one of several repositories of Rails and/or Ruby documentation. Here are a few others: RailsBrain.com, GotApi.com (this site offers documentation for many other APIs as well), and Noobkit Docs.

Wish there was more?

I'm considering writing an ebook - click here.

.

John Munsch is a professional software developer with over 20 years experience. He created a series of game development sites (XPlus and DevGames.com) on his own before co-founding GameDev.net in 1999. The blog for his PBBG work is located at MadGamesLab.com.

Wednesday, September 10th, 2008 buildingbrowsergames, code, rubyonrails
  • JohnMunsch

    That's a tough one for me because I have no PHP experience and I don't think Luke has any Rails experience. I know that given a choice of Java vs. Rails for web development I would recommend Rails hands down (and in fact I moved one of my own sites from one to the other), but that's probably not much help for you.

    One thing I could recommend is that if you find that you learn well from video resources that you look at some of the instruction made available by Railscasts.com (free) and PeepCode.com (small fees per video). There are also some introductory screencasts available at RubyonRails.com. Perhaps you could watch some material on both and see if one appeals more than the other. Alternatively perhaps flipping through some books might help. Simply Rails 2.0 might give you something you could compare against a good starting book for CakePHP.

  • I actually do have a very slight amount of Rails experience - although by
    now that experience might as well be nothing.
    Personally, I would recommend Django - have you already unconsidered it?
    Python is super-intuitive and easy to learn for new and experienced
    programmers, and the indentation-based scoping makes it so that Python code
    is a lot easier to read than the more brace-happy languages.

    When I *was* working with Rails, one book that I found indispensable was
    Agile Web Development with Rails - it was a great walkthrough on getting up
    and running with Rails(and if I remember correctly, it had an appendix that
    taught you enough Ruby to understand what you were actually doing).

    Personally, I would recommend against using PHP - while there are definitely
    arguments *for* it, there are enough arguments against it that you should
    probably steer clear. Using a PHP framework like CakePHP or CodeIgniter
    might change that(I'm afraid I haven't tried one yet), but in my experience
    PHP tends to almost encourage you to write poor, shoddy code. I'm not saying
    that's all you can write - but if you want to build things seriously, you
    will need to be a lot more careful with PHP in order to write good,
    maintainable code.

blog comments powered by Disqus

About

Building Browsergames is a blog about browsergames(also known as PBBG's). It's geared towards the beginner to intermediate developer who has an interest in building their own browsergame.

Sponsors

Got Something to Say?

Send an e-mail to luke@buildingbrowsergames.com, or get in touch through Twitter at http://twitter.com/bbrowsergames