<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <title>MagnionLabs.com - Blog</title>
  <id>tag:www.magnionlabs.com,2010:mephisto/blog</id>
  <generator version="0.8.0" uri="http://mephistoblog.com">Mephisto Drax</generator>
  <link href="http://www.magnionlabs.com/feed/blog/atom.xml" rel="self" type="application/atom+xml"/>
  <link href="http://www.magnionlabs.com/blog" rel="alternate" type="text/html"/>
  <updated>2009-11-30T14:01:18Z</updated>
  <entry xml:base="http://www.magnionlabs.com/">
    <author>
      <name>akmathur</name>
    </author>
    <id>tag:www.magnionlabs.com,2009-11-29:52</id>
    <published>2009-11-29T14:00:00Z</published>
    <updated>2009-11-30T14:01:18Z</updated>
    <category term="Blog"/>
    <category term="Web Application Development"/>
    <link href="http://www.magnionlabs.com/2009/11/29/rails-testing-101" rel="alternate" type="text/html"/>
    <title>Rails testing 101</title>
<summary type="html">&lt;p&gt;From my completely unscientific survey, it appears a lot of people have still not taken to writing tests for their Rails projects. Mostly because either they don&#8217;t know why and how much they should be testing or unfortunately, because they feel overwhelmed by the myriad options: Should I checkout Rspec? or may be Shoulda? what is autotest? Should I learn about mocks and stubs first?&lt;/p&gt;


	&lt;p&gt;If you are one of those feeling overwhelmed, firstly, don&#8217;t feel bad. Here&#8217;s a guide about why, what and how of testing for the completely uninitiated. Simplified, especially for you. (The rest of you can scroll over to the next article please).&lt;/p&gt;


	&lt;p&gt;I will use the Test::Unit framework that comes built-in with Rails and at the end, cover all the other options available.&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;From my completely unscientific survey, it appears a lot of people have still not taken to writing tests for their Rails projects. Mostly because either they don&#8217;t know why and how much they should be testing or unfortunately, because they feel overwhelmed by the myriad options: Should I checkout Rspec? or may be Shoulda? what is autotest? Should I learn about mocks and stubs first?&lt;/p&gt;


	&lt;p&gt;If you are one of those feeling overwhelmed, firstly, don&#8217;t feel bad. Here&#8217;s a guide about why, what and how of testing for the completely uninitiated. Simplified, especially for you. (The rest of you can scroll over to the next article please).&lt;/p&gt;


	&lt;p&gt;I will use the Test::Unit framework that comes built-in with Rails and at the end, cover all the other options available.&lt;/p&gt;
&lt;blockquote&gt;
		&lt;p&gt;However beautiful the strategy, you should occasionally look at the results. &#8212;&lt;strong&gt;Sir Winston Churchill&lt;/strong&gt;&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;h2&gt;As promised, firstly, the whys&lt;/h2&gt;


	&lt;p&gt;As you probably know by now, Ruby is an interpreted language and along with
the upside of faster development cycle, there is a downside of not having a
compiler: there is no syntax or type checking after you write the
code. Executing the code is the only way to know if its valid and tests are a
great way to execute code.&lt;/p&gt;


	&lt;p&gt;Tests also provide you a guarantee against any regression in your code. If you
have ever added a &#8220;feature&#8221; which broke something which was always working in
the past, you know what regression is. Tests allow you to guard against such
breaking changes.&lt;/p&gt;


	&lt;h2&gt;A gentle introduction&lt;/h2&gt;


	&lt;p&gt;If you have been testing your app through the browser (of course you do, silly
me) or by trying things out in the console, writing test takes only a little
bit more effort than that. Writing tests basically automates your steps and
thus saves your from repeating the same steps in the browser or console,
later. If you have never tried testing your Rails app, this is how you should
start:&lt;/p&gt;


	&lt;p&gt;First, prepare your test database:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
$ RAILS_ENV=test rake db:create 
$ rake db:test:prepare

&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Next, write some fixtures: Fixtures are the initial contents of the test
database, before a test runs. Just like you keep some data in your development
database while you are testing your app through the browser, fixtures are a
way to populate some seed data in the test database. Rails automatically
creates a fixture file for each model in your project.&lt;/p&gt;


	&lt;p&gt;Let&#8217;s say you are building a bug tracking system where you have a model called
Ticket. The fixture file for Ticket should contain an entry for each row that
we want to insert into the database. Following fixture file has two
entries. Each entry is given a name. the name is significant while setting
associations.&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
# fixture for Ticket
# file: test/fixtures/tickets.yml
bug_filed_by_john_customer:
  title: &quot;Signup form does not retain previously filled data on user error&quot; 
  description: &quot;some more explanation here&quot; 
  type: &quot;bug&quot; 
  state: &quot;open&quot; 
mary_managers_question:
  title: &quot;How can I change the color of the shirt once it has been added to the cart &quot; 
  description: &quot;I want to ...&quot; 
  type: &quot;question&quot; 
  state: &quot;assigned&quot; 

&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Fixtures are as simple as they seem &#8211; each of these records gets loaded as
rows in the table. There is just one thing to learn here: do not initialize
the id columns and if you have associations, the names you have given to the
rows can be used to fill in the foreign key columns. e.g. suppose, you also
have a Update model which captures updates on tickets by different users.&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
# fixture for Update
# file: test/fixtures/updates.yml
question_by_peter_developer:
  ticket: bug_filed_by_john_customer
  description: &quot;please provide steps to reproduce&quot; 

response_by_john_customer:
  ticket: bug_filed_by_john_customer
  description: &quot;here's how you can see the problem for yourself ...&quot; 

&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;So, specifying the row&#8217;s name (&lt;code&gt;bug_filed_by_john_customer&lt;/code&gt;) would populate
the foreign key (&lt;code&gt;ticket_id&lt;/code&gt;) in updates table correctly.&lt;/p&gt;


	&lt;h2&gt;Various types of tests&lt;/h2&gt;


	&lt;p&gt;Rails recommends that you divide you tests into three categories. Unit tests,
which test your models; Functional tests, which test controllers and
integration tests, which tests almost the whole application end to end. We
will learn about all of these.&lt;/p&gt;


	&lt;p&gt;In the directory test/unit you would find a file corresponding to each model and similarly in test/functional a file for each controller.&lt;/p&gt;


	&lt;h3&gt;Unit tests&lt;/h3&gt;


	&lt;p&gt;Writing unit tests in very similar to trying out stuff in Rails
console. Continuing with our example, let&#8217;s say the Ticket model is defined
like this:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;

# file: app/models/ticket.rb
class Ticket &amp;lt; ActiveRecord::Base
  has_many :updates
  validates_presence_of :title
  validates_presence_of :description
  validates_inclusion_of :type, :in =&amp;gt; %(bug enhancement question)
  validates_inclusion_of :state, :in =&amp;gt; %(open in_progress not_reproducible closed)
end

&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;You should be testing all the code you have added, like the validations above.&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
# file: test/unit/ticket.rb
class TicketTest &amp;lt; ActiveSupport::TestCase
  test &quot;should have title and description&quot; do
    ticket = Ticket.new
    assert !ticket.valid?

    ticket = Ticket.new(:title =&amp;gt; &quot;some title&quot;, :description =&amp;gt; &quot;some desc&quot;)
    assert ticket.valid?
  end
end

&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Then run the test:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
$ rake test

&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;You can of course use the data that you have put into the database through
fixtures. Suppose, your model code put restriction that you couldn&#8217;t have two
tickets with the same title:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
  test &quot;each title should be unique&quot; do 
    ticket = Ticket.new(:title =&amp;gt; tickets(:bug_filed_by_john).title)
    assert !ticket.valid?
  end

&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;As in this test, you can access the models loaded by the fixtures as: table_name(:fixture_name).&lt;/p&gt;


	&lt;p&gt;While writing code and trying it out, you should add a test whenever you discover a bug. Suppose you got a customer complaint and figured description should be made into a text column rather than a string so that it can hold more than 255 characters. It would be a good idea to create a test for that. It guards against description ever being made into a string again.&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
test &quot;description can be longer than 255 chars&quot; do
  ticket = Ticket.new(:title =&amp;gt; &quot;some title&quot;, :description =&amp;gt; &quot;a&quot; x 500)
  assert_not_raised ticket.save!
  assert_equal 500, ticket.description.size
end

&lt;/code&gt;&lt;/pre&gt;

