30 Days of Rails

If you haven’t noticed, I am a .net developer but I was inspired today by Matt Cutt’s TED talk to start a 30-day project.  I highly recommend watching it; it might inspire you too.

 

So I have decided to spend 30 days with Ruby on Rails and blog it right here. Stay tuned for a daily post on rails, it will be fun.  I am starting my journey with TekPub’s Rails 3 production at http://tekpub.com/view/rails3/1

Ruby on Rails Crumbs – Part 1

If you have been following along, I blogged previously about my experience trying Ruby on Rails as a .net developer (here and here).  I quickly realized how different things are and that I desperately need some help, so I got myself the beta PDF version of Agile Web Development with Rails and Rails Recipes.  Both great books but not Rails Recipes doesn’t cover rails latest version – 2.0. 

As I read through these books, I realized there are lots of things I need to keep track of, that is lots of crumbs.  This series of blog posts are a way for me to keep track of these crumbs as well as share them with others.  I don’t plan to explain everything in detail (because I can’t).  This is more of a quick reference to remind me of features and things that I read about in the books because there is no FREAKING INTELLISENSE in rails.  You will realize how valuable Intellisense is when you don’t have it.

These crumbs are not in any specific order.  For the most part, they are in the order I discovered them.

content_tag

Use it to surround a block of text with a tag.  The code below creates <b>make me bold</b>

content_tag (:b, “make me bold”)

&block

I can’t find a good explanation of this but when you call a method from your views like this

<% my_foo() do %>
  [content]
<% end %>

And the method is defined like this

def my_foo(&block)
end

Then the &block parameter will contain all the text that is wrapped by this method in the view.  In the above example &block would contain [content]

blind_down

Use to generate a blind down effect in JavaScript to make hiding an element smoother than just setting display to none.  In you rjs template, write:

page[:element_id_to_blind].visual_effect :blind_down

request.xhr?

This returns true if the request is xhr i.e. an AJAX request.  I like the trailing question mark.  In .net, it would be named IsXhr.

has_many

Use in your model to create a relationship.  For example, an article model class might look like this

class Article < ActiveRecord::Base
has_many :categories
end

NOTE: your category model class name is Category but the has_many uses the actual table name which categories.  This is so weird for me – no compiler errors, no warnings, nothing.  I know, I know, convention over configuration.

belongs_to

Same idea as has_many but in reverse, so the category model class would look like this

class Category < ActiveRecord::Base
belongs_to :articles
end

button_to

A helper method that generates an HTML form containing a button that submits to a URL when clicked.  For example:

button_to “Edit”, :action => ‘edit’, :id => 3

Creates a form with an Edit button that submits to the edit action and pass 3 as an id parameter.  If we were editing an article, the generated html looks like this:

<form class=”button-to” action=”/articles/edit/3″ method=”post”>
    <div><input type=”submit” value=”Edit” /></div>
</form>

More crumbs to come – stay tuned.  Also feel free to add your own crumbs to the comments, it might help someone.

Ruby on Rails for a .NET Developer – Part 2

Ok, so I thought the whole scaffolding thing was so easy and I would be done in a few minutes. I was so wrong. Nothing seemed to work right. I would call ruby script/generate scaffold Tag and it will generate all the files but the views were empty. Hmm… This is exactly what has been done in all the demos and tutorials. Apparently, things have changed in Rails 2.0 and I had to call this instead script/generate scaffold Tag tag:string.

One thing I don’t like so far is the lack of good documentation for Rails 2.0 and there aren’t any books out there. I went ahead and bought me of Agile Web Development with Rails which has been updated for 2.0 but you can only get as beta from The Pragmatic Bookshelf. I bought the PDF version and have been reading it for the past few days.

It occurred to me that before I can get too deep into Rails, I need to learn a little about Ruby. After all the syntax is very different from C# or vb.net. Everyone claims that it is an easier language to understand but I think that is very subjective. Spanish might be easier than Chinese but if you are Chinese you might not think so.

With that said, in this post I am going to list a few things I have learned over the past few days about Ruby Syntax and how it compares to C# syntax.

Comments

C#

//this is a one line comment

/* This is a multi-line
comment
*/

Ruby

# this is a one line comment

=begin
this is a mult-line
comment
=end

Winner: C#

Class Definition

C#

class Car : Vehicle
{
public Car()
{
}
}

Ruby

class Car < Vehicle
def initialize
end
end

Winner: tie but if you hate curly brackets then Ruby wins

Method Definition

C#

public int GetYear()
{
}

public static int GetYear(string carName)
{
}

Ruby

def GetYear
end

def self.GetYear(carName)
end

Note: You can use the class name instead of self to make the method static. Also, in Ruby they are called class methods and not static methods. Come to think of it, that makes sense, since the method is defined for the class and not the instance or the object.

