ActiveRecord: Overwriting attribute=

I always forget the command for doing this so I’m posting it here so I can find it easily.

If you want to overwrite accessors in rails (ActiveRecord), you will run into problems if you try to do it the same way you would with a regular Ruby object. For example, say you want to apply a transformation to an attribute as you assign it:

@person.name = 'ralph'

You always want name to be capitalized, so you would like to modify the name= method. With plain Ruby you would just do:

def name=(value)
@name = value.capitalize
end

You can’t do this with ActiveRecord, you will need to use a method named write_attribute so the method will look like:

def name=(value)
write_attribute(:name, value.capitalize)
end

There is also a read_attribute method to help with overwriting the read method on your attributes in ActiveRecord

Peepcode – It’s worth every penny

peepcode.png

Buying screencasts at Peepcode is worth every penny. The quality of the tutorials is superb. The topics they cover will increase your Rails development productivity, systems reliability, and overall maintainability.

Go check out the screencasts that are available and actually buy one. You won’t be sorry.

[Note: This is NOT an affiliate marketing promotion. I honestly love the work these guys produce.]

Simple Tutorials For Learning BDD and RSpec

Behavior Driven Development (BDD) is quickly grabbing attention of developers who are looking for a better way of developing applications. BDD revolves around the idea of writing specifications for your application, writing the API that your code will need to implement to meet the specifications, and then finally implementing the API to pass all of the specifications.

I used to be guilty of not writing good tests for the code that I developed. I found it difficult to really find the meaning of writing the tests. I knew it was a good practice and would alert me if I broke my code later on, but I had a hard time figuring out what types of tests to write, and which code I actually needed to write tests for. I think this is a problem that Dave Astels saw happening in the Test Driven Development (TDD) world. See his original post leading to BDD.

Behavior Driven Development has helped me begin writing practical tests for my code, and has helped me focus on the specifications of what my application should be fulfilling. It has really caused quite a shift in my thought process.

RSpec is a testing framework that facilitates BDD for Ruby. It makes the testing during the development process work for you. You write your tests first, watch them fail (because you haven’t yet implemented anything yet), and then implement the code and see it pass. It’s a wonderful process, and RSpec makes it fun.

rspec-tests.png

The above example shows some some results of some Ruby development I’m currently working on. I’m working on implementing a FamilyTreeApi client’s person method. You’ll see that you can read the tests and see what the specifications are of that particular method. The Green are specifications that the library is currently passing, and the yellow are not yet implemented.

Below is the actual test for the first specification of the client ‘person’ method description.

rspec-code.png

If you are interested in learning more about BDD and RSpec, I suggest going through the following tutorials:

One more interesting thing with RSpec. Ben Maybe has posted an article on using RSpec for your C code. This is way cool, being able to harness the power of RSpec while writing an application in C.

Has anyone else seen any other good BDD frameworks for other languages? How about more good tutorials? What has been your experience with BDD or TDD?

Programming Heroes – The Rails Core Team

Monsters Inc. is one of my favorite Pixar films. I love the slow-motion scene where the monsters are walking into the scare-portal room to begin work and the young intern monster says in his teenage voice, “Wow! They’re so awesome!” That’s how I feel about the core team behind Ruby on Rails.

I spent a little bit of time this week reading through the profiles on each of the core team members and found myself grateful for contributions that each of the members had made. Each one contributed something new and innovative to the web development community. Each one has made our work as developers hurt less.

David Heinemeier Hansson kicked it all off by sharing with the world his framework that he so ingeniously created while building Basecamp. He’s a true pioneer of the web who journeyed away from the comforts and frustrations of php to a marvelous yet-to-be-taken-seriously-on-the-web language of ruby. Ruby is now my weapon of choice, but I’m convinced that I would have never discovered it without rails.

Sam Stephenson and Thomas Fuchs have made building web interfaces fun. Sam is responsible for fixing Javascript with his Prototype.js framework. I used to hate ever doing anything with Javascript. Since discovering Prototype, I actually enjoy Javascript programming. Thomas developed the awesome script.aculo.us visual effects, controls, and ajax libraries. Script.aculo.us is built on top of the prototype.js. Script.aculo.us makes it possible to build cool Web 2.0 applications. These two libraries together are incredible.

Jamis Buck writes an awesome blog on rails tips and tricks. He’s the genius behind many Ruby libraries for web communication. He’s contributed some awesome libraries and plugins, including Capistrano. He graduated from BYU, my alma mater.

Finally, to everyone who has contributed to making our lives better, THANK YOU!

