Saturday 30 March 2013

Ruby on Rails


For years I have been building applications using C#. In recent years I have taken a keen interest in Ruby and Rails. I thought that I would blog about how to get started, to make it easier for me to remember. Hopefully you get a kick out of it.

Background


Ruby on Rails emphasises the use of well-known software engineering patterns and principles, such as active record pattern, convention over configuration, don't repeat yourself and model-view-controller.

Active Record Pattern


Active record is an approach to accessing data in a database. A database table or view is wrapped into a class. Thus, an object instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save. Any object loaded gets its information from the database. When an object is updated the corresponding row in the table is also updated. The wrapper class implements accessor methods or properties for each column in the table or view.

Convention Over Configuration


Convention over configuration is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility.


Don't Repeat Yourself


In software engineering, don't repeat yourself (DRY) is a principle of software development aimed at reducing repetition of information of all kinds, especially useful in multi-tier architectures. The DRY principle is stated as "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system."


Model–View–Controller


Model–view–controller (MVC) is a software architecture pattern which separates the representation of information from the user's interaction with it.


  1. A controller can send commands to its associated view to change the view's presentation of the model (e.g., by scrolling through a document). It can also send commands to the model to update the model's state (e.g., editing a document).
  2. A model notifies its associated views and controllers when there has been a change in its state. This notification allows the views to produce updated output, and the controllers to change the available set of commands. A passive implementation of MVC omits these notifications, because the application does not require them or the software platform does not support them.
  3. A view requests from the model the information that it needs to generate an output representation.





Getting Started


To get started is very easy. Perform the following steps:
  • Install rails by running gem install rail.
  • Run rails new <application_name> -T. The -T option means [--skip-test-unit] # Skip Test::Unit files
  • Go to the application that you created cd <application_name
  • Edit your Gemfile and add the following to the file:
    group :development do
    gem 'rspec-rails'
    end
  • Since I don't like plain old HTML I prefer to use Slim. To make sure rails uses this template engine add the following to your Gemfile gem "slim-rails"
  • Make sure now you run bundle install to make sure your new gem is up
  • To get RSpec run the following command rails generate rspec:install
  • Run rails server and go to http://localhost:3000/ to make sure everything is ruinning
  • Once you are happy lets get it in version control:
  • Run git init .
  • Run git add -A
  • Run git commit -m "Initial commit”

How easy was that.

Scaffolding


Rails uses the concept of scaffolding. Think of it as a way to generate some code for us. To get started we can create a new Post model
  • rails generate scaffold Post name:string title:string content:text. This is such a powerful command as it goes and creates a new model, view, controller, specs and a db migration.
  • To make sure we create a the data in the database lets run the migration run rake db:migrate
  • Lets make sure that it all works by running rails server
  • Go to http://127.0.0.1:3000/posts and play around with it
How easy was that to create a new Post model that has a view, controller that saves to the database.


Testing



As anyone that knows me knows I am a huge advocate of Behaviour Driven Development. The thing I love about ruby is that it makes it so easy. So let's write a test. Open up post_spec.rb and add this test


it 'should not save post without title' do
    post = Post.new
    expect(post.save).should be_false
end


To implement the solution we will add the following to the Post model and add


validates :title, :presence => true


Pretty easy, for more information please look at this excellent guide on testing.


Configuration



Configuration in rails is done through code and using YAML files. In your rails application all configuration is stored in the config folder. The most common configuration that you will deal with is:
  • config/application.rb – Contains all the application configuration. Rather than putting everything in this file it is recommended to add all of your changes to config/initializers folder
  • config/environments/* - Contains environment specific configuration. This configuration takes precedence to the application configuration.
For more information on configuration, this guide will help you out.Migrations


Rails abstracts the database nicely by introducing us to a concept of migrations. Think of it as a way to version your database. When you generate a model by running:


rails generate model Product name:string description:text


Rails will create a file under the db/migrations folder. This migration will look like:


class CreateProducts < ActiveRecord::Migration
   def change
     create_table :products do |t|
        t.string :name
        t.text :description
        t.timestamps
     end
  end
end


This is just a template and it is encouraged that you change it. As you should be thinking about the queries that you will be making against this model.


More information on migrations can be found here.

Asset Pipeline



The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages such as CoffeeScript, Sass and ERB.



The asset pipeline is a great idea. As backend developers we have taken this sort of thing for granted. This pipeline will allow us to work with JavaScript and CSS in a consistent way. So how does it work?



Well everything for the asset pipeline is stored under app/assets. The convention is that if the file starts with application all of your common assets will be loaded in that file. All of the assets are managed with a gem called sprockets. The format is as follows //= require sub/something, this is like the require statement in ruby. This allows you to manage all the dependencies for JavaScript and CSS.


Another cool aspect is that this pipeline allows you to chain different technologies together. For example if you wanted to use CoffeeScript you would name your file something.js.coffee and include the coffee-rails gem, now the asset pipeline will allow you to write all of you front end in CoffeScript. How cool is that?


For more information I recommend reading the official info on the asset pipeline.

Final Thoughts



This is just a basic introduction to the platform. As you can see Ruby on Rails is a fantastic platform. However realise that it is very opinionated, which is not a bad thing. What I love about rails is how easy it is to get going and testing is not an after thought. There is a lot more to rails which I will explore by writing an application that allows me to explore the concepts of lean projects.


To learn more about rails I recommend looking into the online guides and read the best book on the subject Agile Web Development with Rails (4th edition).

No comments:

Post a Comment