Category Archives: Ruby on Rails

Intro to Story Runner and BDD

Ben Mabey just posted a really good deck of slides on Story Runner and Behavior Driven Development (BDD) from a recent Utah Ruby User Group meeting.

Don’t be overwhelmed by the 99 slides. It moves really fast, and walks you through the history and concept of BDD.

Perhaps my favorite concept from the slide show is “Design is a Process, not a Phase.” As I have embraced Behavior Driven Development, I have seen improved software design come from the process. I believe this is true because writing the specs help create a clean public interface for your objects and classes. By having the tests that verify the behavior of your code, you can easily refactor without the worry of unknowingly breaking desired behavior.

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

Blog posting to Google result in 20 minutes

Today I was looking for some xml matchers for RSpec so I googled ‘xml matchers rspec’, clicked on the first result, which happened to be exactly what I was looking for, and I posted a comment. After posting the comment, I realized that the post had only been up for 22 minutes! That is the fastest turnaround I’ve ever seen from blog post to Google results. Wow.

I was so amazed that I took some screenshots:

google_search.png

wolfman_blog_post.png

Anyways, if you’re into RSpec and doing much with XML document creation, his matchers seem to be a great way to verify that your documents are being created correctly. Thank you.

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?