Why I Prefer Ruby on Rails over CakePHP

Last year, I had a goal to learn Ruby on Rails and build an application in that framework. By learning CakePHP, I was able to wrap my mind around the rails framework concepts and make that transition a little easier. This year, I have made the full plunge into the Ruby on Rails, and I absolutely love it. As I’ve made the transition from php to ruby and from CakePHP to Ruby On Rails, I’ve written down some of the reasons why I now use Ruby on Rails over CakePHP.

[note: I still prefer to use CakePHP over no framework if a client requests an application be written in php. However, when we have the option to start the project in Rails, we really push for rails.]

Here are some of the reasons why I prefer Ruby on Rails over CakePHP:

Rails doesn’t require you to grab all of your data in the controller

When working with CakePHP, you must retrieve all of your data from the database in the controller and pass it all to your View. All of this data is stored in an associative, which makes accessing your data very easy, but lacks the functionality of using an object.

All of the data that you will need from associated models must exist in the array(s) that you pass to your view. You can grab data from associated models this by using Cake’s recursive option which will grab all of the data in surrounding models.

Lets say that you have an Author that has many Articles, Articles have many Comments and you would like to grab the Author, her articles, and comments to give to the view. You would do this with the recursive option of 2 levels of data retrieval. However, lets say that the author also has many books and books have many chapters. When you do a recursive find on the author, it will grab all of the articles and comments, books and chapters. This leads to a lot of wasted data retrieval

With Rails, you can easily walk through the data models while your are in the view, and if the object doesn’t yet have that data, it will automatically query the database behind the scenes. This is a beautiful thing. So, in the controller, you only have to grab the author. In the view you can then walk the model in the following way:

author.articles.first.comments.first.email_address

Of course you can iterate through the articles and the comments, but you can continue to move to associated models all you want. Also, to save queries to the database, you can do an eager find and specify that you also want her articles so that the articles are also returned in that first query. That is super powerful!

Rails model objects allow for dynamic attributes

Lets say that you have a User model that has the attributes of a first_name, and last_name. When displaying this information, you often want to show the full name. You might just output the first name then the last name every time, but wouldn’t it be nice if you just had a full_name attribute? In rails you can do this by defining a new method named full_name on the User model which returns the formatted full name. In Cake you can’t do this because you only have an associative array.

Lets say that the users have an image associated with their record. The image path on the server can be derived by their user id and an image extension which is stored in the users table. The path would be /images/users/[id].[image_extension]. In Rails, you can define a method on the User model named image_location which returns the formatted path. In Cake, you would have to formulate the path inside the view every time you wish to display it.

Further, if the user had no image, you can check for that inside your image_location method for the image_extension and return a no_image.gif when appropriate. In Cake, you would have to wrap some logic around your image display inside your view which makes it much uglier and prone to bugs.

Rails Has Superior Url Routing

[UPDATE: Ben has just notified me that Cake has now added similar routing capabilities. See his comment.]

Rails has amazing routing capabilities. At first glance, it appears that Cake can do everything that Rails can do, but it can’t. One of the main differences is that Cake’s routing is a one-way routing. Another difference is the way that Cake handles parameters passed to the controller.

One-way routing

Cake’s routing is one way, meaning that you set up your routes in the configuration, and then you must remember your url structure and write the urls yourself throughout the application.

For example, if you are building a social application which features personal profiles. You decide to name your controller ‘Person’ and the action to view the profile ‘view’. Each person is identified by a unique id, so you decide to use the default routing in cake and rails which would give you a url of /person/view/33 for person #33.

