Really Getting Started in Rails
We cover everything from The Most Ridiculous Performance Fix Ever (and it is ridiculous), to serving strategies, DOM diets, loop unrolling (for those really extreme cases), how to play nice with the garbage collector, and everything in between. And it comes with our custom profiling tool, The DOM Monster, which analyzes your pages and suggests fixes. This package is only $24 right now but will be $29 as soon as it’s done, in mid-June 2009… but if you snag your copy today, you get the final version by email just as soon as it’s ready and save a noteworthy 5 bux! You can’t lose.
Curt Hibbs has written Rolling with Ruby on Rails, a tutorial on Ruby on Rails for O’Reilly OnLAMP. (Amusing fact: LAMP is an acronym for the triumvirate+1 of Linux-Apache-MySQL-PHP. I am perfectly willing to admit that I am, in fact, easily amused, but I think that this is kinda funny.)
It’s a good tutorial. Good as it is, though, it’s not perfect (hell, what is?). But hooray for imperfection, because it spurred me to write.
It’s actually a pretty good article, the one with the most depth and breadth that I’ve seen at this point, and I used it to explore Rails last night. If you already know and understand programming concepts like database connectivity, object orientation, variables, loops, etc., then it’s a good place to start to get your hands dirty. After having actually produced some code, even if it was guided, I now have a better grounded understanding of Rails and that makes it easier to read the dry (not DRY, alas) documentation.
The only thing is, like all tutorials, it doesn’t always explain why. Why is that the syntax? What does that line mean, exactly? Why is the application designed so it fits together that way? Me, I like to know why—in reality, because of my designer brain, I have to know why to really grok it and retain it.
The Missing Minutiae
It’s true—I’m a little impatient, too. So in the interest of science, I’m running a little experiment, seeing if I can pick up Ruby on Rails without completely learning regular ol’ un-frameworked Ruby first. I’m learning as I go, and seeing how that works out. (I never could have done this before learning the aforementioned programming concepts, though, so if you don’t know them—and especially if you’re a right-brained designer-type like me—this is probably not the best way to go for you!)
Since I didn’t set myself down and read all (or even much) of Pick Axe II yet, there are (large) parts of Ruby that I don’t know off the top of my head, either. So I also used this as a chance to familiarize myself with the syntax —in a less theoretical way.
Variables: Where it’s At
For instance, I learned that in the line
@recipes = Recipe.find_all
@ signifies that
recipes is an instance variable. And for future reference, I learned that
@@ signifies a regular old class variable. (And Tobi over at Leetsoft points out that global variables start with
$. Ewww, globals!)
I already understood the rest of that line:
Recipe is an object based off of the Recipes class (which uses the Recipes model), and
find_all is one of the standard methods you’re able to use on such classes when you use Ruby on Rails’ ActiveRecord system. More on this later.
As you probably noticed, Ruby (not just Rails) has very lax rules when it comes to syntax. But without an explanation, you might not immediately realize how lax. (Hint: The answer is ‘very lax.’)
You don’t have to use semicolons—but you can. You don’t have to use parentheses—but you can. You don’t have to use curly braces on code blocks—although, of course, you can. Variables don’t start with
$, either, unless they’re globals—but they do sometimes start with
@ as we’ve seen.
I used to wrinkle my nose at code with so few constraints, especially the lack of variable signifiers (mmm, I like associating coding with
$$$!) in languages like Python and Ruby. But I was wrong, and perhaps just a tiny bit scarred by my PERL experience. But Ruby is gorgeous—spare like a Japanese tea room, as functional as a Zen studio. I want to marry Ruby and have its babies. But I have the feeling that a language like Ruby lives a life that resembles its syntax; I’m sure it’s not looking for that kind of emotional entanglement. Somehow, I soldier on.
What’s in a Table Name?
For the magic of ActiveRecord to work, you must name your database tables and columns according to specific rules. For example, when you create a table, Rails wants it to be plural. Not
stories. And it wants the
auto_increment primary key column to always be called
id, case sensitive.
And when you want to create a one-to-many foreign key relationship between, say,
authors (note the plural!) and
stories, you have to use a column
stories. The foreign key must be named in the format of:
Ruby Tongue, Rails Groove
My designer brain likes an overview of how everything fits together; if I can’t visualize it all dovetailing like floorboards or puzzle pieces, I have a hard as hell time coming up with a solid design for my programs. (And if I don’t do a design/architecture phase before coding, I feel the need to self-flagellate with printed and bound copies of PHPNuke. Oh, you laugh now, but you should try it sometime.)
Unfortunately, this kind of View from 10,000 Feet information is another thing that most tutorial authors don’t discuss.
Rails’ Super Model
One of the things that really made me drool over Rails to start with was its use of ActiveRecord. ActiveRecord is a really spifftastic tool that allows you to describe your database and its data (together known as your database model) in Ruby code, and instead of having to write the same kinds of stupid repetitive queries (“select name,category_id from articles where id=5″) over and over, allows you to access your data in a representative way, right there in the code.
So when you’re writing your data model files in the tutorial, and you write something like:
class Recipe < ActiveRecord::Base belongs_to :category end
What you're doing is, in effect, duplicating an Entity-Relationship Diagram (ERD) of your data in code. Which means you can then access the data as an object in Ruby, instead of writing stupid queries. (Of course there will be times when you have to write queries because of ActiveRecord's simplicity, but nevertheless! It's still so damned cool!)
Of course you have to following the naming schema that I talked about earlier in order to even use ActiveRecord in this way.
Scaffolding is Fun!
Scaffolding is a feature of Ruby on Rails that I hadn't really, really appreciated until I tried it out. To understand scaffolding, you have to understand some basics about database-backed development, for example CRUD. In case you're not familiar with this archetypical example of devgeek humor, CRUD is shorthand for Create/Retrieve/Update/Delete, and it describes most of the basic operations you'll run into when developing a database-backed app.
Since most apps are centered at least partially around CRUD operations, and Rails already uses ActiveRecord to look at the database and figure out relationships (assuming you're a good little boy or girl and name your tables and columns accordingly), the powers that be decided to just take it one step further and create a generic set of methods and views to enable you to do CRUD operations immediately with a single line of code (after you create your model, anyway).
All you have to do is, after having created your controller and your model, write the following line:
Models, Views, Controllers, Oh My!
Explaining MVC for the lay audience is something I'm not going to tackle right now, since I'm noticeably out of Mtn Dew Livewire and I'm scared of attempting to describe something as complex as design patterns without a little comfort from my chemical cohort. But I can at least make some useful (I think, anyway) points about the MVC-related file structure of Rails projects.
Update. I did tackle this project at some point! Be sure to read MVC: The Most Vexing Conundrum.
Rails is a real development framework. You run it the first time, and it creates a project folder for you, and in that project folder it creates another bunch of directories. One of the hallmarks of good code in web development scripting, especially in something like PHP, is an organized file structure. A file structure like that says to the third party viewer, "Hey, this person took the time to think out logically what files and components should go where, and they separated it out to make it easier for schmucks like me to understand. Cool."
The file structure Rails creates for you goes something like this:
app/ config/ db/ doc/ lib/ log/ public/ script/ test/ vendor/
app is another multi-tier directory, and inside you see the following:
app/ controllers/ helpers/ models/ views/
This is where you'll be doing most of your work. You create the database models in
models, your controllers for each model in
controllers (amazing!), and
views for controllers to use in, well, the eponymous location. Thanks to the data relationship information in a given model, you can access data from multiple models in a single controller, as long as it's all related; and then, the controller can call any number of views, as long as there is a view named the same as the function that wants to call it.
def list end
list.rhtml view will be called, if it exists. If it doesn't exist, ooh boy...
Rolling Your Own (Rails App)
Unfortunately, there doesn't seem to be an easy way to snag the scaffold code and mess with it. If there is, I'll find it soon, because I want to play with it and see what it looks like. Until then, if you want to go beyond the scaffold, you have to write all your own stuff from scratch. Luckily, that's not too difficult once you start grasping all the related concepts above and in the tutorial by Curt.
Stay Tuned... & In Touch
Because I'll be writing up more as I continue to learn and think about this stuff. If you have something particular you'd like me to write about, especially if it's in the realm of beginner information, leave a comment or pop by
#rubyonrails on the IRC network
irc.freenode.net and make some noise. My nick's