There are a number of such assert functions. Here&#8217;s a list of the useful ones:
	&lt;ul&gt;
	&lt;li&gt;assert(boolean, &#8220;optional message&#8221;)&lt;/li&gt;
		&lt;li&gt;assert_equal, assert_not_equal&lt;/li&gt;
		&lt;li&gt;assert_match, assert_no_match&lt;/li&gt;
		&lt;li&gt;assert_nil, assert_not_nil&lt;/li&gt;
		&lt;li&gt;assert_raised, assert_nothing_raised&lt;/li&gt;
		&lt;li&gt;assert_valid(ar_object) # calls valid? on the ar_object&lt;/li&gt;
		&lt;li&gt;flunk(&#8220;message&#8221;) # always fails&lt;/li&gt;
		&lt;li&gt;assert_difference &#8216;expr&#8217; do &#8230; end, assert_no_difference&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;Since tests are normal Ruby code, you can use usual techniques to organize your test code eg. Loops, separating out common pieces in a function, etc.&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
test &quot;ticket when created should have a correct type&quot; do
  valid_types = %(bug question enhancement)
  invalid_types = %(not_reproducible incomplete)

  valid_types.each do |valid_type|
    t = Ticket.new(:title =&amp;gt; &quot;some title&quot;, :type =&amp;gt; &quot;valid_type&quot;)
    assert_valid t
  end
end

&lt;/code&gt;&lt;/pre&gt;

	&lt;h3&gt;Functional tests&lt;/h3&gt;


	&lt;p&gt;Functional tests are meant to test controllers. Since, you have already tested the models in unit tests, you should focus on test only the logic that&#8217;s present in the controllers. For example, here&#8217;s a sample functional test:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
# file: test/functional/tickets
test &quot;access should be restricted to only logged in users&quot; do
  get :show, { :id =&amp;gt; tickets(:bug_filed_by_john).id }
  assert_redirect_to login_path
  assert_equal &quot;Please login&quot;, flash[:notice]
end

&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;As you can see, functional tests give you a method called get (also post, put, head and delete) using which you can simulate a web request to an action. Then, use the assert methods to check up the response. On top of what you saw with unit tests, functional tests also have these additional asserts:
assert_response
assert_redirected_to
assert_template&lt;/p&gt;


	&lt;p&gt;For the most part, views are not tested here. You can test them (see assert_select) but it can get cumbersome.&lt;/p&gt;


	&lt;h3&gt;Integration tests&lt;/h3&gt;


	&lt;p&gt;Integration tests simulate a continuous session between one or more virtual users and our application. It gets the closest to how the application will be used in production.&lt;/p&gt;


	&lt;p&gt;In integration tests, you can send in requests, monitor responses, follow redirects, and so on. Ideally, a integration is something your customer should be able to understand &#8211; there are no models and controller and other internal details.&lt;/p&gt;


	&lt;p&gt;Instead of using the Rails build in integration tests, you can use &lt;a href=&quot;http://github.com/brynary/webrat&quot;&gt;webrat&lt;/a&gt; to make writing the tests lot more easier as it lets you describe a test in pretty much the same steps as you would do things with a browser.&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
$ sudo gem install webrat

&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;In test/test_helper.rb, right at the end of the file, add this:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
require &quot;webrat&quot; 
Webrat.configure do |config|
  config.mode = :rails
end

&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Rails does not generate any integration test skeleton automatically. So, use the generator:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
$ ruby script/generate integration_test ticket_life_cycle

&lt;/code&gt;&lt;/pre&gt;

&lt;pre&gt;&lt;code&gt;
# file: test/integration/ticket_life_cycle_test.rb
  test &quot;ticket life cycle&quot; do
    # a users signs in
    visit new_session_path
    fill_in &quot;Email&quot;, :with =&amp;gt; &quot;john@customer.com&quot; 
    fill_in &quot;Password&quot;, :with =&amp;gt; &quot;john's password&quot; 
    click_button 'Sign in'
    assert_redirected_to tickets_path

    # creates a new ticket
    visit new_ticket_path
    fill_in &quot;title&quot;, &quot;new problem...&quot; 
    fill_in &quot;description&quot;, &quot;some description about it...&quot; 
    click_button 'Save'

    # someone adds an update to that and marks it fixed

    # customer adds another update that it works

    # engineer closes it
  end

&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;As you can see, with webrat you can write the tests in a clear declarative
style. It works like a web crawler similar to &lt;a href=&quot;http://mechanize.rubyforge.org/mechanize/&quot;&gt;Mechanize&lt;/a&gt; or &lt;a href=&quot;http://watir.com/&quot;&gt;Watir&lt;/a&gt;. Webrat also
does some verifications on the page. For example, here&#8217;s what click_button does
according to the &lt;a href=&quot;http://gitrdoc.com/brynary/webrat/tree/master&quot;&gt;documentation&lt;/a&gt;: click_button verifies that a submit button
exists for the form, then submits the form, follows any redirects, and
verifies the final page was successful.&lt;/p&gt;


Here are some useful webrat commands:
	&lt;ul&gt;
	&lt;li&gt;visit &amp;lt;route_or_url&gt;&lt;/li&gt;
		&lt;li&gt;fill_in &#8220;name_or_label&#8221;, :with =&amp;gt; value&lt;/li&gt;
		&lt;li&gt;click_button &#8220;name&#8221; &lt;/li&gt;
		&lt;li&gt;click_link &#8220;name&#8221; &lt;/li&gt;
		&lt;li&gt;select &#8220;option&#8221;, :from =&amp;gt; &#8220;name or label&#8221; &lt;/li&gt;
		&lt;li&gt;choose &#8220;id of option&#8221; &lt;/li&gt;
		&lt;li&gt;attach_file&lt;/li&gt;
		&lt;li&gt;check &#8220;name&#8221; &lt;/li&gt;
		&lt;li&gt;reload&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;All the asserts you have seen earlier, like  assert_response, assert_template
etc. are also available. You can also access the database, like in unit tests,
to verify stuff.&lt;/p&gt;


	&lt;h3&gt;More testing&lt;/h3&gt;


	&lt;p&gt;There are some more kinds of testing you may want to. Most importantly,
performance testing, where you determine how fast your application is
performing and where are the bottlenecks in getting a higher performance. Put
it simply, you first have to do benchmarking to determine your application&#8217;s
current performance and then run a profiler to see the relative performances
of methods for that run. Rails also allows you to test routes and mailers.&lt;/p&gt;


	&lt;p&gt;Additionally, you can do browser testing to determine whether it runs
reasonably in all major browsers.&lt;/p&gt;


	&lt;h3&gt;Ready to move ahead&lt;/h3&gt;


	&lt;p&gt;There are few more tests related concepts to be familiar with:&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;Stubs&lt;/strong&gt;: Often you have a module or over the network call in your application
that you don&#8217;t want to invoke everytime the tests are run. e.g. Credit card
gateway or an external storage. Stubs allow you to mask those calls. Create a
file like test/mocks/development/file_name.rb where file_name.rb should be the
same name as model, controller or lib file that contains the class you are
trying to stub out. In this file, just reopen that class and refine the
relevant methods as stubs.&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;Mocks&lt;/strong&gt;: As you can see the functional tests also load the fixtures and
 execute the model classes, although, models have already been tested in unit
 tests. So, you can substitute model classes by mocks and avoid loading
 fixtures and make the tests run faster. On top of this, mocks check if they
 are used as specified or else they raise an error, giving you an additional
 level of testing. Have a look at &lt;a href=&quot;http://mocha.rubyforge.org/&quot;&gt;Mocha&lt;/a&gt; if you want to use mocks.&lt;/p&gt;


	&lt;p&gt;Once you have mastered writing tests, you can try to write your tests before
you write the code. This is similar to the idea of developing &lt;span class=&quot;caps&quot;&gt;HTML&lt;/span&gt;/CSS mocks
before writing backend code for your application. If you write tests first,
you would be writing the code to a predetermined specification. This practice
is called &#8220;Test driven development&#8221; or &lt;span class=&quot;caps&quot;&gt;TDD&lt;/span&gt;.&lt;/p&gt;


	&lt;p&gt;Now, some people have gone ahead with the idea of tests serving as
specification and called them, well, specs. This style of development is also
called &#8220;Behavior driven development&#8221; and most popular framework that supports
this is &lt;a href=&quot;http://rspec.info/&quot;&gt;Rspec&lt;/a&gt;.&lt;/p&gt;


	&lt;p&gt;There are several other testing frameworks you can try e.g. &lt;a href=&quot;http://github.com/thoughtbot/shoulda&quot;&gt;Shoulda&lt;/a&gt; and
&lt;a href=&quot;http://www.zenspider.com/ZSS/Products/ZenTest/&quot;&gt;Zentest&lt;/a&gt;. There are some useful plugins like &lt;a href=&quot;http://github.com/thoughtbot/factory_girl&quot;&gt;Factory Girl&lt;/a&gt;, &lt;a href=&quot;http://github.com/notahat/machinist&quot;&gt;Machinist&lt;/a&gt; (both are replacements for fixtures) which makes writing tests easier.&lt;/p&gt;


	&lt;p&gt;There are also tools which help with testing like &lt;a href=&quot;http://nubyonrails.com/articles/autotest-rails&quot;&gt;autotest&lt;/a&gt; which runs your
tests automatically whenever the code changes. Of course, continuous
integration packages also run tests.&lt;/p&gt;


	&lt;p&gt;If you are interesting in seeing how much testing you have been doing:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
$ rake stats

&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;will show you how much test code you have written compared to application code. For more serious mesurement you can try calculating code coverage using &lt;a href=&quot;http://eigenclass.org/hiki.rb?rcov&quot;&gt;rcov&lt;/a&gt;.&lt;/p&gt;


	&lt;h2&gt;Tips&lt;/h2&gt;


	&lt;ul&gt;
	&lt;li&gt;Aim of developer testing is not so much to find bugs &#8211; if its does, consider
  that a bonus. For a complex application, you should definitely prepare a
  test plan and do more comprehensive testing, preferably by involving a test
  engineer. &lt;/li&gt;
		&lt;li&gt;Organize your test code. Use setup method, create helper methods in test classes&lt;/li&gt;
		&lt;li&gt;Keep each test method small and test just one thing in one test&lt;/li&gt;
		&lt;li&gt;If you are following RESTful architecture and putting all your domain logic
  in models, write unit tests and do integration testing
  thoroughly. Functional testing can be de-emphasized.&lt;/li&gt;
		&lt;li&gt;In the beginning, don&#8217;t bother testing pathological cases, start simple.&lt;/li&gt;
		&lt;li&gt;For integration testing there are a variety of choices. e.g. use selenium if you are already familiar with it.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;h2&gt;Conclusion&lt;/h2&gt;


	&lt;p&gt;Testing a Rails application using the built-in testing framework is easy and
fast. Although there are lot of things to learn in testing, it is easy to
start small and build gradually as you gain more knowledge and
experience. Happy testing.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://www.magnionlabs.com/">
    <author>
      <name>akmathur</name>
    </author>
    <id>tag:www.magnionlabs.com,2009-10-28:48</id>
    <published>2009-10-28T18:39:00Z</published>
    <updated>2009-10-28T18:39:56Z</updated>
    <category term="Blog"/>
    <category term="Musings"/>
    <category term="Web Application Development"/>
    <link href="http://www.magnionlabs.com/2009/10/28/web-development-is-hard" rel="alternate" type="text/html"/>
    <title>Web development is hard</title>
<summary type="html">&lt;p&gt;Despite a lot of progress, from what I see, developing a web application and running it successfully involve a lot of hard work. Here&#8217;s what I think are reasons for that.&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;Despite a lot of progress, from what I see, developing a web application and running it successfully involve a lot of hard work. Here&#8217;s what I think are reasons for that.&lt;/p&gt;
&lt;p&gt;On the &lt;a href=&quot;http://groups.google.com/group/bangaloreocc&quot;&gt;Bangalore &lt;span class=&quot;caps&quot;&gt;OCC&lt;/span&gt;&lt;/a&gt; mailing
list which has a fantastic mix of entrepreneurs, consultants, VCs and like,
somebody while advising to be careful while hiring web developers
&lt;a href=&quot;http://groups.google.com/group/bangaloreocc/msg/900e2647097b5230&quot;&gt;commented&lt;/a&gt;
: &#8220;Web development is not&#8230; one time development&#8230;&#8221;. That got me thinking: Web
development is still tricky. Yes, we do have our productive frameworks and tried agile
methodologies, but there is still something which makes developing a web
application inherently hard.&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;Never, never, never believe any war will be smooth and easy, or that anyone
who embarks on the strange voyage can measure the tides and hurricanes he will
encounter. &#8212;&lt;strong&gt;Winston Churchill&lt;/strong&gt;&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;Alright, not as difficult as a war may be. But, here are some reasons why I think
it is difficult:&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;Developing a web application needs &lt;strong&gt;multiple skills&lt;/strong&gt;: Your web developer would
  need to know &lt;span class=&quot;caps&quot;&gt;HTML&lt;/span&gt;/CSS, a server side language and relational databases; Javascript and some
  good library to add &lt;span class=&quot;caps&quot;&gt;AJAX&lt;/span&gt; and some zing. Additionally may be,
  Flash/Silverlight. Depending on your application, you may need to do image
  manipulation or some video processing. If you are going to scale, you also
  better build your architecture well add later add caching, tune performance of your
  stack, shard your database or add a nifty nosql database. Aah! It like being
  a  multi-handed Hindu &lt;a href=&quot;http://www.flickr.com/photos/the_world_in_my_eyes/2914301330/&quot;&gt;goddess&lt;/a&gt;.

	&lt;p&gt;Of course, you will not find a single engineer who can do all this but a good web
developer will know few of these well and have sufficient knowledge of
others to know when to bring in more help.&lt;/p&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;strong&gt;It is like gardening&lt;/strong&gt;: You cannot develop a web application and just leave it
  like that. It needs continuous care to change and adapt to usage patterns,
  server loads and optimize work flows.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;strong&gt;Security is top priority&lt;/strong&gt;: In a web application you are effectively putting
  your database online with only the application layer protecting it
  from the big bad internet. Good security is not an add-on, its a
  requirement.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;strong&gt;You will change it&lt;/strong&gt;: Like the war quote above says, it is very hard to
  predict what directions you would take once you put an application
  online. Because of the very short feedback loop of what you put, how your
  users react and then how you would adapt, web applications need to be
  nimble. It would be only prudent to develop it in a way so you can change it
  fast enough.&lt;/li&gt;
	&lt;/ul&gt;
          </content>  </entry>
  <entry xml:base="http://www.magnionlabs.com/">
    <author>
      <name>akmathur</name>
    </author>
    <id>tag:www.magnionlabs.com,2009-10-06:45</id>
    <published>2009-10-06T09:11:00Z</published>
    <updated>2009-10-28T11:26:53Z</updated>
    <category term="Blog"/>
    <category term="Web Application Development"/>
    <link href="http://www.magnionlabs.com/2009/10/6/a-real-life-restful-rails-application" rel="alternate" type="text/html"/>
    <title>A real life RESTful Rails application</title>
<summary type="html">&lt;p&gt;There are a lot of tutorials on the web explaining how to use Rails to build a
RESTful application but very few that goes beyond toy applications. Here, I
present a slightly more complicated example and show how to build it using Rail&#8217;s
RESTful architecture.&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;There are a lot of tutorials on the web explaining how to use Rails to build a
RESTful application but very few that goes beyond toy applications. Here, I
present a slightly more complicated example and show how to build it using Rail&#8217;s
RESTful architecture.&lt;/p&gt;
&lt;blockquote&gt;
		&lt;p&gt;&#8220;Soon you will know, soon you will be one of us&#8221; &#8212; an ancient interwebs proverb.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;h2&gt;Introduction&lt;/h2&gt;


	&lt;p&gt;If you have spent some time learning RESTful way of developing applications
with Rails, you&#8217;ve probably been through some tutorials on developing basic &lt;span class=&quot;caps&quot;&gt;CRUD&lt;/span&gt;
applications in the RESTful way.&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;a href=&quot;http://articles.sitepoint.com/article/rapid-restful-rails-apps&quot;&gt;http://articles.sitepoint.com/article/rapid-restful-rails-apps&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a href=&quot;http://justtalkaboutweb.com/2008/01/25/building-restful-application-in-rails-20-step-by-step/&quot;&gt;http://justtalkaboutweb.com/2008/01/25/building-restful-application-in-rails-20-step-by-step/&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;However, a lot of people struggle with applying the RESTful concepts to
anything beyond simple toy applications. So, here I am presenting an example
application which shows slightly more involved use of RESTful
architecture.&lt;/p&gt;


	&lt;p&gt;At this point I should point out that it is a moderately complex example and
so if you are new to Rails or RESTful architecture in Rails, you should
brush up on these first. Here are a few good starting points for &lt;span class=&quot;caps&quot;&gt;REST&lt;/span&gt;:&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;a href=&quot;http://www.xml.com/lpt/a/2004/12/01/restful-web.html&quot;&gt;http://www.xml.com/lpt/a/2004/12/01/restful-web.html&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a href=&quot;http://www.xfront.com/REST-Web-Services.html&quot;&gt;http://www.xfront.com/REST-Web-Services.html&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;and for how it applies to Rails:&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;a href=&quot;http://topfunky.com/clients/peepcode/REST-cheatsheet.pdf&quot;&gt;http://topfunky.com/clients/peepcode/REST-cheatsheet.pdf&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a href=&quot;http://www.b-simple.de/download/restful_rails_en.pdf&quot;&gt;http://www.b-simple.de/download/restful_rails_en.pdf&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;OK, let&#8217;s start.&lt;/p&gt;


	&lt;p&gt;While using RESTful architecture in Rails, only controller and routes are
different. What you already know about models and helpers and all of the other plugins
and libraries you are used to, work exactly the same.&lt;/p&gt;


	&lt;p&gt;Controllers become more streamlined and there will be lot more controller
classes than earlier, as you will see soon. However the code becomes much more
simpler.&lt;/p&gt;


	&lt;h2&gt;Requirements&lt;/h2&gt;


	&lt;p&gt;Let&#8217;s start by building an example Rails application. Here are the
requirements:&lt;/p&gt;


	&lt;p&gt;Our application should allow users to register and then login using their
login and password. Fairly standard stuff. After authentication, they should
see an inbox with messages &#8211; very much like your Gmail inbox, and a big button
called &#8220;send a message&#8221;. On clicking it, any user should be able to compose
and send another user a message. A message consists of subject and body. Again, quite
similar to email but these messages are within the closed system &lt;i&gt;i.e. only
users in the system can send a message to another user in the system.&lt;/i&gt; Yes,
quite like what social networking sites do. Additionally, a user should be
able to archive a message or delete it; view archived messages and sent
messages.&lt;/p&gt;


	&lt;p&gt;Is requirements part clear? Good.&lt;/p&gt;


	&lt;h2&gt;Preparation&lt;/h2&gt;


Let&#8217;s start by building user accounts and authentication:
&lt;pre&gt;&lt;code&gt;

$ rails -d mysql demo
$ cd demo 
$ ruby script/plugin install git://github.com/technoweenie/restful-authentication.git  
$ ruby script/generate authenticated user sessions
# add 'include AuthenticatedSystem' to application_controller.rb as recommended by restful-authentication plugin
# edit file: config/database.yml and add password for the database if you have one
$ rake db:create
$ rake db:migrate
$ ruby script/server

&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;Point your browser to: &lt;a href=&quot;http://localhost:3000/users/new&quot;&gt;http://localhost:3000/users/new&lt;/a&gt; and create a new account. Then go to: &lt;a href=&quot;http://localhost:3000/sessions/new&quot;&gt;http://localhost:3000/sessions/new&lt;/a&gt; and sign in with the new user account which you just created and you should see the &#8220;Welcome aboard&#8221; page.&lt;/p&gt;


	&lt;p&gt;So far you have built a basic Rails app, with restful auth. You might want to
register 2 users and keep their login and passwords handy &#8211; let&#8217;s say with
login names &lt;strong&gt;venkat&lt;/strong&gt; and &lt;strong&gt;suresh&lt;/strong&gt;. We would next be building the messaging
part so that these two users can send messages to each other.&lt;/p&gt;


	&lt;h2&gt;Models and the Database design&lt;/h2&gt;


	&lt;p&gt;You can reflect for a moment about what kind of DB design would suit this
problem. But, just to speed us up, here&#8217;s something I thought of. Let&#8217;s have
these following 3 models (and hence 3 tables in the DB) and their attributes:&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;MessageDetail&lt;/strong&gt;: subject, body, sent_message_id&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;ReceivedMessage&lt;/strong&gt;: message_detail_id, recipient_id, state&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;SentMessage&lt;/strong&gt;: sender_id, state&lt;/p&gt;


	&lt;p&gt;The idea being that MessageDetail object represents the actual message &#8211; the
subject and body; ReceivedMessage represents the view of the message as
visible to the recipient; similarly SentMessage is sender&#8217;s
view. ReceivedMessage and SentMessage are separate objects from MessageDetail
so that senders and each of the multiple recipients can independently archive or
delete their messages.&lt;/p&gt;


	&lt;p&gt;This means, even if sender decides to delete a message, we won&#8217;t delete
MessageDetail record from our table because otherwise message from recipient
view would be lost. We would delete the message when &lt;i&gt;both&lt;/i&gt; sender and
receiver delete their messages.&lt;/p&gt;


	&lt;p&gt;Let&#8217;s create each of these models:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
$ ruby script/generate model MessageDetail subject:string body:text sent_message_id:integer
$ ruby script/generate model ReceivedMessage message_detail_id:integer recipient_id:integer state:string
$ ruby script/generate model SentMessage sender_id:integer state:string

&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Then run the migrations to create the DB tables:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
$ rake db:migrate

&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Now, fill in the model code:&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;

# model classes omitting validations

class MessageDetail &amp;lt; ActiveRecord::Base
  attr_accessible :subject, :body, :sender, :recipient

  belongs_to :sent_message
  has_one :sender, :through =&amp;gt; :sent_message
  has_many :received_messages
  has_many :recipients, :through =&amp;gt; :received_messages

  def sender=(user)
    self.build_sent_message
    self.sent_message.sender = user
  end

  def recipient=(user)
    self.received_messages &amp;lt;&amp;lt; ReceivedMessage.new(:recipient =&amp;gt; User.find_by_login(user))
  end

  def recipient
    self.received_messages.map { |r| r.recipient.try(:login) }.join(&quot;, &quot;)
  end
end

class SentMessage &amp;lt; ActiveRecord::Base
  has_one :message_detail
  belongs_to :sender, :class_name =&amp;gt; 'User'
end

class ReceivedMessage &amp;lt; ActiveRecord::Base
  belongs_to :message_detail
  belongs_to :recipient, :class_name =&amp;gt; 'User'
end

&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;You will also have to modify the User model a little bit to add this association:&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;

class User &amp;lt; ActiveRecord::Base
  has_many :received_messages, :foreign_key =&amp;gt; 'recipient_id'
  has_many :sent_messages, :foreign_key =&amp;gt; 'sender_id'
  ...
end

&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Now, that is a lot of code. But, hopefully you can make some sense out of it. Even if you are not able to, don&#8217;t worry. We will mostly treat this as black box. Our main aim here is to learn about the controllers which is coming later.&lt;/p&gt;


	&lt;p&gt;To test that our models work as we expect, do this in your Rails console:&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;

message = MessageDetail.new(:subject =&amp;gt; 'test subject',
                            :body =&amp;gt; 'test body',
                            :sender =&amp;gt; User.find_by_login('suresh'),
                            :recipient =&amp;gt; 'venkat')

message.save # this should return true

suresh = User.find_by_login('suresh')
msg = suresh.sent_messages.first # suresh's first sent message
msg.message_detail.recipients # list of all recipients of this message

&lt;/code&gt;
&lt;/pre&gt;

	&lt;h2&gt;Restful architecture&lt;/h2&gt;


	&lt;p&gt;Now, our aim is to expose the messages system through our UI. &lt;span class=&quot;caps&quot;&gt;REST&lt;/span&gt; is
methodology of specifying an external interface (or a network &lt;span class=&quot;caps&quot;&gt;API&lt;/span&gt; in other
words) of a system. Constructing that &lt;span class=&quot;caps&quot;&gt;API&lt;/span&gt; is also quite systematic.&lt;/p&gt;


	&lt;p&gt;In review, &lt;span class=&quot;caps&quot;&gt;REST&lt;/span&gt; is about 3 things:&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;resources, which are identified by URLs&lt;/li&gt;
		&lt;li&gt;fixed vocabulary of verbs (HTTP verbs: &lt;span class=&quot;caps&quot;&gt;GET&lt;/span&gt;, POST, &lt;span class=&quot;caps&quot;&gt;PUT&lt;/span&gt; and &lt;span class=&quot;caps&quot;&gt;DELETE&lt;/span&gt;)&lt;/li&gt;
		&lt;li&gt;representations of resources e.g. the type of representation is specified by &lt;span class=&quot;caps&quot;&gt;HTTP&lt;/span&gt; header: content-type&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;Our first task is constructing a &lt;span class=&quot;caps&quot;&gt;URL&lt;/span&gt; scheme by identifying the resources in
the system. Think of resources as the nouns. Then each resource can be acted
upon by one of the standard &lt;span class=&quot;caps&quot;&gt;HTTP&lt;/span&gt; verbs: &lt;span class=&quot;caps&quot;&gt;GET&lt;/span&gt;, POST, &lt;span class=&quot;caps&quot;&gt;PUT&lt;/span&gt; or &lt;span class=&quot;caps&quot;&gt;DELETE&lt;/span&gt;.&lt;/p&gt;


	&lt;p&gt;Let&#8217;s say we decide on following &lt;span class=&quot;caps&quot;&gt;URL&lt;/span&gt; scheme:&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;/messages&lt;/strong&gt;
where &lt;span class=&quot;caps&quot;&gt;GET&lt;/span&gt; /messages returns all messages in inbox, &lt;span class=&quot;caps&quot;&gt;POST&lt;/span&gt; /messages sends a new message&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;/messages/archived&lt;/strong&gt;
similar to /messages but shows all messages in archive folder&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;/messages/sent&lt;/strong&gt;
similar to /messages but shows all messages in sent folder.&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;/messages/1&lt;/strong&gt;
&lt;span class=&quot;caps&quot;&gt;GET&lt;/span&gt; /messages/1 shows the message id 1&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;/messages/1/archived&lt;/strong&gt;
&lt;span class=&quot;caps&quot;&gt;GET&lt;/span&gt; /messages/1/archived tells us whether this message is archived and &lt;span class=&quot;caps&quot;&gt;PUT&lt;/span&gt;
/messages/1/archived with a true in the body changes the status of the message id 1 to &#8220;archived&#8221;.&lt;/p&gt;


	&lt;p&gt;Rails actually constraints the &lt;span class=&quot;caps&quot;&gt;REST&lt;/span&gt; even further. It generates the following set of URLs:&lt;/p&gt;


	&lt;p&gt;/messages&lt;/p&gt;


	&lt;p&gt;/messages/1&lt;/p&gt;


	&lt;p&gt;/messages/1/edit&lt;/p&gt;


	&lt;p&gt;/messages/new&lt;/p&gt;


	&lt;p&gt;Each of these URLs can be generated by a named route helper (if you don&#8217;t know named routes, see here: http://guides.rubyonrails.org/routing.html). The helper names for the above URLs are:&lt;/p&gt;


	&lt;p&gt;messages_path&lt;/p&gt;


	&lt;p&gt;message_path(:id =&amp;gt; 1)&lt;/p&gt;


	&lt;p&gt;edit_message_path(:id =&amp;gt; 1)&lt;/p&gt;


	&lt;p&gt;new_message_path&lt;/p&gt;


	&lt;p&gt;Then Rails maps certain combinations of &lt;span class=&quot;caps&quot;&gt;HTTP&lt;/span&gt; verbs with these URLs to controller actions:&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;&lt;span class=&quot;caps&quot;&gt;GET&lt;/span&gt; /messages&lt;/strong&gt;  &lt;code&gt;index&lt;/code&gt;&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;&lt;span class=&quot;caps&quot;&gt;GET&lt;/span&gt; /messages/1&lt;/strong&gt;  &lt;code&gt;get&lt;/code&gt;&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;&lt;span class=&quot;caps&quot;&gt;POST&lt;/span&gt; /messages&lt;/strong&gt; &lt;code&gt;create&lt;/code&gt;&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;&lt;span class=&quot;caps&quot;&gt;PUT&lt;/span&gt; /messages/1&lt;/strong&gt; &lt;code&gt;update&lt;/code&gt;&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;&lt;span class=&quot;caps&quot;&gt;DELETE&lt;/span&gt; /messages/1&lt;/strong&gt; &lt;code&gt;delete&lt;/code&gt;&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;&lt;span class=&quot;caps&quot;&gt;GET&lt;/span&gt; /messages/new&lt;/strong&gt;  &lt;code&gt;new&lt;/code&gt;&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;&lt;span class=&quot;caps&quot;&gt;GET&lt;/span&gt; /messages/1/edit&lt;/strong&gt; &lt;code&gt;edit&lt;/code&gt;&lt;/p&gt;


	&lt;p&gt;Now, creating the four named routes, and mapping the above 7 combinations of
&lt;span class=&quot;caps&quot;&gt;HTTP&lt;/span&gt; verb and &lt;span class=&quot;caps&quot;&gt;URL&lt;/span&gt; to controller actions, can be accomplished by adding just this one
line in the config/routes.rb file:&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
map.resources :messages

&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Go ahead and add this to your config/routes.rb. Then, create a controller called MessagesController with the above 7 actions, and the actions will be called whenever the user fetches the corresponding &lt;span class=&quot;caps&quot;&gt;URL&lt;/span&gt;.&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
$ ruby script/generate controller messages

&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Filling the controller with the 7 actions is very much boiler plate code. But,
unfortunately Rails does not provide a generator for that (yet). If you use
Textmate or Emacs, you can use a snippet
(available &lt;a href=&quot;http://www.softiesonrails.com/2007/12/14/textmate-snippet-for-restful-controller&quot;&gt;here&lt;/a&gt;).&lt;/p&gt;


	&lt;p&gt;You can also generate the controllers using scaffold or resource generator.&lt;/p&gt;


	&lt;p&gt;However, let&#8217;s do it by hand:&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
$ ruby script/generate controller messages index show new edit create update destroy 

&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;As an aside, if you are confused about difference between new and create: when a user
wants to create a new message, she GETs the /messages/new &lt;span class=&quot;caps&quot;&gt;URL&lt;/span&gt; which is
rendered by new action, fills in the form, and then POSTs to /messages to
create the object in the database. The &lt;span class=&quot;caps&quot;&gt;POST&lt;/span&gt; /messages request is handled by
create action. edit and update actions work similarly.&lt;/p&gt;


	&lt;p&gt;Now, all that is remaining is to code up the 7 actions in the controller.&lt;/p&gt;


	&lt;p&gt;There are rules about what can the web application do for each of these
actions. Most importantly, &lt;span class=&quot;caps&quot;&gt;REST&lt;/span&gt; specifies that &lt;span class=&quot;caps&quot;&gt;GET&lt;/span&gt;, PUT, &lt;span class=&quot;caps&quot;&gt;DELETE&lt;/span&gt; are
idempotent. Which means they can be repeated, say by user hitting reload on
their browser; where as &lt;span class=&quot;caps&quot;&gt;POST&lt;/span&gt; is not. So, all actions except create must be
idempotent, that is even if they are repeated, there should be no harm.&lt;/p&gt;


	&lt;p&gt;Now, there are a few things to take care of while coding the
controller. Firstly, put a filter so that the actions can be executed only
after authentication:&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;

class MessagesController &amp;lt; ApplicationController
  before_filter :login_required
  ...
  ...
end

&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Now, we have to skillfully map our restful controller&#8217;s actions to calls to
the models we already have built. So, for example, code of index action would
be:&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;

# GET /messages
def index
  @messages = current_user.received_messages
end

&lt;/pre&gt;
&lt;/code&gt;

	&lt;p&gt;Now, create a view messages/index.html.erb and display the messages from @messages&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;

&amp;lt;table&amp;gt;
&amp;lt;thead&amp;gt;
  &amp;lt;th&amp;gt;Sent by&amp;lt;/th&amp;gt;
  &amp;lt;th&amp;gt;Subject&amp;lt;/th&amp;gt;
  &amp;lt;th&amp;gt;Date&amp;lt;/th&amp;gt;
&amp;lt;/thead&amp;gt;
&amp;lt;% @messages.each do |message| %&amp;gt;
  &amp;lt;tr&amp;gt;
    &amp;lt;td&amp;gt;&amp;lt;%= message.message_detail.sender.login %&amp;gt;&amp;lt;/td&amp;gt;
    &amp;lt;td&amp;gt;&amp;lt;%= message.message_detail.subject %&amp;gt;&amp;lt;/td&amp;gt;
    &amp;lt;td&amp;gt;&amp;lt;%= message.created_at %&amp;gt;&amp;lt;/td&amp;gt;
  &amp;lt;/tr&amp;gt;
&amp;lt;% end %&amp;gt;
&amp;lt;/table&amp;gt;

&lt;/pre&gt;
&lt;/code&gt;

	&lt;p&gt;Go to &lt;a href=&quot;http://localhost:3000/messages&quot;&gt;http://localhost:3000/messages&lt;/a&gt; to look at the inbox for the logged in
user.&lt;/p&gt;


	&lt;p&gt;Now, it is quite straight forward to code up all the controller actions and corresponding views. Let&#8217;s try create next:&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;

  # file: app/views/messages/new.html.erb
  &amp;lt;h1&amp;gt;Enter your message&amp;lt;/h1&amp;gt;

  &amp;lt;% form_for(:message, :url =&amp;gt; messages_path) do |f| %&amp;gt;

  &amp;lt;p&amp;gt;From &amp;lt;strong&amp;gt;&amp;lt;%= current_user.login %&amp;gt;&amp;lt;/strong&amp;gt;&amp;lt;/p&amp;gt;
  &amp;lt;p&amp;gt;
      &amp;lt;%= f.label :recipient, &quot;login-id of the recipient:&quot; %&amp;gt;&amp;lt;br /&amp;gt;
      &amp;lt;%= f.text_field :recipient %&amp;gt;
  &amp;lt;/p&amp;gt;
  &amp;lt;p&amp;gt;
      &amp;lt;%= f.label :subject, &quot;Subject:&quot; %&amp;gt;&amp;lt;br /&amp;gt;
      &amp;lt;%= f.text_field :subject %&amp;gt;
  &amp;lt;/p&amp;gt;

  &amp;lt;p&amp;gt;&amp;lt;%= f.text_area :body, :cols =&amp;gt; 60, :rows =&amp;gt; 8 %&amp;gt;&amp;lt;/p&amp;gt;

  &amp;lt;p&amp;gt;&amp;lt;%= f.submit &quot;Post Message&quot; %&amp;gt;&amp;lt;/p&amp;gt;

  &amp;lt;% end %&amp;gt;

  # file: app/controllers/messages_controller.rb
  # GET /messages/new
  def new
    @message = MessageDetail.new
  end

  # POST /messages
  def create
    @message = MessageDetail.new(params[:message].merge(:sender =&amp;gt; current_user))

    if @message.save
      flash[:success] = 'Message was successfully sent.'
      redirect_to messages_path
    else
      render :action =&amp;gt; &quot;new&quot; 
    end
  end

&lt;/code&gt;
&lt;/pre&gt;

	&lt;ul&gt;
	&lt;li&gt;Now, go to &lt;a href=&quot;http://localhost:3000/messages/new&quot;&gt;http://localhost:3000/messages/new&lt;/a&gt; and send out a messages to the
other user in your database.&lt;/li&gt;
		&lt;li&gt;Go to &lt;a href=&quot;http://localhost:3000/session/new&quot;&gt;http://localhost:3000/session/new&lt;/a&gt; and login as other user&lt;/li&gt;
		&lt;li&gt;Go to &lt;a href=&quot;http://localhost:3000/messages&quot;&gt;http://localhost:3000/messages&lt;/a&gt; and see the new message in the inbox&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;There, you have a message system whose external interface is completely RESTful.&lt;/p&gt;


	&lt;h2&gt;Recap:&lt;/h2&gt;


	&lt;ul&gt;
	&lt;li&gt;We built a skeleton Rails app with restful_authentication&lt;/li&gt;
		&lt;li&gt;Then we added messages models and tested from console that we can send a message from one user to other&lt;/li&gt;
		&lt;li&gt;Lastly we exposed the messages through a RESTful interface&lt;/li&gt;
	&lt;/ul&gt;


	&lt;h2&gt;Conclusion:&lt;/h2&gt;


	&lt;p&gt;Rails supports RESTful architecture out of the box. There is no need for any plugin to make it work.&lt;/p&gt;


&lt;span class=&quot;caps&quot;&gt;REST&lt;/span&gt; learning resources:
	&lt;ul&gt;
	&lt;li&gt;&lt;a href=&quot;http://rest.blueoxen.net/cgi-bin/wiki.pl&quot;&gt;&lt;span class=&quot;caps&quot;&gt;REST&lt;/span&gt; wiki&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;Sam Ruby&#8217;s &lt;a href=&quot;http://intertwingly.net/blog/&quot;&gt;blog&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;


Rails:
	&lt;ul&gt;
	&lt;li&gt;&lt;a href=&quot;http://www.krisjordan.com/2008/09/17/david-heinemeier-hansson-go-rest-with-rails/&quot;&gt;&lt;span class=&quot;caps&quot;&gt;DHH&lt;/span&gt; talk which started it all&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a href=&quot;http://topfunky.com/clients/peepcode/REST-cheatsheet.pdf&quot;&gt;&lt;span class=&quot;caps&quot;&gt;REST&lt;/span&gt; cheat sheet&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a href=&quot;http://www.softiesonrails.com/2008/1/29/rails-rest-101-meets-rails-2-0&quot;&gt;Beginner RESTful Rails&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a href=&quot;http://www.slideshare.net/viget/advanced-restful-rails-439639&quot;&gt;Advanced RESTful Rails&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a href=&quot;http://www.akitaonrails.com/2008/1/25/easy-restful-rails-screencast&quot;&gt;http://www.akitaonrails.com/2008/1/25/easy-restful-rails-screencast&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;
          </content>  </entry>
  <entry xml:base="http://www.magnionlabs.com/">
    <author>
      <name>akmathur</name>
    </author>
    <id>tag:www.magnionlabs.com,2009-09-27:44</id>
    <published>2009-09-27T09:41:00Z</published>
    <updated>2009-09-27T09:42:21Z</updated>
    <category term="Blog"/>
    <category term="Web Application Development"/>
    <link href="http://www.magnionlabs.com/2009/9/27/webservices-to-make-application-development-easy" rel="alternate" type="text/html"/>
    <title>Webservices to make application development easy</title>
<summary type="html">&lt;p&gt;Recently &lt;a href=&quot;http://en.wikipedia.org/wiki/Web_service&quot;&gt;Web Services&lt;/a&gt; have been a major driving force towards making application development easy, modular and more robust. Here&#8217;s a list of some popular and proven ones for Rails development.&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;Recently &lt;a href=&quot;http://en.wikipedia.org/wiki/Web_service&quot;&gt;Web Services&lt;/a&gt; have been a major driving force towards making application development easy, modular and more robust. Here&#8217;s a list of some popular and proven ones for Rails development.&lt;/p&gt;
&lt;p&gt;Last week there was an article on &lt;a href=&quot;http://sixrevisions.com/&quot;&gt;six revisions&lt;/a&gt;
about &lt;a href=&quot;http://sixrevisions.com/web-applications/website-features-that-you-can-easily-offload/&quot;&gt;Website Features That You Can Easily
Offload&lt;/a&gt;
listing how you can take advantage of web services to lesser the burden on a site.&lt;/p&gt;


	&lt;p&gt;That prompted me to make a list of web services that an application developer,
especially a Rails developer can use to similarly, offload functionality and
get away with less code, less maintenance and develop quickly. Here&#8217;s what I
could think of:&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;Authentication &#8211; Even though creating an authentication system in Rails is
 easy thanks to plugins like &lt;a href=&quot;http://github.com/technoweenie/restful-authentication&quot;&gt;Resftful authentication&lt;/a&gt;, your users probably hate
 having to create and remember another login and password. By using
 &lt;a href=&quot;http://openid.net/get-an-openid/what-is-openid/&quot;&gt;OpenId&lt;/a&gt; you can allow them
 to sign using a login and password &lt;a href=&quot;http://openid.net/get-an-openid/&quot;&gt;they already remember&lt;/a&gt;, not worry about
 handling forgotten passwords and actually be more secure.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Client side analytics &#8211; &lt;a href=&quot;http://www.google.com/analytics/&quot;&gt;Google analytics&lt;/a&gt; has made client side analytics dead
 easy. But there are others too: &lt;a href=&quot;http://getclicky.com/&quot;&gt;Clicky&lt;/a&gt;, &lt;a href=&quot;http://crazyegg.com/&quot;&gt;Crazy Egg&lt;/a&gt; and &lt;a href=&quot;http://haveamint.com/&quot;&gt;Mint&lt;/a&gt;.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Server side metrics &#8211; If you want to collect metrics within your
  application, there are web services that help you there as well. See
  &lt;a href=&quot;http://mixpanel.com/&quot;&gt;Mixpanel&lt;/a&gt; and &lt;a href=&quot;http://www.nuconomy.com/&quot;&gt;Nuconomy&lt;/a&gt;.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Server monitoring and alarms &#8211; If you don&#8217;t want to build a dashboard yourself using &lt;a href=&quot;http://www.nagios.org/&quot;&gt;Nagios&lt;/a&gt; or
  &lt;a href=&quot;http://munin.projects.linpro.no/&quot;&gt;Munin&lt;/a&gt;, one of the best web services product to
  monitor your server performance is &lt;a href=&quot;http://scoutapp.com/&quot;&gt;Scout&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Application performance monitoring &#8211; Among the hosted services,
  &lt;a href=&quot;http://www.newrelic.com/&quot;&gt;NewRelic&lt;/a&gt; seems to the current leader for Rails
  application performance monitoring. &lt;a href=&quot;http://scoutapp.com/&quot;&gt;Scout&lt;/a&gt; would also do
  it for you in a limited sense. &lt;a href=&quot;https://dash.fiveruns.com/pages/overview&quot;&gt;this&lt;/a&gt; also looks like a
  promising upcoming alternative.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Uptime monitring &#8211; To know if your site is up and get notified as soon as it
  goes down is absolute key to any business. &lt;a href=&quot;http://www.keynote.com/&quot;&gt;Keynote&lt;/a&gt;,
  &lt;a href=&quot;http://www.pingdom.com/&quot;&gt;Pingdom&lt;/a&gt; are two good choices. Of course, there are
  &lt;a href=&quot;http://sixrevisions.com/tools/12-excellent-free-tools-for-monitoring-your-sites-uptime/&quot;&gt;many others&lt;/a&gt;
  as well.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Exception reporting &#8211; probably unique to Rails, is getting notified whenever
  a user gets the dreaded 500 server error page. If you want more than what
  &lt;a href=&quot;http://github.com/rails/exception_notification&quot;&gt;Exception notifier&lt;/a&gt; plugin
  can do for you, &lt;a href=&quot;http://www.hoptoadapp.com/&quot;&gt;Hoptoad&lt;/a&gt; and
  &lt;a href=&quot;http://getexceptional.com/&quot;&gt;Exceptional&lt;/a&gt; are two services which you can look at.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Sending emails &#8211; If sending emails from your server seems like too
  complicated, or you are seeing your mails end up in people&#8217;s
  spam folders, you can try &lt;a href=&quot;http://github.com/openrain/action_mailer_tls&quot;&gt;Google&#8217;s
  &lt;span class=&quot;caps&quot;&gt;SMTP&lt;/span&gt;&lt;/a&gt;. For a more full featured alternative, try &lt;a href=&quot;http://www.campaignmonitor.com/api&quot;&gt;Campaign monitor&lt;/a&gt; or &lt;a href=&quot;http://www.mailchimp.com/api/&quot;&gt;Mailchimp&lt;/a&gt;.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Videos &#8211; With excellent services like
  &lt;a href=&quot;code.google.com/apis/youtube/overview.html&quot;&gt;Youtube&lt;/a&gt;,
  &lt;a href=&quot;http://www.vimeo.com/api&quot;&gt;Vimeo&lt;/a&gt; and &lt;a href=&quot;http://blip.tv/about/api/&quot;&gt;blip.tv&lt;/a&gt; You
  no longer really need to handle video upload, processing and serving. In
  fact, using one of these services will be faster for both development as well as for
  your users.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Images &#8211; Similarly, with services like
  &lt;a href=&quot;http://www.flickr.com/services/api/&quot;&gt;Flickr&lt;/a&gt; you don&#8217;t need to handle photos
  if you don&#8217;t want to. You can even offload profile pictures to &lt;a href=&quot;http://en.gravatar.com/&quot;&gt;Gravatar&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Payment &#8211; Handling payment is one of the trickiest pieces. Almost all
  the apps end up using one of these services to make it easy. Take your pick from:
  &lt;a href=&quot;https://www.paypal.com/&quot;&gt;Paypal&lt;/a&gt;, &lt;a href=&quot;checkout.google.com/&quot;&gt;Google checkout&lt;/a&gt; and
  &lt;a href=&quot;https://payments.amazon.com&quot;&gt;Amazon payments&lt;/a&gt;. Then there&#8217;s
  &lt;a href=&quot;http://spreedly.com/&quot;&gt;Spreedly&lt;/a&gt; especially to make handling subscriptions
  easier.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;E-commerce &#8211; If you want a service for handling checkouts, order management
  dashboards, fulfillment and the whole nine yards, check out
  &lt;a href=&quot;http://www.netsuite.com/portal/home.shtml&quot;&gt;NetSuite&lt;/a&gt; and &lt;a href=&quot;http://api.shopify.com/&quot;&gt;Shopify&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Geoocoding and maps &#8211; You are probably already using &lt;a href=&quot;code.google.com/apis/maps/&quot;&gt;Google
maps&lt;/a&gt; as a service to embed maps in your
application. If you need to do geocoding, try &lt;a href=&quot;http://geokit.rubyforge.org/&quot;&gt;this&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;DB backup and storage &#8211; There are umpteen choices for offsite
  stroage. Couple of good ones are &lt;a href=&quot;https://s3.amazonaws.com/&quot;&gt;Amazon S3&lt;/a&gt; and &lt;a href=&quot;http://www.jungledisk.com/&quot;&gt;Jungle
  Disk&lt;/a&gt; but there are &lt;a href=&quot;http://www.techcrunch.com/2006/01/31/the-online-storage-gang/&quot;&gt;many others&lt;/a&gt; too.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Amazon Web services: I thought &lt;a href=&quot;http://aws.amazon.com/&quot;&gt;&lt;span class=&quot;caps&quot;&gt;AWS&lt;/span&gt;&lt;/a&gt; deserved special mention since they
  really have been pioneers of web services. You can find many interesting
  services here from distributed queue, hosted databases, metering and even on-demand work force. &lt;strong&gt;Disclaimer&lt;/strong&gt;: I used to work for &lt;a href=&quot;http://india.amazon.com&quot;&gt;&lt;span class=&quot;caps&quot;&gt;AWS&lt;/span&gt;&lt;/a&gt;.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;Besides, there are &lt;a href=&quot;http://agilewebdevelopment.com/plugins/search/index&quot;&gt;Rails plugins&lt;/a&gt; of course which
make developing applications easier ever further. But, since we are considering only web
services, they are not listed here.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://www.magnionlabs.com/">
    <author>
      <name>akmathur</name>
    </author>
    <id>tag:www.magnionlabs.com,2009-09-23:43</id>
    <published>2009-09-23T21:18:00Z</published>
    <updated>2009-09-23T21:19:13Z</updated>
    <category term="Blog"/>
    <category term="Computer Science"/>
    <category term="Web Application Development"/>
    <link href="http://www.magnionlabs.com/2009/9/23/beautiful-code" rel="alternate" type="text/html"/>
    <title>Beautiful code</title>
<summary type="html">&lt;p&gt;&lt;a href=&quot;http://www.joelonsoftware.com&quot;&gt;Joel Splosky&lt;/a&gt; once defined beautiful code as: code which does something in much less lines than what it seems like the task should take. I think these examples fit the definition exactly.&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;&lt;a href=&quot;http://www.joelonsoftware.com&quot;&gt;Joel Splosky&lt;/a&gt; once defined beautiful code as: code which does something in much less lines than what it seems like the task should take. I think these examples fit the definition exactly.&lt;/p&gt;
&lt;p&gt;A long time back, browsing through &lt;a href=&quot;http://www.amazon.com/Spirit-Introduction-Modern-Programming/dp/0314285008&quot;&gt;a book&lt;/a&gt;, I came across code for strcpy function which is part of the standard library in C:&lt;/p&gt;


&lt;pre&gt;

strcpy(char *s1,char *s2)
{
  while (*s1++ = *s2++)
}

&lt;/pre&gt;

	&lt;p&gt;Just the beauty of the code made me fall in love with C and programming all
over again. Then, I got busy with courses, jobs, projects and releases.&lt;/p&gt;


	&lt;p&gt;Recently, while programming with Ruby, I had to randomize an array of objects
before it got displayed. I thought, I should consult Google&#8217;s brain before I
whip up anything of my own. This is what I found:&lt;/p&gt;


&lt;pre&gt;

(1..10).sort_by { rand } 

&lt;/pre&gt;
Randomizes an array of numbers 1 to 10. Oh the &lt;a href=&quot;http://ishare.rediff.com/video/Cricket/Dravid-Classic-Cover-Drive---2nd-Test-Napier-India-vs-New-Zealand-2009/593753&quot;&gt;beauty!&lt;/a&gt;

	&lt;p&gt;More details &lt;a href=&quot;http://computer.howstuffworks.com/c35.htm&quot;&gt;here&lt;/a&gt; if you want to learn about strcpy and &lt;a href=&quot;http://www.ruby-forum.com/topic/92083&quot;&gt;here&lt;/a&gt; is where I spotted the Ruby code.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://www.magnionlabs.com/">
    <author>
      <name>akmathur</name>
    </author>
    <id>tag:www.magnionlabs.com,2009-08-15:41</id>
    <published>2009-08-15T16:33:00Z</published>
    <updated>2009-08-15T16:36:32Z</updated>
    <category term="Blog"/>
    <link href="http://www.magnionlabs.com/2009/8/15/web-2-0-application-development-with-ror-slides" rel="alternate" type="text/html"/>
    <title>Web 2.0 application development with RoR - slides</title>
<content type="html">
            Slides from the recent training I delivered at Hewlett Packard India.
&lt;br /&gt;
&lt;div&gt;&lt;a href=&quot;http://www.slideshare.net/akmags/web-20-application-development-with-ruby-on-rails&quot; title=&quot;Web 2.0 Application development with Ruby on Rails&quot;&gt;Web 2.0 Application development with Ruby on Rails&lt;/a&gt;&amp;lt;object height=&quot;355&quot; width=&quot;425&quot;&gt;&amp;lt;param /&gt;&amp;lt;param /&gt;&amp;lt;param /&gt;&amp;lt;embed src=&quot;http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=slides-090815112157-phpapp02&amp;amp;rel=0&amp;amp;stripped_title=web-20-application-development-with-ruby-on-rails&quot; height=&quot;355&quot; width=&quot;425&quot;&gt;&amp;lt;/embed&gt;&amp;lt;/object&gt;&lt;div&gt;View more &lt;a href=&quot;http://www.slideshare.net/&quot;&gt;documents&lt;/a&gt; from &lt;a href=&quot;http://www.slideshare.net/akmags&quot;&gt;akmags&lt;/a&gt;.&lt;/div&gt;&lt;/div&gt;
          </content>  </entry>
  <entry xml:base="http://www.magnionlabs.com/">
    <author>
      <name>akmathur</name>
    </author>
    <id>tag:www.magnionlabs.com,2009-07-22:40</id>
    <published>2009-07-22T16:18:00Z</published>
    <updated>2009-07-22T16:43:48Z</updated>
    <category term="Blog"/>
    <category term="Web Application Development"/>
    <link href="http://www.magnionlabs.com/2009/7/22/before-you-write-that-code" rel="alternate" type="text/html"/>
    <title>Before you write that code...</title>
<summary type="html">&lt;p&gt;There are several important things for a business owner to do before letting engineers start developing code. Here I give a comprehensive list of such tasks. It will make your project more controllable and eventually will make your developers happy as well.&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;There are several important things for a business owner to do before letting engineers start developing code. Here I give a comprehensive list of such tasks. It will make your project more controllable and eventually will make your developers happy as well.&lt;/p&gt;
&lt;p&gt;So you have decided that you are going to implement your big idea and may be
you have also hired your favorite developer. There is nothing that a
programmer loves more than writing code &#8211; they would just want to &lt;/em&gt;get
hacking&lt;/em&gt;. But in my experience, there are some essential things you should
do before you get to writing code.&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;strong&gt;Prepare a page flow diagram&lt;/strong&gt;: You should have a clear enough idea of all the
  important pages and how they link together. You should be able to walk
  through the steps a typical user would go through while using your
  application.

	&lt;p&gt;There&#8217;s a whole
&lt;a href=&quot;http://en.wikipedia.org/wiki/Information_architecture&quot;&gt;field&lt;/a&gt; devoted to
dividing the user flows into pages and laying out information on those pages. But,
you don&#8217;t have to get fancy. As the &lt;a href=&quot;http://37signals.com&quot;&gt;37Signals&lt;/a&gt; guys
recommend in their fantastic book &lt;a href=&quot;http://gettingreal.37signals.com/toc.php&quot;&gt;Getting
Real&lt;/a&gt;, just a rough sketch on paper
is enough.&lt;/p&gt;


	&lt;p&gt;Ideally you should also get the graphic design done based on this page flow
diagram. But, at least get the page flow diagram prepared before you write any code.&lt;/p&gt;


	&lt;p&gt;For a lot of projects, the page flow diagram serves as good as a
requirements doc; and it is a lot less work. You certainly want to make sure
you got your vision into your dev&#8217;s brain. It is a good way to do it.&lt;/p&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;strong&gt;Make a high level task list&lt;/strong&gt;: Based on the page flow diagram, sit down with
  your engineer and make a list of tasks. My favourite tool for capturing task
  level breakdown is &lt;a href=&quot;http://www.pivotaltracker.com&quot;&gt;Pivotal Tracker&lt;/a&gt;. But, you
  could easily use anything else or even paper. 

	&lt;p&gt;Try, &lt;a href=&quot;http://www.redmine.org&quot;&gt;Redmine&lt;/a&gt;,
&lt;a href=&quot;http://unfuddle.com&quot;&gt;Unfuddle&lt;/a&gt; or &lt;a href=&quot;http://studios.thoughtworks.com/mingle-agile-project-management&quot;&gt;Mingle&lt;/a&gt;&lt;/p&gt;


	&lt;p&gt;All of these tools can also serve as the bug database once the project gets
going.&lt;/p&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;strong&gt;Get estimates&lt;/strong&gt;: You should try to get an idea of the effort estimate, in
  terms of days or weeks, for all the tasks you have listed. It will be rough
  and would most likely prove to be inaccurate. But the actual numbers are not
  important. Rather, it will help you see the relative cost of different
  features.

	&lt;p&gt;In any case, it will help you prioritize tasks. You already knew what was
important and not so important for your business. Now you know how much
they roughly cost. Do it. Quite often, it is surprising.&lt;/p&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;strong&gt;Get detailed estimates&lt;/strong&gt;: Just before you are about to start implementation,
  ask for detailed estimates for at least the first few tasks. You should try
  to fill at least the next two weeks with work.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;strong&gt;Ask for a status report&lt;/strong&gt;: Most likely, whatever estimates you have got at the
  beginning is going to change as project progresses. Also, you are going to
  change your mind about features that you want implemented. A weekly status
  report is a good way to keep track of these things.

Make sure to include the following in the reports:
	&lt;ol&gt;
	&lt;li&gt;List of tasks completed last week with amount of time spent on each task&lt;/li&gt;
		&lt;li&gt;Tasks which will be worked on in the next week&lt;/li&gt;
		&lt;li&gt;Important discussions that happened and decisions taken&lt;/li&gt;
	&lt;/ol&gt;


	&lt;p&gt;Of course, these reports will help you settle invoices later.&lt;/p&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;strong&gt;Set up a regular call schedule&lt;/strong&gt;: This is very much dependent on the momentum of the
  project and what suits the team. The underlying point is take regular stock
  of how things are progressing.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;strong&gt;Arrange for a staging server&lt;/strong&gt;: While your app is under development, you should arrange for it to be
  deployed some place where you can review it. It could be some shared hosting
  or a cheap &lt;span class=&quot;caps&quot;&gt;VPS&lt;/span&gt; plan.

	&lt;p&gt;Make sure to protect the staging server with an &lt;a href=&quot;http://httpd.apache.org/docs/1.3/programs/htpasswd.html&quot;&gt;htpasswd&lt;/a&gt; to prevent
casual visitors from any unauthorized peek and stop crawers and search engines. Also, if you are developing a data driven app where you are storing seed data in the staging server while you are developing the application, make sure it is &lt;a href=&quot;http://www.magnionlabs.com/2009/7/7/db-backups&quot;&gt;backed up&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;strong&gt;Arrange for source code repository&lt;/strong&gt;: The code that your engineers are
 developing for you are really the only &#8220;thing&#8221; you are producing. It is worth
 protecting it safely. Make sure you arrange for a code repository (&lt;a href=&quot;http://subversion.tigris.org/&quot;&gt;Subversion&lt;/a&gt;
 and &lt;a href=&quot;http://git-scm.com&quot;&gt;Git&lt;/a&gt; are popular these days) and make sure it is safely
 backed up. Good ones are: &lt;a href=&quot;http://github.com/&quot;&gt;Github&lt;/a&gt;,
 &lt;a href=&quot;http://unfuddle.com&quot;&gt;Unfuddle&lt;/a&gt; and &lt;a href=&quot;http://www.assembla.com&quot;&gt;Assembla&lt;/a&gt;). It also
 serves as an important development tool &#8211; most developers worth their salt
 won&#8217;t write any code without it.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;h3&gt;Final words&lt;/h3&gt;


	&lt;p&gt;If you are interested in being more thorough, you can start by reading the
&lt;a href=&quot;http://www.joelonsoftware.com/articles/fog0000000043.html&quot;&gt;Joel test&lt;/a&gt; and of
course no discussion of software development can be complete without a
reference to &lt;a href=&quot;http://www.amazon.com/Mythical-Man-Month-Software-Engineering-Anniversary/dp/0201835959&quot;&gt;The Mythical Man
Month&lt;/a&gt;
and &lt;a href=&quot;http://www.cc2e.com/&quot;&gt;The Code Complete&lt;/a&gt;&lt;/p&gt;


	&lt;p&gt;Although, this is a discussion on things to do at the beginning of a project,
I should mention that you should make sure to arrange for QA soon after you start.&lt;/p&gt;


	&lt;p&gt;Of course, this is just the beginning and similarly there are other important
things for the in-progress and the at end of a project to take care of as a
business owner. On that, sometime later.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://www.magnionlabs.com/">
    <author>
      <name>akmathur</name>
    </author>
    <id>tag:www.magnionlabs.com,2009-07-07:39</id>
    <published>2009-07-07T19:18:00Z</published>
    <updated>2009-07-07T19:59:56Z</updated>
    <category term="Blog"/>
    <category term="Web Application Development"/>
    <link href="http://www.magnionlabs.com/2009/7/7/db-backups" rel="alternate" type="text/html"/>
    <title>DB Backups</title>
<summary type="html">&lt;p&gt;Having a robust database backup scheme is essential for any production application. Here&#8217;s a brief summary of popular schemes used with Rails applications and a description of my own favorite.&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;Having a robust database backup scheme is essential for any production application. Here&#8217;s a brief summary of popular schemes used with Rails applications and a description of my own favorite.&lt;/p&gt;
&lt;p&gt;Every application in production needs some sort of database backup scheme. There are plenty of methodologies and several Rails scripts or plugins to do just that. Here&#8217;s a brief summary of some of the popular ones:&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;a href=&quot;http://code.google.com/p/ar-backup/&quot;&gt;ar-backup&lt;/a&gt; is a Rails plugin which saves data as fixtures. The data of course becomes database independent. However, to store it safely you will have to push them to your &lt;a href=&quot;http://en.wikipedia.org/wiki/Revision_control&quot;&gt;&lt;span class=&quot;caps&quot;&gt;SCM&lt;/span&gt;&lt;/a&gt; or manage backups separately.&lt;/li&gt;
		&lt;li&gt;A comprehensive backup system of DB data, code and &lt;span class=&quot;caps&quot;&gt;SCM&lt;/span&gt; to Amazon S3 is on &lt;a href=&quot;http://www.rubyinside.com/advent2006/15-s3rake.html&quot;&gt;Ruby Inside&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a href=&quot;http://info-architects.net/2007/08/25/rake-task-for-mysql-backup-to-amazon-s3&quot;&gt;here&lt;/a&gt; is a simple rake task to take a &lt;a href=&quot;http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html&quot;&gt;mysqldump&lt;/a&gt; and push it to S3. There is no scheme for rolling backups, but if you want a simple solution, this may be enough. &lt;/li&gt;
		&lt;li&gt;For a large database where full backups may be expensive, see &lt;a href=&quot;http://pauldowman.com/2009/02/08/mysql-s3-backup&quot;&gt;this&lt;/a&gt;. There&#8217;s also a &lt;a href=&quot;http://github.com/xaviershay/db2s3/tree/master&quot;&gt;Rails plugin using this&lt;/a&gt;, however at the time of writing it seems incomplete.&lt;/li&gt;
		&lt;li&gt;The awesome guys at &lt;a href=&quot;http://collectiveidea.com/&quot;&gt;Collective Idea&lt;/a&gt; have a polished Rails plugin: for backing up the database as fixtures. It also has some nifty features like ability to pull data back into development server. Read about it &lt;a href=&quot;http://opensoul.org/2008/4/27/awesomeness-database-backups&quot;&gt;here&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;Finally, &lt;a href=&quot;http://www.viget.com/extend/backup-your-database-in-git/&quot;&gt;a novel approach&lt;/a&gt; of backing up the database in a &lt;a href=&quot;http://git-scm.com/&quot;&gt;Git&lt;/a&gt; repository which seems will work for databases which are not growing very rapidly.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;However, surprisingly, none of them fitted exactly what I needed and so I decided to roll my own. Also, it is quite straightforward as you will see. This is what I wanted from a DB backup system:&lt;/p&gt;


	&lt;p&gt;Take periodic dumps of the MySQL database and push them to S3 for safe storage. However, keep the old backups so that if the database gets corrupted or I want to look at the history, I have old ones available. But, I don&#8217;t want all the old ones (to cut down on storage charges), perhaps just last couple of weeks&#8217; ones.&lt;/p&gt;


	&lt;p&gt;Courtesy of &lt;a href=&quot;http://blog.craigambrose.com/articles/2007/03/01/a-rake-task-for-database-backups&quot;&gt;this solution&lt;/a&gt;, which provides rolling backups but saves to disk and some help from &lt;a href=&quot;http://amazon.rubyforge.org/doc&quot;&gt;Amazon&lt;/a&gt;, I wrote this rake task. If you want to use it, copy this in lib/tasks/db_backup.rake of your Rails project&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
require 'find'
require 'ftools'
require 'aws/s3'

namespace :db do
  desc &quot;Backup the database to a file. Options: RAILS_ENV=production MAX=28&quot; 
  task :backup =&amp;gt; [:environment] do
    AWS::S3::Base.establish_connection!(:access_key_id =&amp;gt; 'your-S3-access-key', :secret_access_key =&amp;gt; 'your-S3-secret-access-key')
    BUCKET = 'A-S3-bucket-name-you-created'

    datestamp = Time.now.strftime(&quot;%Y-%m-%d_%H-%M-%S&quot;)
    base_path = ENV[&quot;RAILS_ROOT&quot;] || &quot;.&quot; 
    file_name = &quot;#{RAILS_ENV}_dump-#{datestamp}.sql.gz&quot; 
    backup_file = File.join(base_path, &quot;tmp&quot;, file_name)
    db_config = ActiveRecord::Base.configurations[RAILS_ENV]
    sh &quot;mysqldump -u #{db_config['username']} -p#{db_config['password']} -Q --add-drop-table -O add-locks=FALSE -O lock-tables=FALSE #{db_config['database']} | gzip -c &amp;gt; #{backup_file}&quot; 
    AWS::S3::S3Object.store(file_name, open(backup_file), BUCKET)
    puts &quot;Created backup: #{file_name}&quot; 
    FileUtils.rm_rf(backup_file)

    bucket = AWS::S3::Bucket.find(BUCKET)
    all_backups = bucket.objects.select { |f| f.key.match(/dump/) }.sort { |a,b| a.key &amp;lt;=&amp;gt; b.key }.reverse
    max_backups = ENV[&quot;MAX&quot;].to_i || 28
    unwanted_backups = all_backups[max_backups..-1] || []
    for unwanted_backup in unwanted_backups
      unwanted_backup.delete
      puts &quot;deleted #{unwanted_backup.key}&quot; 
    end
    puts &quot;Deleted #{unwanted_backups.length} backups, #{all_backups.length - unwanted_backups.length} backups available&quot; 
  end
end

&lt;/code&gt;&lt;/pre&gt;

 Then set up a cron job on your production host to call this:

&lt;pre&gt;&lt;code&gt;
rake db:backup RAILS_ENV=production MAX=8 # take a backup of production DB, push the file to S3, keep past 8 copies
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;You can use S3Fox to keep a watch on backup files as they get pushed to S3. If you ever need to import back the database into local desktop &#8211; use S3Fox to download the file and do this on your development machine:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
gzip -dc production_dump-YYYY-MM-DD_HH-MM-SS.sql.gz | mysql -u root -p &amp;lt;development database&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
          </content>  </entry>
  <entry xml:base="http://www.magnionlabs.com/">
    <author>
      <name>akmathur</name>
    </author>
    <id>tag:www.magnionlabs.com,2009-03-23:19</id>
    <published>2009-03-23T20:34:00Z</published>
    <updated>2009-07-03T06:06:05Z</updated>
    <category term="Blog"/>
    <category term="Web Application Development"/>
    <link href="http://www.magnionlabs.com/2009/3/23/rails-migrations-revisited" rel="alternate" type="text/html"/>
    <title>Rails migrations revisited</title>
<summary type="html">&lt;p&gt;Rails Database migrations is a great piece of technology and deservedly popular. However, there are aspects of it which are not quite well understood. Here I discuss couple of such points: how to manage the schema.rb file and how to handle data migrations.&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;Rails Database migrations is a great piece of technology and deservedly popular. However, there are aspects of it which are not quite well understood. Here I discuss couple of such points: how to manage the schema.rb file and how to handle data migrations.&lt;/p&gt;
&lt;p&gt;No, we are not back to 2007 again. There are just a few things about
migrations that I think some people have still not got right. So, I thought I
will highlight them here.&lt;/p&gt;


	&lt;p&gt;Rails have had migrations for quite a few releases now. Here&#8217;s a brief review:&lt;/p&gt;


	&lt;h4&gt;Recap&lt;/h4&gt;


	&lt;p&gt;When you want to do a change in your database schema, like add a column or change a
table definition, you generate a migration, populate the code for forward
and backward migrations, and run rake db:migrate. It let&#8217;s you change your
DB incrementally. Everybody gets this part I think. See &lt;a href=&quot;http://guides.rubyonrails.org/migrations.html&quot;&gt;Rails guides&lt;/a&gt; for a wonderful overview.&lt;/p&gt;


	&lt;h4&gt;schema.rb file&lt;/h4&gt;


	&lt;p&gt;Running a migration updates the db/schema.rb file. It is required to put
this in your source control and check it in with the migration. A lot of
people actively ignore this file (by using svn:ignore or .gitignore). Don&#8217;t.&lt;/p&gt;


Migrations are useful when you are upgrading your database. Where as if you
are setting up a new instance of the database (say a new user joins your
team or you are setting up a new staging server), you should not be running the
migrations. Instead do this:
&lt;pre&gt;
&lt;code&gt;
  $ rake db:create
  $ rake db:schema:load
&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Running a long winded migrations, in most non trivial projects, is almost
bound to fail (because of name changes in your source code, since you are not going back and
updating your migrations). This is official Rails policy (see the comment on
top of your db/schema.rb or &lt;span class=&quot;caps&quot;&gt;DHH&lt;/span&gt;&#8217;s code commit &lt;a href=&quot;http://github.com/rails/rails/commit/0f2c6302a19abce498d6cdbd44df0131c51fc8a3&quot;&gt;here&lt;/a&gt;)&lt;/p&gt;


	&lt;p&gt;&lt;a href=&quot;http://www.pathf.com/blogs/2008/07/resolved-should-schemarb-be-included-in-your-source-control/&quot;&gt;See here&lt;/a&gt;
for a summary of the opposite view.&lt;/p&gt;


	&lt;h4&gt;Data migrations&lt;/h4&gt;


	&lt;p&gt;Data migration is porting the data in the tables to the new
schema. Unfortunately, Rails does not have a clearly specified way of dealing
with this. Usually developers do not treat this as a separate issue but handle
it as part of usual Rails migrations.&lt;/p&gt;


There are two cases when you may find yourself dealing with data in migrations:
	&lt;ul&gt;
	&lt;li&gt;while seeding the database with some data, or&lt;/li&gt;
		&lt;li&gt;porting the data in older tables to newer schema.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;Most of the times it is possible to handle both using migrations. However, for the
second case, you may sometimes need to create special migration scripts.&lt;/p&gt;


	&lt;p&gt;However, if you are not running migrations to start a new database, you still
need a way to seed the database with the required data. Here is something I
have used which has worked well for several projects which I picked up from
&lt;a href=&quot;http://quotedprintable.com/2007/11/16/seed-data-in-rails&quot;&gt;here&lt;/a&gt;&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;In addition to creating a migration, put seed data in db/fixtures/*.yml&lt;/li&gt;
		&lt;li&gt;load the seed data from db/fixtures when initializing a new database&lt;/li&gt;
	&lt;/ul&gt;


&lt;pre&gt;
&lt;code&gt;

$ rake db:create
$ rake db:schema:load
$ rake db:seed # see link above for Rake task definition for this

&lt;/code&gt;
&lt;/pre&gt;

	&lt;h4&gt;conclusion&lt;/h4&gt;


	&lt;p&gt;Most projects ignore data migrations during development, which is not entirely
wrong. Who cares for lost data during development? But, you will need a robust
strategy for handling data migrations once you are on production and you
should prepare yourself with a methodology well in advance. And a last final
tip, backup your production database before running any migrations.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://www.magnionlabs.com/">
    <author>
      <name>akmathur</name>
    </author>
    <id>tag:www.magnionlabs.com,2009-02-28:16</id>
    <published>2009-02-28T20:08:00Z</published>
    <updated>2009-07-06T11:57:28Z</updated>
    <category term="Blog"/>
    <category term="Web Application Development"/>
    <link href="http://www.magnionlabs.com/2009/2/28/background-job-processing-in-rails-with-delayed_job" rel="alternate" type="text/html"/>
    <title>Background job processing in Rails with delayed_job </title>
<summary type="html">&lt;p&gt;Running jobs in background is part of every non-trivial web application &#8211; for either speeding up user response, or running periodically scheduled tasks. Here, I explain how to install, configure and use the elegant &lt;a href=&quot;http://github.com/tobi/delayed_job/tree/master&quot;&gt;delayed_job&lt;/a&gt; plugin to process background jobs.&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;Running jobs in background is part of every non-trivial web application &#8211; for either speeding up user response, or running periodically scheduled tasks. Here, I explain how to install, configure and use the elegant &lt;a href=&quot;http://github.com/tobi/delayed_job/tree/master&quot;&gt;delayed_job&lt;/a&gt; plugin to process background jobs.&lt;/p&gt;
&lt;h3&gt;Why background processing is needed&lt;/h3&gt;


	&lt;p&gt;Since Ruby 1.8 only supports &lt;a href=&quot;http://en.wikipedia.org/wiki/Green_threads&quot;&gt;green threads&lt;/a&gt;, if you want to process something longish as part of a web request in Rails, it will delay the
response. Of course, if the processing is not critical to returning
a response to the client, it&#8217;s wiser to push the processing to a background
queue and return a response immediately.&lt;/p&gt;


	&lt;p&gt;There are other incidental benefits to using a background job processing queue like, letting a dedicated server, other than the customer facing app server, handle it, assigning priority to jobs, retry on failure etc.&lt;/p&gt;


	&lt;p&gt;Most common situations where such a background processing is needed are: sending
emails to users, rebuilding search indices, image and video processing, etc.&lt;/p&gt;


	&lt;h3&gt;Available options&lt;/h3&gt;


	&lt;p&gt;There are &lt;a href=&quot;http://backgroundrb.rubyforge.org/&quot;&gt;several&lt;/a&gt;
&lt;a href=&quot;http://github.com/purzelrakete/workling/tree/master&quot;&gt;ways&lt;/a&gt;
 &lt;a href=&quot;http://codeforpeople.com/lib/ruby/bj/&quot;&gt;to&lt;/a&gt;
 process background jobs in Rails. In fact, So many
that &lt;a href=&quot;http://geoffreygrosenbach.com/&quot;&gt;Geoffrey Grosenbach&lt;/a&gt; joked on the &lt;a href=&quot;http://www.railsenvy.com/2009/1/8/rails-envy-podcast-episode-062-01-07-2009&quot;&gt;RailsEnvy
podcast&lt;/a&gt;
about the number of continuous integration servers finally being equal to number of queuing servers available in Ruby.&lt;/p&gt;


	&lt;p&gt;My favorite one so far is:
&lt;a href=&quot;http://github.com/tobi/delayed_job/tree/master&quot;&gt;delayed_job&lt;/a&gt;. Because its
simple to set up, simple to use and has lot of powerful features. However,
don&#8217;t forget to look at others to see what fits you needs and style
better. For an overview &lt;a href=&quot;http://www.scribd.com/doc/2589535/Handling-LongRunning-Tasks-in-Rails&quot;&gt;see here&lt;/a&gt;. In the rest of the article, I will explain how to install and use delayed_job.&lt;/p&gt;


	&lt;h3&gt;Installation&lt;/h3&gt;


	&lt;p&gt;Firstly, install it in your rails project just as you would any other plugin:&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
$ ruby script/plugin install git://github.com/tobi/delayed_job.git
&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Delayed_job stores the jobs in a table in the database. Create the table using
a migration:&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
$ ruby script/generate migration create_table_for_delayed_job

class CreateTableForDelayedJob &amp;lt; ActiveRecord::Migration
  def self.up
    create_table :delayed_jobs, :force =&amp;gt; true do |t|
      t.integer  :priority, :default =&amp;gt; 0
      t.integer  :attempts, :default =&amp;gt; 0
      t.text     :handler
      t.text     :last_error
      t.datetime :run_at
      t.datetime :locked_at
      t.datetime :failed_at
      t.string   :locked_by
      t.timestamps
    end
  end

  def self.down
    drop_table :delayed_jobs
  end
end

$ rake db:migrate
&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Note: Compared to the &lt;a href=&quot;http://github.com/tobi/delayed_job/tree/master&quot;&gt;documentation&lt;/a&gt;, I have changed last_error column to text from string to handle larger error messages&lt;/p&gt;


	&lt;h3&gt;Delay jobs&lt;/h3&gt;


	&lt;p&gt;Restart your server, and you can start delaying jobs. There are two ways to
push a job to background. First, the easy way:&lt;/p&gt;


	&lt;p&gt;You have seen Ruby&#8217;s
&lt;a href=&quot;http://www.ruby-doc.org/core/classes/Object.html#M000334&quot;&gt;send&lt;/a&gt; method, right.&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
&quot;Bangalore&quot;.length # returns 9
&quot;Bangalore&quot;.send(:length) # same as above, returns 9
&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;&lt;em&gt;send&lt;/em&gt; just invokes the given method on the object.&lt;/p&gt;


	&lt;p&gt;Analogous to that, delayed_job adds send_later method. Say, if you were sending
a mail to user on registration:&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
NotificationMailer.deliver_welcome_user(@user)
&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Just change that to:&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
NotificationMailer.send_later(:deliver_welcome_user, @user)
&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;And you are done. delayed_job will push this into the queue (the database
table you created above), to be executed later.&lt;/p&gt;


	&lt;p&gt;There is another way to background a job. First, create a job class.&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
# put this in lib/delayed_notification.rb
class DelayedNotification
  attr_accessor :user_id
  def initialize(user_id)
    self.user_id = user_id
  end

  def perform
   NotificationMailer.deliver_welcome_user(User.find(@user_id))
  end
end

# Add this where you were sending the mail earlier
Delayed::Job.enqueue DelayedNotification.new(@user.id)
&lt;/code&gt;
&lt;/pre&gt;

	&lt;h3&gt;Executing the jobs&lt;/h3&gt;


	&lt;p&gt;Now, there are several ways to run the job which are there in the queue. In development mode, you can just issue the following command in your terminal:&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
$ rake jobs:work
&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;This will cause the worker to run in a loop. Stop it by pressing Control-C.&lt;/p&gt;


	&lt;p&gt;On production, you would want the worker to be running all the time. Also, it
will be nice to have the ability to stop the worker just before the deployment
and start it again once the deployment finishes. It sounds complicated, but
its pretty easy to set up.&lt;/p&gt;


	&lt;p&gt;First, install the &lt;a href=&quot;http://daemons.rubyforge.org/&quot;&gt;daemons&lt;/a&gt; gem:&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
# Add in environment.rb
 config.gem 'daemons'

$ rake gems:install
&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Then, copy &lt;a href=&quot;http://gist.github.com/54682&quot;&gt;this script&lt;/a&gt; in your rails project in file script/delayed_job and give it execute permission. This creates a worker daemon, which when started keeps running as a background process.&lt;/p&gt;


	&lt;p&gt;Alternately, instead of &lt;a href=&quot;http://daemons.rubyforge.org/&quot;&gt;daemons&lt;/a&gt; gem, you can use &lt;a href=&quot;http://github.com/alexvollmer/daemon-spawn/tree/master&quot;&gt;daemon-spawn&lt;/a&gt; gem.&lt;/p&gt;


	&lt;p&gt;Install the gem on the host where you want the delayed_job daemon to run:&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
$ sudo gem sources -a http://gems.github.com
$ sudo gem install alexvollmer-daemon-spawn
&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;And then copy &lt;a href=&quot;http://gist.github.com/104314&quot;&gt;this script&lt;/a&gt; instead in script/delayed_job. Rest all of the following steps are identical, whichever gem and script/delayed_job you choose.&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
# start the worker daemon
$ ruby script/delayed_job start

# stop it
$ ruby script/delayed_job stop
&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;You would of course want to start and stop it on your production server using &lt;a href=&quot;http://www.capify.org/&quot;&gt;Capistrano&lt;/a&gt;. Here&#8217;s a recipe to do that (courtesy &lt;a href=&quot;http://github.com/collectiveidea/delayed_job/tree/master&quot;&gt;collectiveidea&lt;/a&gt;)&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
# add this to config/deploy.rb
namespace :delayed_job do
  desc &quot;Start delayed_job process&quot; 
  task :start, :roles =&amp;gt; :app do
    run &quot;cd #{current_path}; script/delayed_job start #{rails_env}&quot; 
  end

  desc &quot;Stop delayed_job process&quot; 
  task :stop, :roles =&amp;gt; :app do
    run &quot;cd #{current_path}; script/delayed_job stop #{rails_env}&quot; 
  end

  desc &quot;Restart delayed_job process&quot; 
  task :restart, :roles =&amp;gt; :app do
    run &quot;cd #{current_path}; script/delayed_job restart #{rails_env}&quot; 
  end
end

after &quot;deploy:start&quot;, &quot;delayed_job:start&quot; 
after &quot;deploy:stop&quot;, &quot;delayed_job:stop&quot; 
after &quot;deploy:restart&quot;, &quot;delayed_job:restart&quot; 
&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;And you are done. Just deploy as usual.&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
$ cap deploy:migrations
&lt;/code&gt;
&lt;/pre&gt;

	&lt;h3&gt;Further tips and tricks&lt;/h3&gt;


	&lt;ul&gt;
	&lt;li&gt;Get a separate server to process your delayed job so as not to take &lt;span class=&quot;caps&quot;&gt;CPU&lt;/span&gt; away from customer facing app server.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;You can customize some parameters like how many times to retry on failure and prune runaway tasks. See &lt;a href=&quot;http://wiki.github.com/tobi/delayed_job&quot;&gt;here&lt;/a&gt;.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Delayed_job allows you to assign priority to jobs.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;In development mode, if you just want to discard pending jobs instead of running them:&lt;/li&gt;
	&lt;/ul&gt;


&lt;pre&gt;
&lt;code&gt;
$ rake jobs:clear
&lt;/code&gt;
&lt;/pre&gt;

	&lt;ul&gt;
	&lt;li&gt;If you want to control the time at which the job gets executed, you can specify it as an argument to enqueue while delaying the job:&lt;/li&gt;
	&lt;/ul&gt;


&lt;pre&gt;
&lt;code&gt;
Delayed::Job.enqueue DelayedNotification.new(@user.id), 0, 15.minutes.from_now
&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Here, 0 denotes the (default) priority of the task. This task will get executed at least 15 minutes later than it would have been executed normally.&lt;/p&gt;


	&lt;h3&gt;References&lt;/h3&gt;


For more about this wonderful plugin, refer to these resources: 
	&lt;ul&gt;
	&lt;li&gt;A nice &lt;a href=&quot;http://railstips.org/2008/11/19/delayed-gratification-with-rails&quot;&gt;tutorial&lt;/a&gt; covering the basics.&lt;/li&gt;
		&lt;li&gt;Home of &lt;a href=&quot;http://github.com/tobi/delayed_job/tree/master&quot;&gt;delayed_job&lt;/a&gt; (also look at the &lt;a href=&quot;http://wiki.github.com/tobi/delayed_job&quot;&gt;wiki&lt;/a&gt;).&lt;/li&gt;
	&lt;/ul&gt;
          </content>  </entry>
  <entry xml:base="http://www.magnionlabs.com/">
    <author>
      <name>akmathur</name>
    </author>
    <id>tag:www.magnionlabs.com,2009-02-17:15</id>
    <published>2009-02-17T19:09:00Z</published>
    <updated>2009-07-03T06:14:21Z</updated>
    <category term="Blog"/>
    <category term="Computer Science"/>
    <link href="http://www.magnionlabs.com/2009/2/17/why-i-am-thankful-for-all-the-maintenance-programming-i-did" rel="alternate" type="text/html"/>
    <title>Why I am thankful for all the maintenance programming I did</title>
<summary type="html">&lt;p&gt;Although maintenance programming is no one&#8217;s dream job, they can help you learn a lot of practical lessons and mature as a developer. I have done my fair share and here&#8217;s how I think it helped me grow.&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;Although maintenance programming is no one&#8217;s dream job, they can help you learn a lot of practical lessons and mature as a developer. I have done my fair share and here&#8217;s how I think it helped me grow.&lt;/p&gt;
&lt;p&gt;Recently, an article bubbled up in &lt;a href=&quot;http://delicious/popular&quot;&gt;delicious popular&lt;/a&gt; that caught my eye: &lt;a href=&quot;http://www.andrewmoore.com/public/index.php/Why_I_Don%27t_Mind_Maintenance_Programming&quot;&gt;Why I Don&#8217;t Mind Maintenance Programming&lt;/a&gt;&lt;/p&gt;


	&lt;p&gt;As the author notes, almost every developer wants to work on a new project. So much so that, it is invariably brought up in job interviews either by companies to sell their position or by candidates trying to decide whether to take up an offer. I was no different when I graduated from &lt;a href=&quot;http://www.iitkgp.ernet.in/&quot;&gt;college&lt;/a&gt; and was duly disappointed when couple of months into my &lt;a href=&quot;http://www.cadence.com/in&quot;&gt;first job&lt;/a&gt; I realized I would be doing maintenance of several legacy systems. Only later did I realize the whole lot of good that it did to me:&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;I got to see what really good code, written by experienced developers, looked like. Common idioms and styles which make a code base maintainable for long (there was one product which was over 12 years old and still pretty clean).&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;I got to see what really bad code looked like. Code most likely written by rookies or people in hurry to get their little feature done. I probably cannot emphasize enough how illuminating it is to actually &lt;a href=&quot;http://thedailywtf.com/&quot;&gt;look at bad code&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Although it is easy to dismiss something as &#8220;bad code&#8221;, it is much harder to realize that it is pragmatism which is most important. Ultimately, we are building a product to be used by customers. Having clean code is important only as much as it helps you do other future changes quickly enough. Doing maintenance of other people&#8217;s code makes you keenly aware of what real life code looks like. You will never cringe at some small stylistic gotchas in code, but rather focus on the bigger picture of getting it correct and efficient.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;One other important thing that it taught me was importance of writing tests. When you are doing maintenance, you live or die by your test suite. Also, only later I realized that the nifty trick of writing tests first before doing the bug fix or a feature that I was using had a name for it already (&lt;a&gt;&lt;span class=&quot;caps&quot;&gt;TDD&lt;/span&gt;&lt;/a&gt;).&lt;/li&gt;
	&lt;/ul&gt;


	&lt;ul&gt;
	&lt;li&gt;Of course, while doing maintenance, you get to see the difference you are making to the life of a customer, almost immediately.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;I think doing maintenance programming was a significant factor to help me grow as a developer and shaped my judgment ever since. I strongly recommend every beginner developer to spend at least a year or two doing maintenance. With the spread of open source, it has become all the much easier to look at other people&#8217;s code.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://www.magnionlabs.com/">
    <author>
      <name>akmathur</name>
    </author>
    <id>tag:www.magnionlabs.com,2009-02-14:14</id>
    <published>2009-02-14T18:13:00Z</published>
    <updated>2009-07-03T06:15:59Z</updated>
    <category term="Blog"/>
    <category term="Computer Science"/>
    <link href="http://www.magnionlabs.com/2009/2/14/what-s-a-computer" rel="alternate" type="text/html"/>
    <title>What's a computer?</title>
<summary type="html">&lt;p&gt;Back in the days, how one of my teachers defined a &#8220;Computer&#8221; for me and it has stuck with me since then.&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;Back in the days, how one of my teachers defined a &#8220;Computer&#8221; for me and it has stuck with me since then.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://www.chetnavardhan.com&quot;&gt;My wife&lt;/a&gt; once told me about her first lecture in Computer Science back in her college days. The teacher walked in and started talking about history of computers, data, files, computer languages and &#8220;lots of other hyperbole&#8221;. She didn&#8217;t understand anything out of the one hour lecture. Soon after that, she switched to &lt;a href=&quot;http://en.wikipedia.org/wiki/Political_science&quot;&gt;Political Science&lt;/a&gt;.&lt;/p&gt;


	&lt;p&gt;I have heard similar stories of people getting a rough introduction to computers. That got me thinking about how I got introduced to computers. I remember in my very first class (I was 12 then), my teacher Mr. Jhulan Chakraborty started by explaining what a computer is. What he said, stayed with me ever since:&lt;/p&gt;


	&lt;p&gt;A computer is a machine &#8211; just like a ceiling fan, a sewing machine, or an engine in a car. But, it&#8217;s a different kind of machine because of two important properties:&lt;/p&gt;


	&lt;ol&gt;
	&lt;li&gt;You can provide a step by step instructions to it and it will follow the instructions exactly to the letter &#8211; without any error. Just as you provide instructions to your housemaid for a task. However, unlike a human&#8212;&lt;/li&gt;
		&lt;li&gt;A computer while following the instructions, can do repetitive tasks, without getting bored, without any error, and with substantial speed.&lt;/li&gt;
	&lt;/ol&gt;


	&lt;p&gt;That&#8217;s it. That is all a computer is.&lt;/p&gt;


	&lt;p&gt;I think, that is a brilliant introduction. It is concise and accurate. It also serves as a baseline for introduction of more advanced topics. For example, programming languages are just a language for specifying the instructions to a computer (see step 1 above).&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://www.magnionlabs.com/">
    <author>
      <name>admin</name>
    </author>
    <id>tag:www.magnionlabs.com,2008-07-13:9</id>
    <published>2008-07-13T19:20:00Z</published>
    <updated>2009-07-18T08:41:04Z</updated>
    <category term="Blog"/>
    <category term="Computer Science"/>
    <link href="http://www.magnionlabs.com/2008/7/13/file-formats" rel="alternate" type="text/html"/>
    <title>File Formats</title>
<summary type="html">File formats are crucial to how digital data is saved and their longevity. This is an introductory article for some not very familiar with what they are.</summary><content type="html">
            File formats are crucial to how digital data is saved and their longevity. This is an introductory article for some not very familiar with what they are.
&lt;h3&gt;What is a file format&lt;/h3&gt;
&lt;p&gt;
File Format is a way of putting your software application's data into
a file on the disk when you do a save.
&lt;/p&gt;
&lt;p&gt;
For example, if you create a document using a spreadsheet application,
when you save the document, the file format should have ways to store
how the data is organised in rows and columns, where you have put
colours etc. so that you can later re-open the saved document
in the application and it should look exactly the same as you created
it. File formats are ways of encoding the information in the document,
so that they can be stored in files on disks.
&lt;/p&gt;

&lt;h3&gt;Why are they needed&lt;/h3&gt;
&lt;p&gt;
As stated above, they are needed so that you can
save your application to disk. The disk files are really just one long string
of bytes - like a very long sentence. So, file formats specify how how the
information in a document is converted to a string of bytes.
&lt;/p&gt;
&lt;p&gt;
There is another reason for file formats: they allow documents created
in one application to be opened using another application when the two
applications understand a common file format. For example, you can
create a drawing using the drawing application, save it, then open
it in your word processor.
&lt;/p&gt;

&lt;h3&gt;OK, what's the controversy&lt;/h3&gt;
&lt;p&gt;
Well, my goal is to just make you aware of idea of file formats and
not go into any controversy. However, you should be aware of the
controversy. So, here it is.
&lt;/p&gt;
&lt;p&gt;
There are two types of formats: open and closed. Open formats are those that
have a written specification for the format which is available to everybody. Anybody can write an
application to read or write a file in that format. Closed ones are
those whose specifications are not public. There are some formats which fall
some where in between - their specifications not public but available
from the creators for a fee and some legal formalities.
&lt;/p&gt;

&lt;h3&gt;But, why should I care&lt;/h3&gt;
&lt;p&gt;
As mentioned above, file formats are vital for data exchange between
applications. For example, your digital camera stores an image in TIFF
format but you can later convert it to JPG to put it on your blog. The
camera need not be programmed with producing every possible image
format because it produces the image in an open format. Anyone can
write an application to read the camera's captured image in TIFF and
convert it to a different format. It also helps with
future-proofing. Since your camera produces images in an open format,
there is a good chance that it will be supported by new image editing
softwares even when your camera vendor stops supporting your
camera, since anybody can read your image files because its in an open
format.
&lt;/p&gt;

&lt;p&gt;
File formats are used extensively in EDA (Electronic Design Automation), which is where I became
aware of them. EDA vendors produce software to create electronic
designs. Electronic design work happens in steps: first comes the schematic capture,
followed by a simulation and then synthesis and then placement and
routing. The software to do each of these steps can come from
a different vendor and hence the tools need to talk to each
other. However, when a software is being written, the developer does
not clearly know what exact software
 will come before and after it. So, the industry has agreed to use
file formats, each software tool is build with ability to import a
standard file format and export data in that standard file format. Problem Solved.
&lt;/p&gt;

&lt;p class=&quot;ps&quot;&gt;
Postscript: One of the popular EDA file format is LEF &amp; DEF created by Cadence
Design System and later open sourced. I worked on the Cadence's
original LEF &amp; DEF reader and writer which was also the first project I
worked on as a software professional.
&lt;/p&gt;
          </content>  </entry>
</feed>