Throughout your Rails application, you’ve linked to the personal profile pages by calling link_to(persons_name, :controller => 'person, :action => 'view', :id => persons_id). This builds a url using the default route /person/view/[id].

Throughout your Cake application, you’ve linked to the personal profile pages by calling echo $html->link($persons_name, "/person/view/".$persons_id); . This also gives you the same url: /person/view/[id].

Down the road, you realize that you would like to make your urls more friendly, and represent personal profile pages with a url like: /friend/[id].

In rails, your new route looks like this:

map.connect "friend/:id", :controller => 'person', :action => 'view'

In cake, your new route looks like this:

$Route->connect('/friend/*', array('controller' => 'person', 'action' => 'view'));

It appears that Cake can do everything that Rails can do, but what about all of your urls that you have scattered throughout your application. Rails will automatically write them to fit this new routing pattern. Cake makes you find all of your links and change them by hand.

Rails has two-way routing, where Cake’s routing is one-way.

Parameter handling

[Correction here: You can accomplish similar parameter handling capabilities with Cake. This becomes a null point. You can still concatenate a querystring to the end of the url and use $this->params[‘url’][‘param_name’] to retrieve your parameters].

Cake handles parameters on the url differently than rails. With Cake, your parameters are listed like so /find-person/[param1]/[param2]/[param3]/[etc.].

In your Cake controller, you accept the parameters like so:

function find_person($name, $city, $page)

The order in which they appear on the url determines which parameter they become in the action.

Rails checks to see if the parameter matches a url definition in its routes, and if it doesn’t fit there, it will append it to the end of the url in a querystring like so: /find-person/?name=x&city=Provo&page=3.

In your Rails controller, you would access the paramters like so:

def find_person
name = params[:name]
city = params[:city]
page = params[:page]

You might think that Cake’s way of handling the parameters is superior because it keeps the url looking prettier. However, this can be a real pain if you are writing an advanced search where any of your parameters can be optional. It’s also nice to be able to use a form with the method=GET for search. I don’t know of a way to do this in Cake. See the above message on how to do this in Cake.

There are still other reasons for using Rails over CakePHP, and there are some reasons why clients will still prefer to stick to php. What are some of the reasons you prefer CakePHP over Rails or Rails over CakePHP?

RadRails Error – No such file to load — rubygems (LoadError)

I’m using the Eclipse plug-in named RadRails to work on Rails projects. I’m running on Mac OS X, and I finally got past this error that would come up every time I tried to generate a Model, Controller, or anything for that matter:

No such file to load -- rubygems (LoadError)

Strange thing is, generating models, controllers, and such worked just fine from my bash shell, but not from within Eclipse. I thought it was something to do with my system PATH variable, but that was not the case.

The way to fix this error is to add ruby to your list of interpreters in:

Window => Preferences => Ruby => Installed Interpreters

Add an interpreter, name it Ruby, and give it the path to your ruby binary file. To find where that is located, just type which ruby from your shell prompt.

I hope this helps someone else. It took me a long time to find a solution for this.

Picking up Ruby on Rails after CakePHP

So, I’m finally diving into Ruby on Rails. The transition to Ruby on Rails from using CakePHP is going fairly smoothly. Now that I am really comfortable with the MVC framework that CakePHP uses, the learning curve has been pretty minimal.

My web hosting provider offers Ruby on Rails support, but I don’t like editing files directly on a server, so I decided to get things running locally on my own machine. It has been kind of a headache to get things working with FastCgi. Without FastCgi, everything runs pretty slow. With fcgi support, it runs really fast, which is nice. Just remember that you must restart Apache after you change your database.yml file.

If you want to start developing on Rails, I suggest following the WARR (Windows Apache Ruby on Rails) setup instructions. These instructions finally got my fcgi to work. You don’t have to put things in the directories that the tutorial suggests, especially if you are already set up with apache, mysql, etc.

If you want to learn some of the basics on Ruby, I suggest the following sites:

  • Try Ruby – This site lets you type ruby commands into a little console in the browser window. No installation needed, just a browser. Follow their tutorial! It gives a pretty good, quick run-through of Ruby programming principles.
  • Why’s (Poignant) Guide to Ruby – This is an online book that is an easy read.

If you’re looking for some good Rails tutorials check out:

If you really want a good understanding of Ruby on Rails, and Ruby, I suggest buying these books:

  • Agile Web Development with Rails – This is a good book whether you’re learning Rails or another inspired framework such as CakePHP. It was written by David Heinemeier Hansson, who is one of the master minds behind Rails and is on the 37Signals team. All parts of the MVC framework are discussed thoroughly in this book, and it has the best explanations for Model relationships such as Belongs To, Has One, Has and Belongs To Many. This book is awesome.
  • Programming Ruby – This is an in depth guide to Ruby programming. It covers the basics all the way to the advanced features such as distributing Ruby objects across several processes and servers, much like Java’s RMI or CORBA. It is written by Dave Thomas (not the Wendy’s guy) who is also a co-author of the Agile Web Development with Rails book.

So, now I’m off and running, or at least jogging, with Ruby on Rails. Ruby is a really cool programming language. A lot of stuff seems backwards from what I’m used to with languages such as Java or php, but the differences actually make Ruby super elegant. It will take me a while to become super proficient in it, but I’m on my way.

I’ve already noticed some differences between Ruby on Rails and CakePHP, which I’m taking note of. I’ll write again soon with a detailed comparison of CakePHP and Ruby on Rails.