Monday, January 14, 2008

How to stop blogger inserting <br />

The default behavior of blogger is to insert <by /> for all line breaks when publishing posts. It does this even if you chose to edit in html. If this is annoying you and causing your blog to look a bit messed up, you can stop it by changing the 'Settings->Formatting->Convert line breaks" option in the blog panel.

Sunday, January 13, 2008

Ruby single/double quotes

Both single and double quotes can be used for string. The difference is in the way they are interpreted. Double quotes are 'interpreted more'. That is to say the parser will look at them and replace escape characters with newlines, insert variables etc.

Single quotes

Single quotes only support the escape sequences

  • \' - single quote
  • \ - single backslash

If you have a phrase were this would create confusion, making the code difficult to read you choose a different delimiter using %q :

 puts %q!c:\napolean's documents\tomorrow's bus schedule.txt!
puts %q/c:\napolean's documents\tomorrow's bus schedule.txt/
puts %q^c:\napolean's documents\tomorrow's bus schedule.txt^
puts %q(c:\napolean's documents\tomorrow's bus schedule.txt)
puts %q{c:\napolean's documents\tomorrow's bus schedule.txt}
See the ruby programming wiki.

Double quotes

Double quotes support many more escape sequences and you can use these to substitute variables into strings:

puts "Enter name"
name = gets.chomp
puts "Your name is #{name}"

For more control sequences see the strings page of the ruby programming wiki. You can also do a similar trick to the above using %Q.

Saturday, January 12, 2008

Rails Routing

When a user clicks on a link the url eg (http://www.mysite.com/users/show/12) is sent by the browser to the rails server (eg. webrick/mongrel). The server then looks at then looks at the routes file to work out which controller to send it to. The request is then dispatched to the controller which manages requesting the data from the model and sending it to the view to display. For a much better explanation (with picture) see BetterExplained (a brilliant little site well worth investigating). So, in the routes file (/config/routes.rb) are instructions that tell the server how to turn urls into controllers and actions. The server will start at the top of the file and work down until it finds an instruction that works. If you look in the file you will find the instructions look a bit like
map.connect ':controller/:action/:id'
What will this do? The argument after the map.connect tells the server a string to match and what to call the bits it matches. Here when the server receives "http://www.mysite.com/user/show/12" it first strips off the web address and so is left with "user/show/12". It will then look at this rule and match the form and asign the string 'user' to :controller, 'new' to :action and '12' to :id. It will then call the 'user' controller with the 'new' action and id = 12. This is a pretty basic rule. How about this one:
 map.connect 'date/:year/:month/:day', :controller => 'blog', :action => 'display_date' 
this would match "www.mysite.com/date/2008/1/1" to the 'display_date' method of the 'blog' controller with :year => 2008, :month => 1, :day => 1. To specify that some of the match pattern is optional (to match www.mysite.com/date/2008) say, you can add
 :month =>nil, :day=>nil 
to the rule. To stop too much matching (eg to stop the above matching www.mysite.com/date/latest ) you can add
 :requirements => {:year => /\d{4}/, :month => /\d{1,2}/, :day => /\d{1,2}/} 
This allows you to use the full power of regular expressions when matching. To add a default eg
 map.connect 'posts/:category', :controller => 'blog', :action => 'posts', :category => :all 
At first glance there doesn't seem much point to doing this as :category could default to :all in the controller. However the payoff comes when 'going backwards' using link_to and url_for. If you didn't have the default set you would have to write
 link_to 'Posts', :controller => 'blog', :action => 'posts', :category => :all 
and also "all" would be displayed at the end of the url in the browser. In the link_to syntax the first argument is the name to call the link (ie the link as shown to the user) and the rest of the arguments the stuff necessary to match to a url by looking in the routes.rb file. For more explanation of the above (where I copied the examples from :p ) see the rubyonrails manual Remember that the server starts at the top and works down so that rules at the top have higher precedence. See here for a deeper look at what's going on. Note "map.root" is equivalent to "map.connect ' ', :controller => 'index', :action => 'index' " (I think).

Using rails for a static site

I wanted to add an index and about page to my site but avoid repeating the overall page design stored in app/views/layouts/application.html.erb. I found the basic idea on Robert Evans' site. The application.html.erb file is what the rails routing machine falls back on as a default template if it doesn't find one of the same name as the controller.

  1. Create a new controller to manage the pages. At the control line (positioned within your application folder) enter:
    script/generate controller static index about
    The script/generate contoller bit tells rails to create the controller file (app/controllers/static_controller.rb) and the associated views folder (app/views/static/) . The next argument (static) is the name of the controller to be created. The final arguments (index, about) are optional and tell rails to create methods of those names in the controller file and the appropriate files in the views folder (eg. app/views/static/index.html.erb).
  2. Edit the view files to contain the required content
  3. You can customise parts of application.erb.html for example create a custom title by changing the title line in the header to
    <title>YourSiteName <%= @page_title if @page_title %></title>
    
    and modifying the methods in the controller file to
    def index
        @page_title = "Home"
    end
  4. Add the following to the "config/routes.rb" file
    map.root :controller => 'static', :action => 'index'
  5. Refer to the pages using
    link_to :controller => 'static', :action => 'index'
    link_to :controller => 'static, :action => 'about'

Friday, January 11, 2008

2: Downloading and installing Ruby and Rails

I'm not going to talk about this as it is covered very well here (macs) or you can google it. You will also need some sort of text editor. I am currently using textmate (only for macs), which seems good to me. There are lots of good open source (free) text editors around. I'm afraid I can't say much more about any of them. It's good to find one that will do ruby syntax highlighting if you can. Maybe also look here. When starting out I did try aptana studio but didn't have much luck. It is more an IDE than text editor and as such seemed to want to do a lot of things for me. To be honest I didn't really give it a chance but on the whole I think it is better to go for simple text editor when you're first learning as it seems to make the procedure more transparent.

1: About Ruby & Rails

Ruby is a programming language. Some people who know about these sorts of things seem to think it is nice. It is a high level programming language which from a practical point of view means it can do a lot of smart things. It is also an interpreted language (like php) which means that it is parsed in real time. This makes it slower than languages such as C. However as computer speed is constantly improving most code is not speed critical and the time you save in development and testing easily justifies using higher level languages. These facts are not particularly important. As far as learning ruby for the purpose of rails goes, at first at least, you'll pick up most of the syntax as you go along. For a neat introduction to ruby (allows you to try it out in your browser) see here. This is not really necessary to get going with rails though. Rails is a web framework. Basically rails allows you to use the ruby language to create websites. It will create the framework for your application automatically including basic forms, view pages etc. It integrates with a database in a natural way and also has facilities to maintain the database, distribute your application on different servers, manage updates and different versions and testing capabilities. Tis good. Anyhow all you need to know is that it will make your life much easier. There are lots of 'discussions' on various bulletin boards between rails fans and rails haters about how rails is/isn't flawed etc. Rails is an 'opinionated' system and prides itself on not trying to be everything to everyone. It emphasises convention over configuration. This means it likes you to do things in certain ways (and maybe restricts you from doing some things), which seems to annoy some people (!). However, these ways seem to be well thought out and on the whole lead to easily maintainable applications which are easily understood by other rails programmers. Which seems a good trade-off to me. If you are worrying about this I probably wouldn't bother.

0: About this tutorial

This is a tutorial to describe how to build a web application using the Ruby on Rails framework. It is written for Rails 2.0 which was released on 7th December 2008. I started learning rails shortly after motivated and had problems finding tutorials that still worked as it seems significant changes were made in the 2.0 version. This tutorial aims to record simply what I learned as well as some of the resources I found useful.