As I promised yesterday, I won’t bore you with a tutorial on how to set up a database system, create a table, create a Rails model, and do CRUD (Create-Read-Update-Delete) with it. Instead, I’ll try to provide you with something more exciting (hopefully) for a first Rails app, a true Web 2.0 application: Ajax-powered Shout Box. All in 5 minutes, I promise. Sounds cool?
ShoutBoxes are somewhat popular these days, you know, these little boxes where anyone can post short messages that will be shown instantly on a web page. Sort of mini-chat feature, I guess. There are lots of ShoutBox scripts that you can find on the Internet, including (if not mostly) free ones. Let’s make YOU cooler than these guys by making YOUR own ShoutBox from scratch in about 5 minutes, the Rails way.
First, the obvious prerequisites are, you need to have Rails installed, and create a Rails project (I don’t care where you put it, as long as you can run script/server and you’ve tested that it works). Next time I won’t be that kind to tell you that, you know. For this project I won’t be using any database, even if it’s not that hard to setup a database system with Rails, this demo will run just fine without one. Unfortunately, that means our little demo will be somewhat useless if you want to actually use it without modification on a production site.
Minute 1
First, let’s create a non-ActiveRecord model class named ShoutLine which represents one line in the ShoutBox. Create a file named app/models/shout_line.rb and fill it with:
class ShoutLine
attr_accessor :name, :text
# Initializes a ShoutLine using some text
def initialize(name, text)
@name = name
@text = text
end
# Returns all ShoutLines in memory
def self.find_all
@@lines
end
# Adds a ShoutLine to the top of the ShoutBox, returns the added ShoutLine
def self.add(shoutLine)
@@lines.unshift shoutLine
shoutLine
end
# Initializes class variables
@@lines = [ ShoutLine.new(’hendy’, ‘Welcome to my ShoutBox!’) ]
end