Winner: Ruby

Variables

Local variables

C#

int aNumber = 4; //declared inside a method

Ruby

aNumber=4 # no declaration needed just use it inside a method

Instance variables (fields)

C#

int aNumber; //declared inside a class not a method

Ruby

@aNumber #no declaration needed just use it anywhere

Static variables (fields)

C#

static int aNumber; //declared inside a class not a method

Ruby

@@aNumber #no declaration needed just it anywhere

Control Structure

if

C#

if (aCondition)
{
}
else
{
}

Ruby

if aCondition then
else
end

unless

C#

There is no unless in C# but the same logic can be written like this:

if (!aCondition)
{
}
else
{
}

Ruby

unless isBlue

else

end

case

C#

switch (year)
{
case 1960:
case 1961:
case 1962:

case 1969:
break;
case 1970:

case 1979:
break;
default:
}

The code above has been truncated for brevity because you cannot do ranges in C# as easy you can in Ruby

Ruby

case year
when 1960 .. 1969
when 1970 .. 1979
else
end

The above Ruby code is complete and not truncated. The express 1960 .. 1969 specifies a range.

while

C#

while (aCondition)
{
}

Ruby

while aCondition
end

until

C#

There is no until in C# but the same logic can be expressed like this:

while (!aCondition)
{
}

Ruby

until aCondition
end

This is not a comparison of language features, it is just a comparison of the syntactical differences of *some* of both languages. This is *not* an exhaustive list and is not meant to be – a simple Google search will get you thousands of pages of syntax goodies for either language.

So far, I can’t say I love Ruby’s syntax but if I were new to programming, I would say it looks more readable and easier to understand. Being a C#/VB developer for so long, I am a little confused and uncomfortable with the Ruby syntax. But, the facts that I have used VB for the past 10 or so years and that I hate semi-colons and curly brackets in C#, it is not that bad.

Ruby on Rails for a .NET Developer – Part 1

Looking at my blog or resume, you will immediately know that I am a .net developer and my entire programming career has been Microsoft-centric.  I have been wanting to play with Ruby on Rails due to its inescapable popularity and I was actually surprised to learn that the language itself (Ruby) was developed in the early 90′s…  So it’s not really new.  Ruby on Rails is a framework that sits on top of it…

NOTE: forgive me if any of this is wrong, my RoR experience as of right now is 35 minutes…

Anyway, this post is not about the history of Ruby or a comparative analysis of which language or platform is better…  It is just a part of a series of blog posts that I will be writing as I learn more about RoR.  Everything is written from my perspective i.e. a 100% windows user and a .net developer.  So I am in foreign lands here.

The Setup

My current setup is a Mac Mini running Leopard with

(null)

The Environment

So after downloading all the RoR stuff from this website, I followed the steps and managed to create an empty application like this:

  1. Open a terminal window 
  2. Run rails /users/emad/code/favewares
  3. Run cd path/to/your/new/application
  4. Run ruby script/server

Then I opened http://localhost:3000 in my browser and got to the welcome page shown below.

RoR Welcome aboard

Time to create the database, so I had to go download MySQL and install it which was surprisingly very straight forward:

  1. Double click the MySQL installer
  2. Double click the MySQL Startup Item installer

Then I ran into problems trying to get things going and quickly realized that being a windows user, I needed a GUI tool.  So I downloaded one from the MySQL website and installed it which was also pretty straight forward.  Until I tried to connect and got the error message “Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock’ (2)”

mysql connection error

After about an hour of trying different things and reading all sort of blogs and forums, I finally decided to restart my mac and voila, it worked…  At least Windows tells me that I need to restart.

Ok, so I got the GUI MySQL administrator up.  I added a database called favewares_development (to follow RoR naming conventions) and created some tables.

mysql administrator

If you read anything about Rails you will end up reading the phrase “convention over configuration” a bazillion times; so here is a quick note on database naming conventions:

  1. Database name = appname_development, appname_test, appname_production
  2. Table name = plural e.g. authors, wares, stories, categories, etc…
  3. Primary key name = id
  4. Foreign keys = singularOfForeign_id e.g. category_id, author_id, etc…
  5. Many to many tables = tablea_tableb in alphabetical order e.g. items_orders, classes_students

There is more information about Rails and Ruby naming conventions over here.

Database is now created, let’s edit the code.  Oops, no code editor – damn it.  I went to textmate and downloaded their 30-day trial.

Once I was done creating my tables, I generated the schema.rb file in the project’s db folder in textmate by clicking Bundles > Ruby on Rails > Database > Dump DB to schema.rb

Dumb db to schema.rb

My scheam.rb file looked like this:

schema.rb

Although I didn’t really have much so far, my brain had had enough of being outside its comfort zone – I miss windows… 

Stay tuned for the next part of this post.

[update] Part 2 is available here.