<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	>

<channel>
	<title>Rida Al Barazi's Personal Blog &#187; Programming</title>
	<atom:link href="http://rida.me/blog/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://rida.me/blog</link>
	<description>Rida's Zone in Cyberspace</description>
	<pubDate>Sat, 14 Feb 2009 14:49:55 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Testing your Rails plugin</title>
		<link>http://rida.me/blog/2008/11/18/testing-your-rails-plugin/</link>
		<comments>http://rida.me/blog/2008/11/18/testing-your-rails-plugin/#comments</comments>
		<pubDate>Tue, 18 Nov 2008 19:00:37 +0000</pubDate>
		<dc:creator>Rida</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Ruby on Rails]]></category>

		<category><![CDATA[Tutorials]]></category>

		<category><![CDATA[ruby]]></category>

		<category><![CDATA[testing]]></category>

		<category><![CDATA[tests]]></category>

		<guid isPermaLink="false">http://www.ridaalbarazi.com/blog/?p=167</guid>
		<description><![CDATA[When I first released both ArabicHelper and SimplySearchable I didn&#8217;t have any tests for them because I didn&#8217;t know the right way to write those tests. After doing some digging and looking at other plugins tests I found out how, and I&#8217;m sharing that here with you.
Specifically for ActiveRecord extensions you need a database and [...]]]></description>
			<content:encoded><![CDATA[<p>When I first released both <a href="http://www.ridaalbarazi.com/blog/2008/10/12/arabic-helper-ruby-on-rails/">ArabicHelper</a> and <a href="http://www.ridaalbarazi.com/blog/2008/11/05/simplysearchable-plugin/">SimplySearchable</a> I didn&#8217;t have any tests for them because I didn&#8217;t know the right way to write those tests. After doing some digging and looking at other plugins tests I found out how, and I&#8217;m sharing that here with you.</p>
<p>Specifically for ActiveRecord extensions you need a database and models definition to test your plugin, to do that you have to:</p>
<ul>
<li>Require ActiveRecord gem:
<pre name="code" class="ruby">
require 'activerecord'
</pre>
</li>
<li>Establish an ActiveRecord connection to a memory based sqlite3 database:
<pre name="code" class="ruby">
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :dbfile => ":memory:")
</pre>
</li>
<li>Define both <em>setup_db</em> and <em>teardown_db</em>:
<pre name="code" class="ruby">
def setup_db
  ActiveRecord::Schema.define(:version => 1) do
    create_table :posts do |t|
      t.column :title, :string
      t.column :body, :text
      t.column :category_id, :integer
    end
    create_table :categories do |t|
      t.column :id, :integer
      t.column :name, :string
    end
  end
end

def teardown_db
  ActiveRecord::Base.connection.tables.each do |table|
    ActiveRecord::Base.connection.drop_table(table)
  end
end
</pre>
</li>
<li>Define your models:
<pre name="code" class="ruby">
class Post < ActiveRecord::Base
  belongs_to :category
end
class Category < ActiveRecord::Base
  has_many :posts
end
</pre>
</li>
<li>Finally define both <em>setup</em> and <em>teardown</em> methods in your test class (Note that all the above should be placed before your test class definition):
<pre name="code" class="ruby">
  def setup
    setup_db
  end

  def teardown
    teardown_db
  end
</pre>
</li>
</ul>
<p>That&#8217;s it, now you can write your tests as if you&#8217;re writing them in your Rails application unit tests. Check the following for more example tests:</p>
<ul>
<li><a href="http://github.com/rbarazi/simply_searchable/tree/master/test%2Fsimply_searchable_test.rb">SimplySearchable test</a></li>
<li><a href="http://github.com/rails/acts_as_tree/tree/master/test/acts_as_tree_test.rb">acts_as_tree test</a></li>
<li><a href="http://github.com/technoweenie/acts_as_versioned/tree/master/test/versioned_test.rb">acts_as_versioned test</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://rida.me/blog/2008/11/18/testing-your-rails-plugin/feed/</wfw:commentRss>
		</item>
		<item>
		<title>SimplySearchable plugin</title>
		<link>http://rida.me/blog/2008/11/05/simplysearchable-plugin/</link>
		<comments>http://rida.me/blog/2008/11/05/simplysearchable-plugin/#comments</comments>
		<pubDate>Tue, 04 Nov 2008 22:27:11 +0000</pubDate>
		<dc:creator>Rida</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<category><![CDATA[Plugins]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://www.ridaalbarazi.com/blog/2008/11/04/simplysearchable-plugin/</guid>
		<description><![CDATA[Update 1:Associations support has been implemented.
Almost a year ago I released SimplySearchable plugin to help me implement the filtering options of restate.ae and during this year I&#8217;ve been updating it regularly until it become something completely different so I did a quick rewrite, moved all the logic to the model, moved the repository to github [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Update 1:</strong>Associations support has been implemented.</p>
<p>Almost a year ago I released <strong>SimplySearchable</strong> plugin to help me implement the filtering options of <a href="http://restate.ae" title="restate.ae">restate.ae</a> and during this year I&#8217;ve been updating it regularly until it become something completely different so I did a quick rewrite, moved all the logic to the model, moved the repository to <a href="http://github.com">github</a> and here it is.</p>
<h3>SimplySearchable</h3>
<p>The main goal of <strong>SimplySearchable</strong> is to make it easy to do queries on your model by auto-magically creating some <em>named_scope</em> methods for common conditions.</p>
<p>This plugin adds a method to the model named <em>list</em> that will find and filter records smartly.</p>
<p>Please submit your bugs, requests and feedback at the project&#8217;s page on <a href="http://rbarazi.lighthouseapp.com/projects/19246/home">Lighthouse</a>. RDocs are available at <a href="http://ridaalbarazi.com/code/simply_searchable/">http://ridaalbarazi.com/code/simply_searchable/</a>.</p>
<h3>Installation</h3>
<pre>
  ./script/plugin install git://github.com/rbarazi/simply_searchable.git
</pre>
<p>And in your model:</p>
<pre>
  class Post < ActiveRecord::Base
    simply_searchable
  end
</pre>
<p>Then in your controller you can say:</p>
<pre>
  class PostsController < ApplicationController
    def index
    @posts = Post.list(params)
  end
</pre>
<h3>Example:</h3>
<p>If you have the following attributes in you posts table:</p>
<pre>
  Post
    id:integer
    title:string
    body:text
    category_id:integer
    created_at:datetime
    updated_at:datetime
</pre>
<p>And in your Model:</p>
<pre>
  class Post < ActiveRecord::Base
    has_many   :comments
    belongs_to :category
    simply_searchable
  end
</pre>
<p>This will create the following named scopes:</p>
<pre>
  named_scope where_id,         lambda {|value| { :conditions => ["id = ?", value] }}
  named_scope where_title,      lambda {|value| { :conditions => ["title like ?", "%#{value}%"] }}
  named_scope where_body,       lambda {|value| { :conditions => ["body like ?", "%#{value}%"] }}
  named_scope where_created_at, lambda {|value| { :conditions => ["created_at = ?", [*value]] }}
  named_scope where_updated_at, lambda {|value| { :conditions => ["updated_at = ?", [*value]] }}
  named_scope where_categories, lambda {|value| { :conditions => ["category_id in (?)", [*value]] }}
  named_scope where_comments,   lambda {|value| { :conditions => ["comments.ids in (?)", [*value]] }}
</pre>
<p>It will also create the method &#8216;list&#8217; which you can use like:</p>
<pre>
  Post.list(:title => 'abc', :created_at => Date.today)
</pre>
<p>Which will return the posts that contain &#8216;abc&#8217; in their title and created today.</p>
<p>By default SimplySearchable list will_paginate, you can still disable it:</p>
<pre>
  class Post < ActiveRecord::Base
    simply_searchable :will_paginate => false
  end
</pre>
<p>Or customize its settings:</p>
<pre>
  class Post < ActiveRecord::Base
    simply_searchable :per_page => 20
  end
</pre>
<p><del datetime="2008-11-10T11:07:14+00:00">In the new implementation there is no support for associations&#8217; filtering yet, it will come very soon though so stay tuned.</del> Association support has been implemented.</p>
]]></content:encoded>
			<wfw:commentRss>http://rida.me/blog/2008/11/05/simplysearchable-plugin/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Crazy September</title>
		<link>http://rida.me/blog/2006/09/17/crazy-september/</link>
		<comments>http://rida.me/blog/2006/09/17/crazy-september/#comments</comments>
		<pubDate>Sun, 17 Sep 2006 01:35:06 +0000</pubDate>
		<dc:creator>Rida</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.ridaalbarazi.com/blog/2006/09/17/crazy-september/</guid>
		<description><![CDATA[I didn&#8217;t post anything for the last 15 days as I was very busy and somehow depressed with the good and bad I&#8217;m facing, in short I bought a car and a laptop but with some action in the middle that is worth mentioning here.
The Car and The New Record
Everything started when my father convinced [...]]]></description>
			<content:encoded><![CDATA[<p>I didn&#8217;t post anything for the last 15 days as I was very busy and somehow depressed with the good and bad I&#8217;m facing, in short I bought a car and a laptop but with some action in the middle that is worth mentioning here.</p>
<h3>The Car and The New Record</h3>
<p>Everything started when my father convinced me that we need another car for the family and here I mean my parents and brothers family as I don&#8217;t even have a girlfriend to have a family of my own yet. As I don&#8217;t have any car yet I loved the idea and left everything to my father to chose, test and negotiate <em><strong>(action 1)</strong></em>.</p>
<p>Finally after few days we decided on a used <a href="http://auto.consumerguide.com/Auto/Used/reviews/full/index.cfm/id/2134/act/usedcarreviewhighlights/">Dodge Grand Caravan 1996</a>, 7 seats, in a very good condition and loaded with full options. It was my first time <strong>EVER</strong> buying something (or pay a share in it) and getting it registered to my name <strong>WITHOUT EVEN SEEING IT</strong> <em><strong>(action 2)</strong></em>.</p>
<p><a href="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/09/after_48hr.jpg" rel="lightbox" title="After 48 hours"><img class="rfloated" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/09/after_48hr_thumb.jpg" width="320" height="240" alt="Rida's Car after less than 48 hours" /></a></p>
<p>The car was mine on September 5th, things were superb, at last I have a car of my own now and I&#8217;m very excited about it, but this happiness didn&#8217;t last longer than 48 hours&#8230; I hit the huge caravan trying to park it in a small space <em><strong>(action 3)</strong></em> and guess when?&#8230; I was going to Apple store to check Mac prices <em><strong>(action 4)</strong></em>.</p>
<p>Naturally my day was awful, I hated myself, I made a new record, hitting my first owned car within 48 hours of buying it (or even seeing it), even the Mac prices weren&#8217;t any good for me, the Apple store here in <acronym title="United Arab Emirates">UAE</acronym> is not an authorized branch or reseller, it only resells the machines it buys from the official UK agent after customising it to support Arabic, their prices are higher than the regular Apple prices so my Mac dream is now suspended until further notice.</p>
<p><a href="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/09/hp_dv5242ea.jpg" rel="lightbox" title="HP Pavilion DV5242ea"><img class="rfloated" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/09/hp_dv5242ea_thumb.jpg" width="239" height="239" alt="HP Pavilion DV5242ea" /></a></p>
<p>I quit Mac&#8217;ing for a while and to be more realistic I started looking for a decent laptop that fulfill my needs and I can afford, after doing my homework I ended up choosing <a href="http://h10025.www1.hp.com/ewfrf/wc/document?lc=en&#038;cc=us&#038;dlc=en&#038;product=3223544&#038;lang=en&#038;docname=c00716030" title="HP Pavilion DV5242ea">HP Pavilion dv5242ea</a>, a laptop with fairly good configurations compared to its price (around $1000) which is an exact fit to my budget.</p>
<h3>The Big Day, Sept 11th</h3>
<p>What do you expect from such a day, a catastrophic day in history and so it was for me, my computer crashed, my car failed me in the middle of my way to buy the new laptop. While doing the required homework to chose my laptop, my PC decided to take a nap and it started it by disconnecting every USB peripherals attached to it including my cable modem, after a little check I ended up with everything working but the keyboard <em>(<strong>action 5</strong>, please don&#8217;t ask how)</em>.</p>
<p><a href="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/09/car_failure_big.jpg" rel="lightbox" title="Rida\'s Car Failure on Sept 11"><img class="rfloated" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/09/rida_car_9_11.jpg" width="320" height="240" alt="Rida's Car Failure" /></a></p>
<p>Naturally I went to the store to buy the laptop and a keyboard, on my way to the store, just on the red signal, in the middle of a 6 lanes road, my car stopped and also (like my PC) decided to take a nap, a very long one to the level that it&#8217;s still not working to the moment of this post <em><strong>(action 6)</strong></em>.</p>
<p>After two hours waiting for the towing recovery and another one to take the car to the garage, I arrived home at 12:00Am without a laptop or a keyboard to spend the rest of the night without any computer or internet connection just trying to understand how bad things can go.</p>
<h3>And Finally&#8230;</h3>
<p>I bought the laptop the next day, using a taxi this time, my car is still in the repair without knowing what&#8217;s wrong with it yet, anyways I got over it and whatever happens happens, I guess I had enough of bad luck for this month and I hope the rest 15 days will be better.</p>
<p>Thank you for reading my depressing story of Crazy September and sorry for the delay in my posts, I missed the <a href="http://www.ridaalbarazi.com/blog/2006/08/02/blog_club_anime_community/">Blog Club</a> post of the Art Community, I missed two parts of the <a href="http://www.ridaalbarazi.com/blog/2006/08/16/rails-project-story/">Rails Project Story</a>, I didn&#8217;t even publish a single post for over 15 days, I will cover this up soon, starting with the third part of the <acronym title="Rails Project Story">RPS</acronym> coming tomorrow evening <em>(if nothing bad crossed my way)</em>.</p>
]]></content:encoded>
			<wfw:commentRss>http://rida.me/blog/2006/09/17/crazy-september/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Rails Project Story: 2. User Authentication</title>
		<link>http://rida.me/blog/2006/08/27/rails-project-story-2-user-authentication/</link>
		<comments>http://rida.me/blog/2006/08/27/rails-project-story-2-user-authentication/#comments</comments>
		<pubDate>Sun, 27 Aug 2006 16:21:55 +0000</pubDate>
		<dc:creator>Rida</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Rails Project Story]]></category>

		<category><![CDATA[Ruby on Rails]]></category>

		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.ridaalbarazi.com/blog/2006/08/27/rails-project-story-2-user-authentication/</guid>
		<description><![CDATA[Here comes the second part of our story, last time in part one we met rails directory structure, designed a three tables database, created it in MySQL and linked it to our application then we let rails db schema create those tables for us and finally we generated a modest scaffold for our Books table.
If [...]]]></description>
			<content:encoded><![CDATA[<p>Here comes the second part of <a href="http://www.ridaalbarazi.com/blog/2006/08/16/rails-project-story/">our story</a>, last time in <a href="http://www.ridaalbarazi.com/blog/2006/08/20/rails-project-story-1-getting-started/">part one</a> we met rails directory structure, designed a three tables database, created it in MySQL and linked it to our application then we let rails db schema create those tables for us and finally we generated a modest scaffold for our <em>Books</em> table.</p>
<p>If you remember last week we added another table in our db schema file which was the <em>Users</em> table, today we will talk about users in our application and how to make our application a more social one.</p>
<p>The options we have in order to have a user management setup for our applications are mainly three:</p>
<ul>
<li>Do it ourselves from zero.</li>
<li>Use some decent plugin like <a href="http://technoweenie.stikipad.com/plugins/show/Acts+as+Authenticated"><strong>Acts As Authenticated</strong></a>.</li>
<li>Use a ready generator like <a href="http://wiki.rubyonrails.org/rails/pages/SaltedHashLoginGenerator"><strong>Salted Hash Login Generator</strong></a>.</li>
</ul>
<p>Before we choose between these three let&#8217;s see what are the main differences between them:</p>
<p>If we write our code from zero we will definitely learn more, we will have a better understanding of the whole process but at the same time we will be spending too much time on something became very regular and common in every web application and in some way we will be doing some not required extra work.</p>
<p><strong>Acts As Authenticated</strong> and <strong>Salted Hash Login Generator</strong> are almost the same from some functionality point of view but the main difference is that the act is more dynamic and customizable because it is simpler, it let us take care about few things that we should really be responsible of while the generator take care about everything in some more advance way, so personally I prefer to go for <strong>Acts As Authenticated</strong> for its simplicity and core functionality that will help us understand how things work and allowing us to add some extra functionalities by ourselves.</p>
<p>Acts in rails are some sort of plugins and extensions to our framework extending it with few extra features, there are many great acts we will use in this application, some of them are completely independent from rails and some like <strong>Acts As Taggable</strong> became so common to the level they got packaged with rails itself.</p>
<h3>Acts As Authenticated</h3>
<p>It&#8217;s a simple system that helps us deal with users in our applications, it generate the required code to support user authentication and management starting from the regular MVC code ending with migration and tests.</p>
<h4>Installation</h4>
<p>To start with we have first to install the plugin on our system, to do this we have first to update our repositories index and then install the plugin.</p>
<pre>
D:\\Projects\\Book Swap\\bookswap>ruby script/plugin source http://svn.techno-weenie.net/projects/plugins
Added 1 repositories.

D:\\Projects\\Book Swap\\bookswap>ruby script/plugin install acts_as_authenticated
+ ./acts_as_authenticated/CHANGELOG
+ ./acts_as_authenticated/README
.
.
.
Consult the Acts As Authenticated wiki for more: http://technoweenie.stikipad.com/plugins/show/Acts+as+Authenticated
</pre>
<h4>The Generator</h4>
<p>After installing the plugin now we are able to generate all the required files, acts_as_authenticated have mainly two generators, one for the authentication system itself, the core functionalities and their corresponding model, views and controller. And the other generator is the mailer, the one responsible for sending notification and verification emails to our registered users.</p>
<pre>
To use:

  ./script/generate authenticated user account

This generates a basic user model, a controller, some basic views, and tests.
</pre>
<p>So to generate the authentication system we have first to decide the controller name to be generated and remember here that the controller is the one that normally appear in our URL (to deal with the books controller we had to call <a href="http://localhost:3000/books">http://localhost:3000/books</a>) so what will be the best controller name for our users? Account? Readers? Owners? Well personally I prefer to stick with the defaults and the classics, at the end these are our applications <em>Users</em>, and this is what we called the database table earlier so let&#8217;s stick to it and name it <strong>&#8220;users&#8221;</strong>:</p>
<pre>
D:\\Projects\\Book Swap\\bookswap >ruby script/generate authenticated user users
      exists  app/models/
      exists  app/controllers/
      exists  app/helpers/
      create  app/views/users
      exists  test/functional/
      exists  test/unit/
      create  app/models/user.rb
      create  app/controllers/users_controller.rb
      create  lib/authenticated_system.rb
      create  lib/authenticated_test_helper.rb
      create  test/functional/users_controller_test.rb
      create  app/helpers/users_helper.rb
      create  test/unit/user_test.rb
      create  test/fixtures/users.yml
      create  app/views/users/index.rhtml
      create  app/views/users/login.rhtml
      create  app/views/users/signup.rhtml
      create  db/migrate
      create  db/migrate/001_create_users.rb
</pre>
<p>If we examine the generated files we can see that <em>acts_as_authenticated</em> has generated for us the user model, users controller and its corresponding views, a helper, some unit and fixture tests and finally a migration file, as we have all these files generated it seems that <strong>BookSwap</strong> is ready now to have users, let&#8217;s see if this is true <a href="http://localhost:3000/users">http://localhost:3000/users</a></p>
<p><img id="image100" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/08/users_signup.PNG" alt="users_signup.PNG" /></p>
<p>It seems that it works, it already directed us to the signup method <a href="http://localhost:3000/users/signup">http://localhost:3000/users/signup</a>, ok let&#8217;s give it a try and see what will happen (click to enlarge):</p>
<p><a href="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/08/users_signup_error.PNG" rel="lightbox" title="User Signup Error"><img src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/08/users_signup_error.PNG" width="450" height="330" alt="User Signup Error" /></a></p>
<p>Oops, we have a problem, but at least we have some information that we can work with to understand what we have done wrong.</p>
<h4>Fixing The Conflict</h4>
<p>With the user friendly error page we should be able to catch what we&#8217;ve done wrong, it&#8217;s saying: <em><strong>&#8220;undefined local variable or method `crypted_password&#8217; for #&lt;User:0&#215;39499b8&gt;&#8221;</strong></em>, so basically the problem is in <em>&#8220;crypted_password&#8221;</em> and it is in the model <em>User</em>, we remember that the Model is the one that deals with the database, if you remember from our first part in the db schema definition we named the password column <em>&#8220;salted_password&#8221;</em>:</p>
<p>Error: Could not open schema.rb</p>
<p>So from where did this <em>&#8220;crypted_password&#8221;</em> come from?</p>
<h4>Back to Migrations</h4>
<p>Maybe it&#8217;s time to go back and check what&#8217;s inside the migration file that <em>acts_as_authenticated</em> generated for us and and check if it has anything realted:</p>
<p>Error: Could not open 001_create_users.rb</p>
<p>First let&#8217;s understand the migration process more, the migration is made to allow us move up and down in our application with a decent control over our database modification, in this case we can understand that <em>acts_as_authenticated</em> did create the migration file for us so we migrate to it.</p>
<p>Any migration file is separated into two parts, <strong>up</strong> and <strong>down</strong>. From the names <strong>&#8220;up&#8221;</strong> is the actions which will take place when we move forward in our migration like migrating from 4 to 5 for example, and <strong>&#8220;down&#8221;</strong> will hold the actions that will be executed when we move backward in our migrations like migrating from 6 to 5 for example.</p>
<p>The <em>001_create_users.rb</em> migration file creates a table in its <strong>up</strong> method and drop it in its <strong>down</strong> method, the table it creates is the <em>Users</em> table which we already created earlier in our schema, it almost have all the columns, few more and some with different names, here we can find the mysterious <strong>&#8220;crypted_password&#8221;</strong> we saw in the error page, it&#8217;s the column we named as <strong>&#8220;salted_password&#8221;</strong>, so we found what&#8217;s wrong, now how to fix this conflict?</p>
<p>We have to write our own migration instead of using the default migration generated by <em>acts_as_authenticated</em>, we will tweak it to suit our needs. First we don&#8217;t need to create the <em>Users</em> table as it is already created, we don&#8217;t need to recreate the fields we have already created as well but we need the new fields required by <em>acts_as_authenticated</em> and sure we have to fix and <em>rename</em> the field <strong>salted_password</strong> into <strong>crypted_password</strong>. This will make <strong>&#8220;up&#8221;</strong> method like this:</p>
<p>Error: Could not open 001_create_users_up.rb</p>
<p>Instead of the <em><a href="http://api.rubyonrails.com/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#M000604">create_table</a></em> method we used some individual methods that deals with an existing table, <em><a href="http://api.rubyonrails.com/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#M000607">add_column</a></em>, <em><a href="http://api.rubyonrails.com/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#M000608">remove_column</a></em> and <em><a href="http://api.rubyonrails.com/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#M000611">rename_column</a></em> are simple methods that takes the table name as their first parameter and the column name as their second, only the <em>rename_column</em> method takes an extra parameter which is the new column name.</p>
<p>As this is the first migration file we have it got the 001 numbers at the beginning of its name automatically, from now on any new migration will get a serial prefix to its name that indicate its place among other migrations.</p>
<p>Whenever we do any changes or modifications to our database we have to support going back by defining the opposite actions in the <strong>&#8220;down&#8221;</strong> method of our migration as follows:</p>
<p>Error: Could not open 001_create_users_down.rb</p>
<p>So at the end our modified <em>001_create_users.rb</em> file will end up like this:</p>
<p>Error: Could not open 001_create_users_new.rb</p>
<p>Logically we have solved the conflict error but there is still one step left which is migrating our application to the latest migration available and for now it is 001, to migrate our application we have to call the command &#8220;rake migrate&#8221;, if we called it without any parameter it will automatically migrate our database to the latest migration available, if we specified the <strong>&#8220;VERSION=<em>X</em>&#8220;</strong> parameter it will migrate the application to migration <strong><em>X</em></strong> whether it is newer or older from our current migration level.</p>
<pre>
D:\\Projects\\Book Swap\\bookswap>rake migrate
(in G:/Projects/Book Swap/bookswap)
== CreateUsers: migrating =====================================================
-- rename_column(:users, :salted_password, :crypted_password)
   -> 0.3590s
-- add_column(:users, :salt, :string, {:limit=>40})
   -> 0.3280s
-- add_column(:users, :created_at, :datetime)
   -> 0.3600s
-- add_column(:users, :updated_at, :datetime)
   -> 0.3430s
-- add_column(:users, :remember_token, :string)
   -> 0.3440s
-- add_column(:users, :remember_token_expires_at, :datetime)
   -> 0.3600s
== CreateUsers: migrated (2.0940s) ============================================</pre>
<p>Back to our application checking if the user system is working now, let&#8217;s try to sign up again and see what we will get (<a href="http://localhost:3000/users/signup">http://localhost:3000/users/signup</a>):</p>
<p><img id="image98" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/08/users_after_successful_login.PNG" alt="users_after_successful_login.PNG" /></p>
<p><em>&#8220;Train delayed? and what&#8217;s to say?&#8221;</em> nice poetry after such a cool process, so we are signed up and logged in now, this is what <em>acts_as_authenticated</em> can give us so far and the rest is on us. </p>
<p>Have you noticed that the column <em>fullname</em> didn&#8217;t show up in the signup page? That&#8217;s because the templates generated by <em>acts_as_authenticated</em> plugin don&#8217;t know about it <em>YET</em>.</p>
<h3>Tailoring</h3>
<p>To be able to tailor and customize the authenticated system we have to understand the generated files and know how to deal with them and we will start with the views:</p>
<p>The generated templates are three, <em>login</em>, <em>signup</em> and <em>index</em>, they are all placed under the &#8220;<em>users</em>&#8221; subdirectory in our <em>app/views</em> directory, what we want is to allow users to add their fullnames when they signup so let&#8217;s have a quick look at the <em>signup.rhtml</em> template:</p>
<p>Error: Could not open signup_old.rhtml</p>
<p>It looks that we have a pattern for every property of the user object to generate its corresponding form input, if we followed the same pattern to generate the required input for the user fullname our template will look like this:</p>
<p>Error: Could not open signup.rhtml</p>
<p>This template like any other <strong>rhtml</strong> view template contains two types of code, the basic <em>xhtml/html</em> code and an embedded ruby code which we call <strong>ERb</strong>. To embed a ruby code in our views we have to surround it with <strong><em>&lt;%</em></strong> and <strong><em>%&gt;</em></strong> this will execute the ruby code but it will not show any output so it&#8217;s called <strong>&#8220;evaluation ERb block&#8221;</strong>, if we want to show the output of this code we have to add an equal sign after the introductory signs so it will be surrounded by <strong><em>&lt;%=</em></strong> and <strong><em>%&gt;</em></strong> and this is called <strong>&#8220;output ERb block&#8221;</strong>.</p>
<p>In any of the <strong>ERb</strong> block types we will deal mainly with two things, first is the <em>ActionController</em> methods and actions, these will help us generate the required <em>xhtml/html</em>, <em>js</em> and <em>xml</em> code in a dynamic smooth way.</p>
<p>The second thing we will deal with in our views is <em>the instance variable</em> received from the related action in the related controller, each view will be parsed after its corresponding action in its related controller is requested, in that particular action we set some instance variables that we can manipulate in our views, we will see that in more details soon.</p>
<h3>How is it working?</h3>
<p>In order to understand the code and the way it is generated in <em>signup.rhtml</em> let&#8217;s have a look at the parsed version of it, the html source code of the page we get in our browser when we call <a href="http://localhost:3000/users/signup">http://localhost:3000/users/signup</a>:</p>
<p>Error: Could not open signup.html</p>
<p>Back to our <em>rhtml</em> template we notice that it starts with an output ERb block with the method <em><a href="http://api.rubyonrails.com/classes/ActionView/Helpers/ActiveRecordHelper.html#M000460">error_messages_for</a></em> which will output all the error messages of the user object in this form if there is any, as we don&#8217;t have any errors here we didn&#8217;t find any related html code in the parsed version.</p>
<p>Then comes an evaluation ERb block that opens a block by its turn, the <a href="http://api.rubyonrails.com/classes/ActionView/Helpers/FormHelper.html#M000387">form_for</a> method do the required preparation to output a form fully customized to hold the information of a specific object and by ready I mean setting this form inputs names and ids to form a set of the object&#8217;s data in the post parameters. So what we do is to specify the object name we are preparing this form for, which in our case <em>&#8220;user&#8221;</em>, we can also specify the action this form will be directed to when it&#8217;s submitted, if we don&#8217;t specify any (like in our case) it will be submitted to itself so our form will be submitted back to the <em>signup</em> action of the <em>users</em> controller.</p>
<p>The <em>form_for</em> method prepared a form helper object for the &#8220;user&#8221; object and name it &#8220;f&#8221;, then the generating of the required inputs for each column started by simply calling their corresponding helper methods, notice that only two methods are used so far: <em>text_field</em> and <em>password_field</em> and they are called as methods of the form helper object called &#8220;f&#8221;, notice as well that these methods are called in an output ERb block so they can return their output in the parsed template.</p>
<p>Let me try to simplify this code by trying to write it in plain English: <em>&#8220;Start a form for a new user then generate the required text fields and password fields for this user and then post them back to the same current page.&#8221;</em></p>
<p>The main idea of setting the names and ids of the generated inputs is to simplify the way we deal with them in our actions as post parameters, rails has a standard for this and therefore it has the ready tools to generate what&#8217;s required to follow these standards and get things faster.</p>
<p>After we are done with our form fields we find a <em>submit_tag</em> named <em>&#8220;Sign up&#8221;</em> then the <em>form_for</em> block is  simply closed by an <em>&#8220;end&#8221;</em> and we are done. When someone signup and fill all these fields and hit the sign up button the form data will be posted to the same action <strong>&#8220;signup&#8221;</strong> where it will be handled to add a new user to the <em>Users</em> table accordingly, if it faced any errors it will return to the same form and show the errors at the top (as the results of the <em>error_messages_for</em> method), if not it will simply login to our poetry page.</p>
<h3>Are We Logged In?</h3>
<p>Now let&#8217;s change this literal poetry in the <em>index.rhtml</em> template to some code poetry, how about we change the output of this view depending on the status of the user, if he/she is logged in we show a link to <em>logout</em>, if not we show links to either <em>signup</em> or to <em>login</em>. I don&#8217;t think this is difficult it&#8217;s just a quick <em>if</em> statement:</p>
<p>Error: Could not open index_new.rhtml</p>
<p>I guess the code is self-explanatory now, I just want to note that we used the method <em><strong>logged_in?</strong></em>, in ruby whenever there is a method with a question mark <em><strong>&#8220;?&#8221;</strong></em> at the end of it will return a Boolean, True or False, so in English it&#8217;s like a simple question, <em>is the current user logged in?</em> this method is a part of the <em>acts_as_authenticated</em> plugin.</p>
<p>The other thing I wanted to talk about here is the <a href="http://api.rubyonrails.com/classes/ActionView/Helpers/UrlHelper.html#M000378"><em>link_to</em></a> method, it is an ActionView helper method, it generates an anchor, takes the first parameter as the anchor name and the second as the action name we want to link to, it will automatically understand and generate the corresponding URL of the action we specify, for example when we specify the &#8220;logout&#8221; action it will know automatically that its URL is <a href="http://localhost:3000/users/logout">http://localhost:3000/users/logout</a>.</p>
<p>So we have changed our <em>index.rhtml</em> file, now let&#8217;s see if it&#8217;s working and how it will look like, remember that our last state where logged in after we signed up and saw the lovely poetry:</p>
<p><img id="logged_in" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/08/users_index_logged_in.PNG" alt="Logged in users index page" /></p>
<p>We are logged in, that&#8217;s true, it seems that everything is really working fine and we don&#8217;t have any problems so far, how about the link to <em>&#8220;logout&#8221;</em>? is it working? let&#8217;s check out:</p>
<p><img id="logged_out" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/08/users_index_logged_out.PNG" alt="Logged out users index page" /></p>
<p>Yes it is working, we are logged out now and we have one of two options, either to login again or to signup for a new account, try logging in and out again to see how it&#8217;s working and then let&#8217;s try a new signup to see if the fullname field we have added is present or not:</p>
<p><img id="signed_up" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/08/users_signup_new.PNG" alt="New users signup page" /></p>
<p>Wonderful, we have a simple user authentication system now that we modified a little, so far it works for signup, login and logout, it doesn&#8217;t do anything more yet but at least it helped us understand few concepts and how things work at the backend.</p>
<h3>More Security by Filtering</h3>
<p>To care more about security and to get the most benefit out of the latest rails 1.1.6 security release let&#8217;s use the new method of ActionController (released in rails 1.1.6) <em><a href="http://api.rubyonrails.org/classes/ActionController/Base.html#M000201">&#8220;filter_parameter_logging&#8221;</a></em>:</p>
<p><em><strong>&#8220;<a href="http://api.rubyonrails.org/classes/ActionController/Base.html#M000201">ActionController#filter_parameter_logging</a> lets you filter form data that you don&#8217;t want saved in the log. This is useful for preventing sensitive data like passwords and credit card numbers from being logged in the clear, for keeping huge pieces of data from clogging the log file, and so on.&#8221;</strong> from <a href="http://weblog.rubyonrails.org/2006/8/21/filtered-parameter-logging">Filtered Parameter Logging</a> of <a href="http://weblog.rubyonrails.org/2006/8/21/filtered-parameter-logging">the Ruby on Rails official Blog</a>.</em></p>
<p>This method job –as clarified in rails weblog- is to filter fields from being logged, in our case what we want to filter is the <em>password fields</em> and we will do that by adding the <em><strong>filter_parameter_logging</strong></em> line to our application controller in <em>controllers/application.rb</em>:</p>
<p>Error: Could not open application_filtered.rb</p>
<p>By doing this the <strong>password</strong> and <strong>password_confirmation</strong> fields will never be logged anymore and will be replaced by &#8220;<strong>[FILTERED]</strong>&#8221; in the log files, to check that yourself you can check your <em>log/development.log</em> file and see how the passwords of the users added to the system earlier were plainly logged while the passwords of any new users will be replaced with &#8220;[FILTERED]&#8220;.</p>
<h3>Summary</h3>
<p>In this part we have implemented the Acts As Authenticated plugin into our application, modified it a little and understood few backend behaviors specifically the way the view templates handle ERb code, we also had a better look at Migrations and understood how they help us have a better control over our database modifications in a very dynamic way.</p>
<p>During the next week I will release a sidenote post on how to checkout the project files from the subversion repository I&#8217;m using for it, I&#8217;m also working on creating packaged files for each part of the tutorial and will release it on RubyForge soon too.</p>
<p>In the next part we will talk about relationships, as for now we have a user system and a simple books system, we will link them together using some magic relationship mapping from ActiveRecord maybe we will do some testing as well to ensure things are working properly, so&#8230; see you next week.</p>
]]></content:encoded>
			<wfw:commentRss>http://rida.me/blog/2006/08/27/rails-project-story-2-user-authentication/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Rails Project Story: 1. Getting Started</title>
		<link>http://rida.me/blog/2006/08/20/rails-project-story-1-getting-started/</link>
		<comments>http://rida.me/blog/2006/08/20/rails-project-story-1-getting-started/#comments</comments>
		<pubDate>Sun, 20 Aug 2006 15:24:21 +0000</pubDate>
		<dc:creator>Rida</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Rails Project Story]]></category>

		<category><![CDATA[Ruby on Rails]]></category>

		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.ridaalbarazi.com/blog/2006/08/20/rails-project-story-1-getting-started/</guid>
		<description><![CDATA[So here is the first part of the previously announced Rails Project Story, in this part we are going to understand the Rails directory structure, design a very basic database to start with, link it to our rails application, setup the rails database schema for it and finally try the famous scaffolding feature that everybody [...]]]></description>
			<content:encoded><![CDATA[<p>So here is the first part of the previously announced <a href="http://www.ridaalbarazi.com/blog/2006/08/16/rails-project-story/">Rails Project Story</a>, in this part we are going to understand the Rails directory structure, design a very basic database to start with, link it to our rails application, setup the rails database schema for it and finally try the famous scaffolding feature that everybody talks about.</p>
<p>It seems that I underestimated the amount of work this tutorial is going to take that&#8217;s why I&#8217;m a day late, because of that I will change the weekday each part of this series will come up from Saturday to Sunday and sorry about this delay.</p>
<p>If you remember our project is <strong>BookSwap</strong>, <em>a small system based on users, it will give them the chance to exchange and swap books between each others from their online bookshelves that they create</em>. so let&#8217;s get started:</p>
<p>Normally I prefer to get something up and running as soon as I can, at least to enjoy seeing results from the very beginning of my project work and this is what we are going to do with this project as well, so to start let&#8217;s decide what is the simplest database design we can start with?</p>
<h3>Database Schema</h3>
<p>Basically from the light definition of our project we can tell that this project includes two main things: <em>users</em> and <em>books</em>, and from here we will go, we need two tables, one to hold the users data and we will call it Users and another one for books data and we will call it Books and now let&#8217;s discuss the relationship between these two tables</p>
<p>Obviously every user will have many books, and many users can own the same book (I mean the same title not the same physical book), so the relationship we have here is the <em>many-to-many</em> relationship which requires a third table in our database called <em>users_books</em>, therefore our database should look like this (db model is generated using <a href="http://www.fabforce.net/dbdesigner4/">DBDesigner4</a>):</p>
<p><img id="image91" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/08/users_books1.png" alt="Users and Books tables" /></p>
<p>As you can tell from the database model above, I have mentioned the common and very basic columns of each table; fullname, login, email and salted_password for the Users table and title, author, publisher and ISBN for the Books table and naturally both of them have the default ID column as well.</p>
<p>We will use MySQL as the database server for this application, it&#8217;s time to create the three databases we will work with on our way:</p>
<p><em><strong>bookswap_production</strong></em>: This will be the database we will use when we finish our development work and ready to have a live and completely working web application, that&#8217;s why it&#8217;s called the production database, it should contain the most stable version of our database structure with the most stable version of our code that&#8217;s why we separated it from the development database.</p>
<p><em><strong>bookswap_development</strong>t</em>: As you can tell, this is the database that we will play with during our development process, whenever we need to change anything or touch anything related to the database this is the one we should be dealing with in order to keep our production database in peace.</p>
<p><em><strong>bookswap_test</strong></em>: In a sooner part of this tutorial we will cover the testing of our application, we will write code that will test our code and this testing code will deal with a completely separate database from both development and production databases, it will deal with the test database as it will require a lot of data insertions and deletion while testing which we want to keep away from other live and development databases.</p>
<p>If you have a <acronym title="Graphical User Interface">GUI</acronym> for your MySQL server you can create the above databases from there or we can simply use the command line admin tool:</p>
<pre>
D:\\Projects>mysqladmin -–user root -–password create bookswap_production
Enter password: ********

D:\\Projects>mysqladmin -–user root –-password create bookswap_development
Enter password: ********

D:\\Projects>mysqladmin -–user root -–password create bookswap_test
Enter password: ********
</pre>
<p>We will only create the databases now, we will not create any tables or relationships yet and actually we will do all that in Ruby and Rails after we get to know the directory structure of our rails application.</p>
<h3>Generating The Rails Application</h3>
<p><em>Before we get started with generating the rails application let&#8217;s just clarify few things, we are using Rails 1.1.6 for this application which got <a href="http://weblog.rubyonrails.org/2006/8/10/rails-1-1-6-backports-and-full-disclosure">announced</a> only few days ago (from the date of this post), so if you have Rails installed earlier before the update please upgrade before we proceed.</em></p>
<p>To generate our rails application we have to run the <strong>rails</strong> command, personally I have created a directory called &#8220;Book Swap&#8221; where I will store everything related to this project, including the rails app itself. So all I have to do now is to run the <strong>&#8220;rails&#8221;</strong> command in my directory with the project name to get my files generated.</p>
<pre>
D:\\Project\\Book Swap>rails bookswap
      exists
      create  app/controllers
      create  app/helpers
      create  app/models
      .
      .
      .
      create  doc/README_FOR_APP
      create  log/server.log
      create  log/production.log
      create  log/development.log
      create  log/test.log
</pre>
<p>I guess you agree with me that these are a lot of files and directories that Rails has generated for us, maybe we should give them a quick scan and try to understand what they are for and what we will be dealing with more frequently:</p>
<h3>File Structure</h3>
<p><img id="image93" class="rfloated" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/08/file_structure.png" alt="File Structure" /></p>
<h4>app</h4>
<p>This directory is the one that will contain most of our working files, it already contains four subdirectories (controllers, helpers, models and views), that is made to support the <acronym title="Module View Controller">MVC</acronym> nature of Rails, in brief the MVC methodology is based on separating our code into three levels: </p>
<p>First we have <strong>the Model</strong> which carries the core functions and responsible for all the data handling and manipulation, then comes <strong>the Controller</strong> which normally interacts with the model to retrieve data and prepare it to be viewed by <strong>the View</strong> which by its turn is the responsible of doing all the &#8220;show&#8221; business.</p>
<p>As for <strong>Helpers</strong>, they are the view supporters, when we reach the level that we have too much code in the view we better go and make a helper function and use it instead, once we start writing code we will get a better understanding of all these concepts which will happen very soon.</p>
<p><strong>Behind The Scenes</strong></p>
<p>All of these models, controllers and views are just the children of a bigger and more general parts of Rails, actually Rails is a union of different parts for each task which makes it more understandable and customizable to fit our best needs.</p>
<p><a href="http://api.rubyonrails.com/classes/ActiveRecord/Base.html">ActiveRecord</a> is the part of Rails that&#8217;s responsible of interacting with the database and lets us deal with it as a complete object oriented solution, which really sounds like the model behavior (core functions and data manipulation) which is true, normally the model classes in our <em>models</em> directory are subclasses of ActiveRecord where they inherit the magic powers of it and get such strong tools to deal with the database.</p>
<p><em><strong>&#8220;Active Record objects don’t specify their attributes directly, but rather infer them from the table definition with which they’re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.&#8221;</strong> From <a href=" http://api.rubyonrails.com/classes/ActiveRecord/Base.html">Rails API</a></em></p>
<p>Following the same path Rails also depends on <a href="http://api.rubyonrails.com/classes/ActionController/Base.html">ActionController</a> for its controllers, which is the midpoint between the views and the models, it receives the web requests from one side, activate the corresponding action which will contact the model for few  data objects and then render the views to show the results.</p>
<p><em><strong>&#8220;Action Controllers are the core of a web request in Rails. They are made up of one or more actions that are executed on request and then either render a template or redirect to another action. An action is defined as a public method on the controller, which will automatically be made accessible to the web-server through Rails Routes.&#8221;</strong> From <a href=" http://api.rubyonrails.com/classes/ActionController/Base.html">Rails API</a></em></p>
<p>And finally we&#8217;ve got the views which are <a href="http://api.rubyonrails.com/classes/ActionView/Base.html">ActionView</a> templates, we will see how they are just normal html, js or xml pages but with embedded Ruby code inside which also known as <acronym title="Embedded Ruby">ERb</acronym>, this embedded code helps us represent the data with some behavior and have a better separation between our design and our backend code.</p>
<p><em><strong>&#8220;Action View templates can be written in three ways. If the template file has a +.rhtml+ extension then it uses a mixture of ERb (included in Ruby) and HTML. If the template file has a +.rxml+ extension then Jim Weirich’s Builder::XmlMarkup library is used. If the template file has a +.rjs+ extension then it will use ActionView::Helpers::PrototypeHelper::JavaScriptGenerator.&#8221;</strong> From <a href=" http://api.rubyonrails.com/classes/ActionView/Base.html">Rails API</a></em></p>
<h4>config</h4>
<p>From its name, config directory is where the configurations files are stored, the database link file, routs and environments files. <em>database.yml</em> is the database link file, where we will setup our database connection settings, <em>environment.rb</em> is the file where we specify our application environment, remember when we talked about development, production and test databases; each one of those is related to one separate environment as well that we can run our application on.</p>
<p>Config directory include environments subdirectory too which include environments configurations files, for each environment a  different file, to control all the environments we have the father file we&#8217;ve just talked about environment.rb.</p>
<p>Finally comes the <em>routes.rb</em> file which (as it&#8217;s named) take care of all the web requests routing in our application, starting from some very basics routes up to a very complicated ones, it is very helpful for making clean and meaningful URLs as well.</p>
<h4>components</h4>
<p>In this directory we can create and store components which are something like a small application with model, controller and view that we can use all over our website instead of repeating ourselves for some modules.</p>
<h4>db</h4>
<p>From its name, the <em>db</em> directory will store our database related files, earlier we used to store the SQL files that generate our database structure but now it will hold only ruby files. It will store the schema and migrations files that we will discuss after a while in this part.</p>
<p>When we first generate our rails application the db folder will be empty but as we move along it will contain the schema.rb file that stores our database schema definitions and a subdirectory named &#8220;<em>migrations</em>&#8221; to store the versioned migrations we will create.</p>
<h4>lib</h4>
<p>Sometimes but not always there are some code that we want to write and it doesn&#8217;t fit under any of the MVC hierarchy, such custom code will be stored in the <em>lib</em> directory.</p>
<h4>public</h4>
<p>An interesting fact about Rails that none of these directories we are talking about is viewable or accessable online except for &#8220;<em>public</em>&#8220;, it contains the cgi/fcgi dispatchers that will do all the underground work to deal with the routes and our application, it also contains the <em>images</em>, <em>stylesheets</em> and <em>javascripts</em> subdirectories that we will be calling in our <em>views</em> and <em>layouts</em>.</p>
<h4>script</h4>
<p>You will notice when go a little further that rails is full of generators and embedded scripts that help us along the road to generate and create many things and even run a tiny web server as well the <em>script</em> directory is where all these stuff are hidden.</p>
<h4>test</h4>
<p>The <em>test</em> directory is where all the automotive tests are stored, there are functional tests for our controllers with some fixtures to load and a couple of unit tests for our models as well.</p>
<h4>vendor</h4>
<p>As in any application, sometimes we don&#8217;t want to reinvent the wheel, we don&#8217;t want to do something that&#8217;s already done, rails as an open source framework have many wonderful plugins and resources available that we can use in our applications and we will do that as well in BookSwap, all these external libraries and plugins will be stored in the <em>vendor</em> directory.</p>
<h4>doc, log, and tmp</h4>
<p>These three directories we don&#8217;t interact with their files much as they are automatically generated and updated, the <em>log</em> directory will store the log files of our web server for each environment, <em>tmp</em> will store the session, cache and socket temporary generated files and finally <em>doc</em> will store the html documentation that we will generate for our application (we will cover this up in some later part).</p>
<h3>Link The Database</h3>
<p>After we had this quick overview over the file structure in Rails we have to configure our rails application to connect to the databases we have created earlier, the responsible configuration for this is <em>config/database.yml</em> which normally looks like (notice that the databases names are exactly like the one we&#8217;ve created as they follow the project name):</p>
<p>Error: Could not open original_database.yml</p>
<p>Now for the sake of <acronym title="Don’t Repeat Yourself">DRY</acronym> &#8216;ing our configuration file we will change it a little bit and add our database connection details as well to:</p>
<p>Error: Could not open dried_database.yml</p>
<p>Basically what we have done is taking all the repeated information from the three database configurations parts, collect them under one reference and call this reference back in the configurations parts, by doing this we are not only DRY &#8216;ing our database configuration file but we also allowed different database engines to be defined more easily.</p>
<p>So our Rails application is linked to its blank databases using the MySQL adapter and it&#8217;s time to implement the structure we&#8217;ve decided on earlier using the rails schema and migrations facilities.</p>
<h3>Rails + Database = Schema + Migrations</h3>
<p>Migration in rails is the way Rails allow us to move back and forth in our application easily without losing any data from our databases but also keeping track of all the database structure changes from version to version (something like version control for our code files).</p>
<p>Database schema in Rails is very first database schema our rails application will have so if we want to install it on a new machine or load our database structure in any different database server it will be ready as a schema file that gets accumulated by the migrations files to move between versions.</p>
<p>In this part we will deal only with the schema part and later on with our versions and modifications we will get to know migrations better and have a closer look at them, now let&#8217;s generate the schema file and see how it looks like:</p>
<pre>
D:\\Projects\\Book Swap\\bookswap>rake db_schema_dump
</pre>
<p>This command will create a new file in our <em>db</em> folder named <em>schema.rb</em>, this file will hold all the starting schema setup and definitions and as this is a fresh application it will be empty from any definitions yet:</p>
<p>Error: Could not open original_schema.rb</p>
<p>Now let&#8217;s implement the basic database schema we agreed on at the beginning of this part, three tables with few fields, after the modification our <em>schema.rb</em> will be like this:</p>
<p>Error: Could not open schema.rb</p>
<p>If you read the above code you can easily understand that we simply created three database tables and identified their columns accordingly but notice also that we didn&#8217;t define the id column of the <em>users</em> and <em>books</em> tables, this is because ActiveRecord will create it by default.<br />
<em><br />
<a href="http://api.rubyonrails.com/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#M000604">create_table</a></em> is a simple method that generates SQL code of creating a table, we used its block form to add columns of our desired type, in the block form an instance of the table definition is created as <strong><em>&#8220;t&#8221;</em></strong> and when we call <em>t.column</em> it&#8217;s like if we say <em>add_column</em> in the regular form of the <em>create_table</em> method.</p>
<p>We have a schema file that contains our database structure, we have a rails application linked correctly to our database all we have to do now is to tell rails to import this schema to the linked database:</p>
<pre>
D:\\Projects\\Book Swap\\bookswap>rake db_schema_import
(in D:/Projects/Book Swap/bookswap)
-- create_table("users")
   -> 0.3440s
-- create_table("books")
   -> 0.1410s
-- create_table("users_books")
   -> 0.1720s
</pre>
<p>Running this command will import the database schema defined in <em>schema.rb</em> to our development database and that&#8217;s because the default environment of any new rails project is the development environment which can be changed and configured at anytime in <em>config/environment.rb</em>.</p>
<p>With this ruby-based database schema file we have saved ourselves from being attached to any database engine, Rails supports too many database engines like SQLite, Oracle, DB2, SQL Server and PostgreSQL, now our application can work with any of those by simply changing the connection adapter in <em>config/database.yml</em> file and import our schema to it using the above rake command.</p>
<p>This is one of the reasons why many designers or non-developers liked Ruby on Rails when they started to learn it as their first web development language and framework, Ruby has this beautiful self-explanatory code and Rails is full with Agile practices, it saved us from dealing with any SQL code and made our application cross-database-engines with Schema and Migrations.</p>
<p>All this read and all this steps and we didn&#8217;t see anything in action yet, maybe it&#8217;s time for us to try <a href="http://wiki.rubyonrails.org/rails/pages/ScaffoldGenerator">Scaffolding</a> which is a quick auto-generator that we tell it about a table we want to scaffold and it will generate all the required Model, Controller and Views to connect with it and control it.</p>
<p>By running the following command we will be able to add, edit, delete and list all the data of our Books table:</p>
<pre>
D:\\Projects\\Book Swap\\bookswap>ruby script/generate scaffold Book Books
      exists  app/controllers/
      exists  app/helpers/
      create  app/views/books
      exists  test/functional/
  dependency  model
      exists    app/models/
      exists    test/unit/
      exists    test/fixtures/
      create    app/models/book.rb
      create    test/unit/book_test.rb
      create    test/fixtures/books.yml
      create  app/views/books/_form.rhtml
      create  app/views/books/list.rhtml
      create  app/views/books/show.rhtml
      create  app/views/books/new.rhtml
      create  app/views/books/edit.rhtml
      create  app/controllers/books_controller.rb
      create  test/functional/books_controller_test.rb
      create  app/helpers/books_helper.rb
      create  app/views/layouts/books.rhtml
      create  public/stylesheets/scaffold.css
</pre>
<p>This command will ask Ruby to run the scaffold generator to create the MVC setup for our table Books, the first parameter after <em>&#8220;scaffold&#8221;</em> is the Model/Table name and notice here that the table name here is not plural as we have specified it in our schema.rb, it&#8217;s Book not Books and this is because Rails will take care of this with it&#8217;s pluralization magic.</p>
<p>The second parameter in the scaffold command is the Controller/View name, basically it will create controller of the same name and a directory in the views directory named books with few templates for each action in the created controller.</p>
<p>Few other files got created too in the process, a helper and few test files, for now we will not deal with any of them  but we can at least understand that for each data table of our database we can have all these structured files, a model to interact with the database and present the table data as objects, a controller which interact with these objects, filter them and prepare them to be viewed by the views which are templates with light embedded ruby code.</p>
<p>With this very minimum work, few commands and modifying a couple of files, we didn&#8217;t even write any code yet but we have something up and running and it&#8217;s time to have a sneak view on how it will look like.</p>
<pre>
D:\\Projects\\Book Swap\\bookswap>ruby script/server
=> Booting WEBrick...
=> Rails application started on http://0.0.0.0:3000
=> Ctrl-C to shutdown server; call with --help for options
[2006-08-20 16:49:04] INFO  WEBrick 1.3.1
[2006-08-20 16:49:04] INFO  ruby 1.8.4 (2005-12-24) [i386-mswin32]
[2006-08-20 16:49:04] INFO  WEBrick::HTTPServer#start: pid=5652 port=3000
</pre>
<p>We don&#8217;t even need to install a webserver while developing a rails application, we can simply try it with <a href="http://www.webrick.org/">WEBrick</a>, the simple http server bundled with rails. It will run by default on port 3000 on the localhost server so let&#8217;s check it out <a href=" http://localhost:3000">http://localhost:3000</a>.</p>
<p><img id="image63" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/06/testapp.png" alt="TestApp Rails Welcome Screen" /></p>
<p>Rails welcomes us, read this page as it has some useful information that we have discussed some and will discuss the rest (routes specifically) in depth later in other parts.</p>
<p>So where is the magic? We have generated a scaffold for the books table and we chose the controller/view name to be books, rails understand that and it will run everything automatically under the following mapping: <em><strong>servername:port/controller/action</strong></em>, in our case the servername is <em>localhost</em> running on port <em>3000</em>, the controller we&#8217;ve created is named <em>books</em> but we don&#8217;t know any action yet but let&#8217;s try this: <a href="http://localhost:3000/books/">http://localhost:3000/books/</a> </p>
<p><img id="image94" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/08/scaffold_books_list.PNG" alt="Book Listing" /></p>
<p>Great!! We have a page with the title <strong>&#8220;Listing Books&#8221;</strong>, an empty table with same headers of our columns names and finally a link that says <em>&#8220;New book&#8221;</em>. By clicking on this link we will see something more wonderful, a ready form, lovely and simple that allows us to add new books to our database.</p>
<p><img id="image95" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/08/scaffold_books_new.PNG" alt="New Book" /></p>
<p>Let&#8217;s try filling it out with some data and add the book, where will we go next? Back to the listing page but now it&#8217;s not empty like before, we have the new book we&#8217;ve just created listed there:</p>
<p><img id="image96" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/08/scaffold_books_add.PNG" alt="Added Book" /></p>
<p>What else have we got there? Three links in same row with our recently created book, <em>Show</em>, <em>Edit</em> and <em>Destroy</em>.. Do we have to explain? Clicking on <em>Show</em> will take us to a separate page that shows only the data of this particular row, <em>Edit</em> will take us to a form page loaded with the information of this record, ready to be edited while <em>Destroy</em> will popup a warning message before it will delete this record. This is it, one line only and the scaffold generator created all this for us.</p>
<p>Follow the URLs of each action and see how they are very meaningful and clean, all this web requests are handled in config/routes.rb as we said above, with the default route (mapping) as /:controller/:action/:id so for example if we go to http://localhost:3000/ books/show/2   routes.rb will forward this request to the books controller to run the show action on the book with 2 as its id.</p>
<p>Naturally scaffolding is not made to be used on its own, it&#8217;s made just to provide us with the very basics functions in a very simple way so we can understand how things work but we have to do the rest and modify the code to what perfectly suit our needs and that is what we will discuss in the next parts.</p>
<h3>At The End</h3>
<p>In this part we have met Rails in a little depth, had a quick look at the file structure it generates and understood some of the migrations and schema magic as well, technically we have now a basic rails application for books where we can add, edit and delete any record at any time after we wrote a very minimum amount of code and left the rest on Rails to take care of.</p>
<p>In the next part we will talk about creating some more tables, discussing migrations a little further and getting a better look with a nice interface and see how to implement the design with our Rails application as well, sorry for the length of this part and see you next week…</p>
]]></content:encoded>
			<wfw:commentRss>http://rida.me/blog/2006/08/20/rails-project-story-1-getting-started/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Programming for Programming&#8217;s Sake</title>
		<link>http://rida.me/blog/2006/07/28/programming-for-programmings-sake/</link>
		<comments>http://rida.me/blog/2006/07/28/programming-for-programmings-sake/#comments</comments>
		<pubDate>Fri, 28 Jul 2006 12:16:43 +0000</pubDate>
		<dc:creator>Rida</dc:creator>
		
		<category><![CDATA[Opinion]]></category>

		<category><![CDATA[Personal]]></category>

		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.ridaalbarazi.com/blog/2006/07/28/programming-for-programmings-sake/</guid>
		<description><![CDATA[You may have heard about the &#8220;Art for Art&#8217;s Sake&#8221; slogan and movement that had spread widely in Europe in the 19th century, this concept of doing the art for the sake of the art itself not just to make money or to satisfy anybody but just to satisfy the art passion and the desire [...]]]></description>
			<content:encoded><![CDATA[<p>You may have heard about the <a href="http://en.wikipedia.org/wiki/Art_for_Art%27s_Sake">&#8220;Art for Art&#8217;s Sake&#8221;</a> slogan and movement that had spread widely in Europe in the 19th century, this concept of doing the art for the sake of the art itself not just to make money or to satisfy anybody but just to satisfy the art passion and the desire of the artist himself.</p>
<p><em><strong>&#8220;Art should be independent of all claptrap—should stand alone, and appeal to the artistic sense of eye or ear, without confounding this with emotions entirely foreign to it, as devotion, pity, love, patriotism and the like.&#8221;</strong> by <a href="http://en.wikipedia.org/wiki/James_McNeill_Whistler">James McNeill Whistler</a></em></p>
<p>This movement included both literature and fine arts at that time but a while after people start to use this concept in different forms like Science for Science&#8217;s Sake and many others considering the wide meaning of art and what it can cover under its umbrella and so is the case with programming, which is an art, art of making beautiful and useful things. (I guess there no better quote than Graham&#8217;s here):</p>
<p><em><strong>&#8220;What hackers and painters have in common is that they&#8217;re both makers. Along with composers, architects, and writers, what hackers and painters are trying to do is make good things. They&#8217;re not doing research per se, though if in the course of trying to make good things they discover some new technique, so much the better.&#8221;</strong>  <a href="http://www.paulgraham.com/hp.html">Hackers and Painters</a> by <a href="http://www.paulgraham.com/">Paul Graham</a></em></p>
<p>Programming isn&#8217;t the same to all programmers, some consider it an art and a craft while others consider it a painful process to earn a living, that&#8217;s why I think Graham wanted to distinguish between programmers and hackers. Hackers according to Graham are the architects of the industry, the software makers who make their masterpieces with creativity and style.</p>
<h3>Does History Repeat Itself?</h3>
<p>One of the main factors that encouraged the art movement at the time it started was the <a href="http://en.wikipedia.org/wiki/Industrial_revolution ">Industrial Revolution</a> when many crafts and work types lost their meaning and purpose because of a machine or a factory alternative, for example painting became more into an abstract art instead of being just a way to image how things looked like; specifically after Photography rise, new ways and styles of painting appeared, schools formed and being an artist got a different meaning.</p>
<p>This is happening now after the <a href="http://en.wikipedia.org/wiki/Digital_Revolution">Digital Revolution</a> and the rise of <a href="http://en.wikipedia.org/wiki/Information_Age">Information Age</a>, many types of work lost their meaning, businesses became much easier, faster and more accurate with computers and high-tech devices, some of these crafts became an art where the rest died, products and services we used to pay a lot of money to get are much cheaper now or even available for free sometimes.</p>
<p>Programming is the act of making software for a computer or any other digital device, it is a result of the digital revolution and what operates it. Here we notice the difference compared to the art case in the 19th century, programming is one of the major weapons of the digital revolution, programming  makes alternatives to many work types in real life so they lose their purpose for a computerized alternatives, where art used to be the victim of the industrial revolution as mentioned earlier.</p>
<p>Programming and Art are similar in different areas and from different aspects, it is a different scenario that may force programming to face similar destiny of art and be done for its own sake.</p>
<h3>The New Concept of Competition</h3>
<p>Programming itself evolved extensively during the past few years, the number of programmers grew dramatically and making software became an easier process as well, many programming languages and frameworks, many communities and methodologies and a completely different market shares for new software development companies.</p>
<p>The existence of communities such as the <a href="http://en.wikipedia.org/wiki/Open_source">Open Source</a> community gave programming a special feature in sharing and understanding, which caused a higher level of knowledge and a very quick development approach, programmers start to learn from each other and share their knowledge to help each other do something better or to complete the undone and has to be done.</p>
<p>In the other hand market giants adopted different approaches, some encouraged open source while others didn&#8217;t where in both cases as giants they had a very good position to take decisions and direct the market. The existence of the giants and open source communities made programming a high level industry in which the ability to be one of the giants isn&#8217;t affordable so programmers either wished to work for the giants or develop a product or service that gets the attention of a huge company that could possibly acquire it.</p>
<p>In my opinion when programming as an industry reach such a level of complexity (market and philosophy wise) it is natural to find a group of programmers who make software for the sake of it and not to compete or anything, just for enjoying what they are doing and share it with others.</p>
<h3>What is Programming&#8217;s Sake?</h3>
<p>Programming for Programming&#8217;s sake is when you write the code with creativity and passion, not only to serve users or to earn your living from it. It is when you make the software for the happiness and joy it brings to your heart, applying your methods and spending enough time refining your masterpiece to let it express you and the art you represent without allowing any other factors to affect your craft.</p>
<p>No matter if the program you are doing is already made before or how simple it may sound, when you give it the artistic quality of your mind it will be different from any other one that has ever been made.</p>
<p>Enjoying what we do is something that we all wish to do but sometimes we are afraid to do it or unable to do it because we don&#8217;t want or unable to give or sacrifice anything for it, we don&#8217;t want to lose our lifestyle, we don&#8217;t want to go for less but the question is: <em>How much are we able to <strong>sacrifice</strong> for something that we really <strong>enjoy</strong>?</em></p>
<h3>The Thin Line</h3>
<p>It may sound simple but it is not, when it comes to real life it&#8217;s very difficult to be able to do what you like, do it for the sake of it and be able to live with it. In the past this has created a completely new culture of <a href="http://en.wikipedia.org/wiki/Bohemianism">Bohemianism</a> where bohemians didn&#8217;t care about the money or traditional life behaviours but cared the most about their own art, doing it for the joy of it and sacrificing everything in a very ignorant way in return.</p>
<p>It is a very thin line that one should be careful before crossing when it comes to sacrifice, life is full of responsibilities but at the end of the day it&#8217;s not important how much you are earning but how happy you are in your life, living without regrets of any sacrifices you made in the past. So I&#8217;m not saying that you should always do the programming for it&#8217;s own sake because I know how difficult this is, specially if you make your living out of it, but a parallel stream with your work will make you happier with your programming and will even make your programs more artisitc.</p>
<p>This whole idea may sound too bohemian and crazy to some people, but with all the craziness it has in it, I really believe in it and I believe that such concepts is a primary step in the life cycle of every craft, I know it is a very tough road to go through and the idea itself still requires some refining in my head which I will keep on posting about until I reach its best shape. If you liked the idea or disliked it go ahead, share your opinion here and let&#8217;s discuss it free and loud&#8230; </p>
]]></content:encoded>
			<wfw:commentRss>http://rida.me/blog/2006/07/28/programming-for-programmings-sake/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Local Development Environment - Part 3</title>
		<link>http://rida.me/blog/2006/06/21/local-development-environment-part-3/</link>
		<comments>http://rida.me/blog/2006/06/21/local-development-environment-part-3/#comments</comments>
		<pubDate>Tue, 20 Jun 2006 21:38:33 +0000</pubDate>
		<dc:creator>Rida</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Ruby on Rails]]></category>

		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.ridaalbarazi.com/blog/2006/06/21/local-development-environment-part-3/</guid>
		<description><![CDATA[After we had our WAMP local server setup done in Part 1 and Part 2, and booting it online via No-IP dynamic DNS service, it&#8217;s time now to talk about installing Ruby on Rails on our server and use Apache 2 along with FastCGI as the webserver for the first option and Mongrel for the [...]]]></description>
			<content:encoded><![CDATA[<p>After we had our <acronym title="Windows Apache MySQL PHP">WAMP</acronym> local server setup done in <a href="http://www.ridaalbarazi.com/blog/2006/05/13/local-development-environment-part-1/">Part 1</a> and <a href="http://www.ridaalbarazi.com/blog/2006/05/26/local-development-environment-part-2/">Part 2</a>, and booting it online via No-IP dynamic DNS service, it&#8217;s time now to talk about installing Ruby on Rails on our server and use Apache 2 along with FastCGI as the webserver for the first option and Mongrel for the second, we will also install few ruby libraries that are commonly used and ensure that they are working and functioning properly by installing a ready rails script.</p>
<h3>Ruby</h3>
<p><a href="http://www.ruby-lang.org/en/">Ruby</a> is a pure object oriented programming language, created by <a href="http://en.wikipedia.org/wiki/Yukihiro_Matsumoto">Yukihiro Matsumoto</a> from Japan around 11 years ago, first it was only in Japanese language, and then got translated into English around 5-6 years ago, where it had an exposure success and a great support.</p>
<p>For Windows the simplest way to install Ruby is via <a href="http://rubyinstaller.rubyforge.org/wiki/wiki.pl">RubyInstaller</a>, the latest stable release is version 1.8.2-15 but we should get version 1.8.4-17 <acronym title="Release Candidate">RC</acronym>2 (this will be explained later) as we are going to prepare for Mongrel as a webserver, you can use 1.8.2 if you will use Apache-FastCGI option only, but version 1.8.4 is more recommended for both cases.</p>
<p><strong>Note:</strong> If you are running any previous version of Ruby and upgrading to Ruby 1.8.4 you may face a problem with your existing Rails applications: &#8220;<em>Invalid char `\002&#8242; in expression</em>&#8221; this error happens because of some wrong tabs interpreting in windows, in order to solve it simply use your preferred editor (I use Notepad++) to replace all tabs by spaces as <a href="http://www.benr75.com/">Ben Reubenstein</a> <a href="http://www.benr75.com/articles/2006/03/28/party-like-its-1-1">advised</a>.</p>
<p>So after you download the <a href="http://rubyforge.org/frs/download.php/10286/ruby184-17_rc2.exe">executable file</a> from <a href="http://rubyforge.org/">RubyForge</a>, run it and don&#8217;t forget to change the setup directory to D:/Development/ruby (the directory we&#8217;ve created to host our development programs files in Part 1).</p>
<p><img id="image62" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/06/ruby_install.png" alt="Ruby 1.8.4-17 RC2 install location" class="centered" /></p>
<p>Ruby is now installed on our system, let&#8217;s try the lovely IRB that comes with it. IRB is an interactive command-line interpreter, which allows us to simply type our code lines and see the results on the spot. </p>
<p>Start the command line (Start->Run->cmd), simply enter the command &#8220;irb&#8221; to start, and to exit you can type &#8220;exit&#8221;.</p>
<p>Error: Could not open irb_test.rb</p>
<p>You can know more about Ruby (if you don&#8217;t already know) from <a href="http://en.wikipedia.org/wiki/Ruby_programming_language">Wikipedia Ruby Programming Language page</a>, and now let&#8217;s move on to see some more Ruby goodness, let&#8217;s meet RubyGems.</p>
<h4>RubyGems</h4>
<p><a href="http://rubyforge.org/projects/rubygems/">RubyGems</a> is the standard packaging system for Ruby, it simplify the distribution of Ruby third party libraries and projects by packing them in a standard format and then allowing us to install it in another simple way too (this is what we will do with Rails).</p>
<p>First download the <a href="http://rubyforge.org/frs/download.php/5208/rubygems-0.8.11.zip">Ruby Gems 0.8.11</a> zip file from <a href="http://rubyforge.org">RubyForge</a>, unzip it, and then run the <em>setup.rb</em> file which will take care of the rest.</p>
<p>Installing Ruby Gems will add a new command &#8220;gem&#8221; that can be used from the command prompt to install, update and build gem packages. Now we will use it to install Rails and many other libraries by simply typing a single command line and let it take care of the rest.</p>
<h3>Ruby on Rails</h3>
<p><a href="http://www.rubyonrails.org/">Ruby on Rails</a> aka Rails aka RoR is the web framework of Ruby, created almost three years back by <a href="http://www.loudthinking.com/">David Heinemeier Hansson</a> as an extraction of his work on <a href="http://www.basecamp.com">BaseCamp</a> (a product of <a href="http://www.37signals.com">37Signals</a>), maintained now by a list of talented developers in <a href="http://www.rubyonrails.org/core">the core team</a> that came from different backgrounds to help Rails be the best friend of every web developer.</p>
<p><acronym title="Ruby on Rails">RoR</acronym> framework implemented to demonstrate a better <acronym title="Model-View-Controller">MVC</acronym> architecture that follows the <acronym title="Don't Repeat Yourself">DRY</acronym> concept, which to help us create better applications in less time and more solid way, personally I moved to Rails because it allowed me to spend more time on algorithms and real programming work instead of just worrying about the regular stuff that we do everyday like connecting to the database and the other<br />
<acronym title="Create Read Update Delete">CRUD</acronym> work.</p>
<p>We will install Rails and all its dependencies via RubyGems using &#8220;gem install&#8221; command, that will first search for the gem file locally, then attempt the remote installation from the robyforge gem repository:</p>
<pre>
D:\\development>gem install rails --include-dependencies
Attempting local installation of 'rails'
Local gem file not found: rails*.gem
Attempting remote installation of 'rails'
Updating Gem source index for: http://gems.rubyforge.org
Successfully installed rails-1.1.2
</pre>
<p>If you are not able to connect to the internet from the command line then you have to install Rails locally by downloading <a href="http://rubyforge.org/frs/download.php/9684/rails-1.1.2.gem">Rails 1.1.2</a> and its dependencies: <a href="http://rubyforge.org/frs/download.php/9571/actionmailer-1.2.1.gem">ActionMailer 1.2.1</a>, <a href="http://rubyforge.org/frs/download.php/9568/actionpack-1.12.1.gem">ActionPack 1.12.1</a>, <a href="http://rubyforge.org/frs/download.php/9681/actionwebservice-1.1.2.gem">ActionWebservice 1.1.2</a>, <a href="http://rubyforge.org/frs/download.php/9680/activerecord-1.14.2.gem">ActiveRecord 1.14.2</a> and <a href="http://rubyforge.org/frs/download.php/9562/activesupport-1.3.1.gem">ActiveSupport 1.3.1</a> as stand alone gems, place them in the directory were you want to run the gem command so it will be able to find them, let&#8217;s say inside D:\Development and see:</p>
<pre>
cd d:\\development
D:\\development>gem install activesupport
Attempting local installation of 'activesupport'
Successfully installed activesupport, version 1.3.1
Installing RDoc documentation for activesupport-1.3.1...

D:\\development>gem install actionpack
Attempting local installation of 'actionpack'
Successfully installed actionpack, version 1.12.1
Installing RDoc documentation for actionpack-1.12.1...

D:\\development>gem install actionmailer
Attempting local installation of 'actionmailer'
Successfully installed actionmailer, version 1.2.1
Installing RDoc documentation for actionmailer-1.2.1...

D:\\development>gem install activerecord
Attempting local installation of 'activerecord'
Successfully installed activerecord, version 1.14.2
Installing RDoc documentation for activerecord-1.14.2...

D:\\development>gem install actionwebservice
Attempting local installation of 'actionwebservice'
Successfully installed actionwebservice, version 1.1.2
Installing RDoc documentation for actionwebservice-1.1.2...

D:\\development>gem install rails
Attempting local installation of 'rails'
Successfully installed rails, version 1.1.2
</pre>
<p>It&#8217;s pretty simple isn&#8217;t it, so now we have Ruby and Rails installed on our machine, let&#8217;s give Rails a try, and see this quick thing that everybody is talking about, we will create a rails application in our webroot folder (the one we have created in Part 1 to be our web root).</p>
<pre>
cd D:\\webroot
D:\\webroot>rails testapp
      create
      create  app/controllers
      create  app/helpers
      .
      .
      .
      .
      create  log/production.log
      create  log/development.log
      create  log/test.log
</pre>
<p>With just this two words command we have got a complete web application hierarchy that we can start from to develop what we need, as this post is getting more longer that expected let&#8217;s just run WEBrick and see what will it look like.</p>
<h4>WEBrick</h4>
<p><a href="http://www.webrick.org/">WEBrick</a> is a library that comes bundled with Ruby to build HTTP servers, it is commonly used as the development server for Rails applications, we will use it now to test the testapp we have just made:</p>
<pre>
D:\\webroot>cd testapp

D:\\webroot\\testapp>ruby script/server
=> Booting WEBrick...
=> Rails application started on http://0.0.0.0:3000
=> Ctrl-C to shutdown server; call with --help for options
[2006-06-20 01:24:33] INFO  WEBrick 1.3.1
[2006-06-20 01:24:33] INFO  ruby 1.8.4 (2005-12-24) [i386-mswin32]
[2006-06-20 01:24:33] INFO  WEBrick::HTTPServer#start: pid=3668 port=3000
</pre>
<p>This will start a light webserver on port 3000, which is the default (changeable) port of WEBrick, be sure if you are running any other services that they are not using this port, how about seeing the results of two lines of work on Rails? Point your browser to <a href="http://localhost:3000">http://localhost:3000</a> and see by yourself.</p>
<p><img id="image63" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/06/testapp.png" alt="TestApp Rails Welcome Screen" class="centered" /></p>
<p>Enough for now, let&#8217;s stop WEBrick (use Ctrl+C) and install some quick gems before we configure FastCGI and Mongrel. </p>
<h4>Extra Goodness - Ruby Libraries and Typo</h4>
<p>Below is a quick list of some useful Ruby libraries that you may use during your development work (description taken from each project&#8217;s RubyForge page):</p>
<ul>
<li><a href="http://rmagick.rubyforge.org/">RMagick</a>: An interface to the <a href="http://www.imagemagick.org">ImageMagick</a> and <a href="http://www.graphicsmagick.org">GraphicsMagick</a> image processing libraries. Supports more than 90 image formats, including GIF, JPEG, PNG. Includes RVG, a 2D drawing API. Comprehensive HTML documentation.<br />
to install: &#8220;<em>gem install RMagick-win32-1.x.x-mswin32.gem</em>&#8221;
</li>
<li><a href="http://libxml.rubyforge.org/">LibXML</a>: The Libxml-Ruby project provides Ruby language bindings for the <a href="http://xmlsoft.org/">GNOME Libxml2</a> XML toolkit. It is free software, released under the MIT License.</li>
<li><a href="http://code.whytheluckystiff.net/redcloth/">RedCloth</a>: A module for using Textile in Ruby. Textile is a text format. A very simple text format. Another stab at making readable text that can be converted to HTML.</li>
<li><a href="http://net-ssh.rubyforge.org/">Net::SSH</a>: Net::SSH is to SSH as Net::Telnet is to Telnet and Net::HTTP is to HTTP. Perform non-interactive SSH processing, purely from Ruby!</li>
<li><a href="http://rubyforge.org/projects/salted-login/">Salted Login</a>: Salted hash loging generator with ActionMailer integration</li>
</ul>
<p>You can read the help of each library if you failed to install it via RubyGems, feel free to leave a comment here if you faced any problems during the installation.</p>
<p>Moving forward to install the Rails script we talked about earlier, we will install <a href="http://www.typosphere.org/trac/wiki/WikiStart">Typo</a>, which is the first Rails Blogging system, quick, simple and widely used among Rails developers, as a start let&#8217;s download it from <a href="http://www.typosphere.org/trac/wiki/WikiStart">Typo Sphere</a>, as you can see from <a href="http://www.typosphere.org/trac/wiki/DownloadStable">Download page</a>, it&#8217;s clearly mentioned that Typo 2.6 will not work with Rails 1.1 or above, so we have to download the <a href="http://www.promotionsickness.com/mirror/typo/typo-2.6.0_with-rails.zip">version with frozen Rails included</a>.</p>
<p>Unzip the downloaded file into the web root folder and let&#8217;s rename it to &#8220;blog&#8221; so we get Typo in D:\webroot\blog , now we have to prepare the required database for it, we will create a database and name it &#8220;blog&#8221; and insert the typo MySQL schema from D:\webroot\blog\db\schema.mysql.sql into it using the command line:</p>
<pre>
D:\\webroot\\blog>mysql --user=root --password
Enter password: ********
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 80 to server version: 5.0.21-community-nt

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> CREATE DATABASE blog
    -> ;
Query OK, 1 row affected (0.00 sec)

mysql> quit
Bye

D:\\webroot\\blog>mysql --user=root --password --database=blog\<"D:\\webroot\\blog\\db\\schema.mysql.sql"
Enter password: ********
</pre>
<p>Finally to get Typo working we have to update the <a href="http://www.yaml.org/">YAML</a> file responsible about connecting Typo to its database, this file is called database.yml and it&#8217;s located in D:\webroot\typo\config, all we have to do is changing the password line and place the password we used while installing MySQL in Part 2, then changing the production database from &#8220;typo&#8221; to &#8220;blog&#8221; (the line before last), save the file and let&#8217;s run WEBrick in production mode (from inside the blog folder) to see if we everything is fine or not yet..</p>
<pre>
D:\\webroot\\blog>ruby script/server -e=production
</pre>
<p>Pingo!! It&#8217;s running and asking us to complete our admin information, just complete it and have a look at the lovely admin panel and the Ajax goodness implemented inside, although I suggest that you just wait a little bit more to do the Apache or Mongrel integration, at least so you will be able to run it safely online even in production.</p>
<p><img id="image64" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/06/typo.png" alt="Typo Setup Screen" class="centered"  /></p>
<h3>Apache2 and FastCGI</h3>
<p>FastCGI with Apache is considered one of the best production environment for Rails applications, although there are many alternatives like LightTPD-FastCGI (Which is better), and Mongrel which will be explained here as well.</p>
<p>The first things we need are the mod_fcgi and mod_sql files that are available in the quick <a href="http://rubyforge.org/frs/download.php/5256/RubyForApache-1.3.1.exe">installer</a> package named <a href="http://rubyforge.org/projects/rubyforapache/">Ruby for Apache</a>, it&#8217;s a straight forward installer that will ask you about the locations of both Apache and Ruby, which are both located in D:\development where we installed them earlier.</p>
<p><img id="image65" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/06/rubyforapache.png" alt="Ruby for Apache" class="centered" /></p>
<p>We don&#8217;t need the mod_ruby file (I even heard that it may make some conflicts too), so anyhow let&#8217;s choose mod_fcgi and mod_sql only and start editing our httpd.conf file to configure FastCGI.</p>
<p>Mainly there are three steps to configure FastCGI with Apache and all of them are in httpd.conf file that if you remember is located in D:\Development\Apache\conf\httpd.conf :</p>
<ul>
<li>First let&#8217;s load the FastCGI module by adding the following lines to the LoadModule section:
<p>Error: Could not open fcgi_apache_1.conf</p>
</li>
<li>Secondly let&#8217;s configure FastCGI itself, preparing it for the production environment, configuring the min/max processes allowed and define the initial environment variables to lead FastCGI to the Ruby and MySQL directories.
<p>Error: Could not open fcgi_apache_2.conf</p>
</li>
<li>
<p>And finally it&#8217;s time for the VirtualHost information to be defined. Here there are two options to think of depending on your requirements and situation, for example I have an ISP that block the port 80 (as I mentioned in Part 1) so I won&#8217;t be able to run the virtual host as another subdomain referring to my server, but I have to load it on another port and make a direction later.</p>
<p>As I said, depending on your situation you should chose what best fits your needs, starting with the first option, we will create a new subdomain and refer it to our IP, you can do this simply by following the same steps mentioned in Part 1 for No-IP, and then at the bottom of httpd.conf we will add the VirtualHost details as follows:</p>
<p>Error: Could not open virtual_host2.conf</p>
<p>The second option (which is the one I&#8217;m using currently) is where I define a new port for my rails application and then make a quick Apache redirect toward it. First we have to tell Apache to listen to the desired port, then configure the virtual host of this port to refer to our Rails application.</p>
<p>Error: Could not open virtual_host.conf</p>
</li>
</ul>
<p>If you created the Rails application using the &#8220;rails&#8221; command on your Win32 machine then dispatch.fcgi will automatically refer to your local Ruby file, but for ready scripts like Typo for example the referred to Ruby is the default Ruby path on Linux systems and has to be changed, to do that simply edit the first line of dispatch.fcgi (located in the &#8220;public&#8221; directory of every Rails application) from:</p>
<pre>#!/usr/bin/env ruby</pre>
<p>to:</p>
<pre>#!d:/development/ruby/bin/ruby</pre>
<p>This will tell FastCGI where your ruby bin files are located and so it will run peacefully.</p>
<p><strong>Note</strong>: The above information were gathered from other websites that had solved the difficulties of integrating FastCGI with Apache like <a href="http://dema.ruby.com.br/">Demetrius Nunes</a>&#8217;s &#8220;<a href="http://dema.ruby.com.br/articles/2005/08/23/taming-fastcgi-apache2-on-windows">Taming FastCFI+Apache on Windows</a>&#8221; and <a href="http://scottstuff.net/">Scott Laird</a>&#8217;s &#8220;<a href="http://scottstuff.net/blog/articles/2005/07/20/apache-tuning-for-rails-and-fastcgi">Apache tuning for Rails and FastCGI</a>&#8221; and other resources too.</p>
<h3>Mongrel</h3>
<p>Mongrel is very to WEBrick from it&#8217;s working point of view, although it&#8217;s much faster and more suitable for productive environments than WEBrick, it also run on a specific port and now it is well supported on Windows systems, Mongrel now can be installed as a system service which makes it more stable and better configurable.</p>
<p>To start working with Mongrel we have to install it along with its dependencies, gratefully using RubyGems:</p>
<pre>
D:\\development>gem install mongrel_service
Attempting local installation of 'mongrel_service'
Local gem file not found: mongrel_service*.gem
Attempting remote installation of 'mongrel_service'
Updating Gem source index for: http://gems.rubyforge.org
Install required dependency gem_plugin? [Yn]  y
Install required dependency mongrel? [Yn]  y
Select which gem to install for your platform (i386-mswin32)
 1. mongrel 0.3.13 (mswin32)
 2. mongrel 0.3.13 (ruby)
 3. mongrel 0.3.12.4 (ruby)
 4. mongrel 0.3.12.4 (mswin32)
 5. Cancel installation
> 1
Install required dependency win32-service? [Yn]  y
Select which gem to install for your platform (i386-mswin32)
 1. win32-service 0.5.0 (mswin32)
 2. Cancel installation
> 1
Successfully installed mongrel_service-0.1
Successfully installed gem_plugin-0.2.1
Successfully installed mongrel-0.3.13-mswin32
Successfully installed win32-service-0.5.0-mswin32
Installing RDoc documentation for mongrel_service-0.1...
Installing RDoc documentation for gem_plugin-0.2.1...
Installing RDoc documentation for mongrel-0.3.13-mswin32...
Installing RDoc documentation for win32-service-0.5.0-mswin32...
</pre>
<p>Now that Mongrel is installed on our system, we have two commands that we have to use for every Rails application we have and want to run it using Mongrel, the first is where we install the service (check your Windows Services from Control Panel), to do this we have to change directory to the application we want to Mongrel it and then run the command:</p>
<pre>
cd D:\\webroot\\blog
D:\\webroot\\blog>mongrel_rails service::install -N blog -c D:\\webroot\\typo -p 4000 -e production
Mongrel service 'blog' installed as 'blog'.
</pre>
<p>Notice that in the above command we have specified the environment (using -e option) as production, and the port (using -p option) to be 4000 and we named the service &#8220;blog&#8221;, now the service is already installed on our Win32 system, we can run it from Control Panel -> Administrative Tools -> Services or by the command:</p>
<pre>
D:\\webroot\\blog>mongrel_rails service::start -N blog
</pre>
<p>Have a look at <a href="http://localhost:4000">http://localhost:4000</a> now and see how it is working. You can leave Mongrel working on this specific port, or make an Apache proxy redirect to it, which is very similar to the first option we had for virtual hosts in FastCGI scenario but with two extra line:</p>
<p>Error: Could not open mongrel_apache.conf</p>
<p>This will redirect any request to &#8220;/&#8221; which is the root of the domain to the specific port 4000 at localhost where Mongrel is already running. Note that you have to enable the mod_proxy module from LoadModule section first to get this working</p>
<p>More information about Mongrel on Win32 systems can be found on <a href="http://mongrel.rubyforge.org/docs/win32.html">Mongrel official website</a>, I know this was a very long post, much longer than the previous two parts, but at the same I couldn&#8217;t help myself from pointing up some notes and important points that might save your time while preparing this setup, I hope this was useful and helpful.</p>
<p>Now with the end of this part, we have our local development environment ready to host any Rails application, actually it&#8217;s already hosting Typo blogging system, using Apache2 with FastCGI or Mongrel environments for a better performance, along with PHP and MySQL that we have installed in Part 2 and No-IP that we have installed in Part 1 to allow our local webserver to go live and online. In the next part (which is the last one), Subversion will be explained and installed, allowing us to collaborate better with our colleagues and friends, creating our own repositories or even using an external one, so stay tuned and hopefully it will be shorter than this one&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://rida.me/blog/2006/06/21/local-development-environment-part-3/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Local Development Environment - Part 2</title>
		<link>http://rida.me/blog/2006/05/26/local-development-environment-part-2/</link>
		<comments>http://rida.me/blog/2006/05/26/local-development-environment-part-2/#comments</comments>
		<pubDate>Fri, 26 May 2006 04:07:34 +0000</pubDate>
		<dc:creator>Rida</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.ridaalbarazi.com/blog/2006/05/26/local-development-environment-part-2/</guid>
		<description><![CDATA[Last time in Part 1 of this article we prepared our Apache web server and MailEnable mail server and assured that they are available online with a hostname of our choice that is dynamically updated with our IP via No-IP DUC.
Now in Part two we will install MySQL as the Database server, and PHP with [...]]]></description>
			<content:encoded><![CDATA[<p>Last time in <a href="http://www.ridaalbarazi.com/blog/2006/05/13/local-development-environment-part-1/">Part 1</a> of this article we prepared our Apache web server and MailEnable mail server and assured that they are available online with a hostname of our choice that is dynamically updated with our IP via No-IP <acronym title="Dynamic Updater Client">DUC</acronym>.</p>
<p>Now in Part two we will install <a href="http://www.mysql.com">MySQL</a> as the Database server, and <a href="http://www.php.net">PHP</a> with its integration with Apache using Apache Modules and finally we&#8217;ll install <a href="http://turboajax.com/turbodbadmin/">TurboDBAdmin</a> script as the online database administration script.</p>
<h3>MySQL Database</h3>
<p><a href="http://www.mysql.com">MySQL</a> is a free SQL database management system, one of the most famous databases available now for open source development specially with PHP, many books have been written on both, it is also known as a key of both <acronym title="Linux Apache MySQL PHP">LAMP</acronym> and <acronym title="Windows Apache MySQL PHP">WAMP</acronym> the two most used open source development environments. Now let&#8217;s start the installation:</p>
<ul>
<li>Run the installation wizard downloaded in <a href="http://www.ridaalbarazi.com/blog/2006/05/13/local-development-environment-part-1/">Part 1</a>, and choose &#8220;Custom setup&#8221; in order to change the directory to your development path <em>D:\development</em>:</li>
</ul>
<p><img id="MySQL_custom" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/05/mysql_custom.gif" alt="MySQL Custom Installation" class="centered" /></p>
<ul>
<li>&#8220;Skip Sign-UP&#8221; in the &#8220;MySQL.com Sign-Up&#8221; screen, unless you prefer to do so.</li>
<li>After the installation wizard is done check the &#8220;Configure the MySQL Server Now&#8221; box in order to start the configuration wizard.</li>
<li>In &#8220;MySQL Server Instance Configuration&#8221; choose &#8220;Standard Configuration&#8221;, then confirm that the &#8220;Install As Windows Service&#8221;, &#8220;Launch the MySQL Server automatically&#8221; and &#8220;Include Bin Directory in Windows PATH&#8221; options are checked.</li>
<li>Now in the &#8220;Security Options&#8221;, as we have our server available online, we don&#8217;t want to allow any access to our MySQL server from outside, so we will set a password for our &#8220;root&#8221; user account and disable both anonymous account and remote access from remote machines options.</li>
</ul>
<p><img id="MySQL_security" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/05/mysql_security.gif" alt="MySQL Security Configuration" class="centered" /></p>
<p>By setting the security options and finalizing the configuration wizard we have MySQL up and running on our local server, MySQL essential package doesn&#8217;t come with any graphical interface for the database system, so after we install PHP and integrate it with Apache we will install TurboDBAdmin as our graphical interface which will be available online as well.</p>
<h3>PHP</h3>
<p>I prefer the manual installation of PHP as it includes more extensions and it is more customizable, and luckily it is not difficult to do, just unzip the downloaded PHP compressed file (from <a href="http://www.ridaalbarazi.com/blog/2006/05/13/local-development-environment-part-1/">Part 1</a>) into your development directory <em>D:\Development</em>, and that&#8217;s it, PHP is there now, we only need to add it to the Windows PATH environment variables, and apply the PHP5Apache2 module.</p>
<p>To setup the Windows PATH variables go to Windows Control Panel -> System, and from the Advanced tab click on the &#8220;Environment Variables&#8221; button, in the System Variable section, edit the PATH variable and add your PHP path <em>D:\development\php</em> where php.exe exists, now wherever PHP is called it will be found.</p>
<h4>Configuring Apache</h4>
<p>In order to allow Apache to parse any PHP code placed in our web directory we have to load the PHP5 Apache2 Module, the module is available as a <acronym title="Dynamic Link Library">DLL</acronym> file in our php directory under the name <em>php5apache2.dll</em>, we have to load it in Apache, add php file type and specify the PHP Ini Directory by adding the following lines to our <em>httpd.conf</em> file (located in <em>D:\development\Apache2\conf\</em>):</p>
<p>Error: Could not open httpd.conf</p>
<p>To keep your <em>httpd.conf</em> clean and organized insert the above lines in the <acronym title="Dynamic Shared Object">DSO</acronym> Support section right after the default modules loads, and don&#8217;t forget to restart Apache after saving the changes.</p>
<p>To test PHP let&#8217;s create a small PHP file that call the php information function in our webroot folder <em>D:\webroot\info.php</em> and let&#8217;s try it <a href="http://yoursubdomain.no-ip.org:8520/info.php">http://yoursubdomain.no-ip.org:8520/info.php</a></p>
<p>Error: Could not open info.php</p>
<p>The <strong>phpinfo()</strong> function shows all the information about PHP on the local server in a nice html markup. Now PHP is working perfectly, you can run any PHP script not only locally but online also as you have an online web server.</p>
<h3>TurboDBAdmin</h3>
<p>With our secure database and the ability to run PHP scripts, we will install <a href="http://turboajax.com/turbodbadmin/">TurboDBAdmin</a> which is a PHP script with some lovely <acronym title="Asynchronous JavaScript and XML">Ajax</acronym> touches that gives a nice interface to our database, and we will secure it using <em>.htaccess</em>.</p>
<p>To run the script just unzip the downloaded TurboDBAdmin compressed file (from <a href="http://www.ridaalbarazi.com/blog/2006/05/13/local-development-environment-part-1/">Part 1</a>) to the webroot folder as <em>D:\webroot\turbodbadmin\</em>, and edit the configuration file <em>D:\webroot\turbodbadmin\php\config.php</em> to meet your database credentials, by changing the &#8220;root&#8221; password around line 10 to the one you have created earlier during MySQL configuration wizard.</p>
<p>Let&#8217;s try it now: <a href="http://yoursubdomain.no-ip.org:8520/trubodbadmin">http://yoursubdomain.no-ip.org:8520/trubodbadmin</a>, it&#8217;s working and we are able to see our database system, create tables, import, export, etc&#8230; Great but this script is available online now and anybody who knows the url can mess up our database system so let&#8217;s secure this directory using http security.</p>
<h4>Securing TurboDBAdmin</h4>
<p>To secure our script we will use http security by creating .htaccess and htpasswd users file into the script directory, first lets create the user file:</p>
<ul>
<li>From the command prompt change directory to <em>D:\development\Apache\bin\</em>
<pre>cd D:\\development\\Apache\\bin\\</pre>
</li>
<li>Use the htpasswd tool provided by Apache to create your users file with the user of your choice:
<pre>htpasswd -c D:\\webroot\\turbodbadmin\\users admin</pre>
<p>It will prompt you for the password to create, and creates the file for you, if you want to add other users to your users file just use the same command without &#8220;-c&#8221; option:</p>
<pre>htpasswd D:\\webroot\\turbodbadmin\\users <em>username</em></pre>
</li>
<li>Using a text editor of your choice create a new file as <em>D:\webroot\turbodbadmin\.htaccess</em> (notice the dot before the name):
<p>Error: Could not open htaccess</p>
</li>
<li>Finally we have to change Apache configuration to allow AuthConfig, in httpd.conf in DocumentRoot Directory directive, you will find:
<pre>
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
    AllowOverride None
</pre>
<p>Which we have to change into:</p>
<pre>AllowOverride AuthConfig</pre>
<p>Restart Apache now and check <a href="http://yoursubdomain.no-ip.org:8520/turbodbadmin/">http://yoursubdomain.no-ip.org:8520/turbodbadmin/</a> and finally we have our script folder secured.</p>
</li>
</ul>
<p>You can generate your own .htaccess and htpasswd files using <a href="http://www.htaccesstools.com/">.htaccess Tools</a> website, it has some other nice features too.</p>
<h3>Summary</h3>
<p>After two parts of this article we have a complete WAMP environment, Apache 2, MySQL 5 and PHP 5 installed and working perfectly on our Win32 box, we also installed TurboDBAdmin script as our online graphical interface to administer MySQL, and secured it using Apache security.</p>
<p>In the next part I&#8217;ll be talking about Ruby and Rails and how to configure them on Windows as it needs a complete individual post to talk about it.</p>
]]></content:encoded>
			<wfw:commentRss>http://rida.me/blog/2006/05/26/local-development-environment-part-2/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Local Development Environment - Part 1</title>
		<link>http://rida.me/blog/2006/05/13/local-development-environment-part-1/</link>
		<comments>http://rida.me/blog/2006/05/13/local-development-environment-part-1/#comments</comments>
		<pubDate>Sat, 13 May 2006 01:37:08 +0000</pubDate>
		<dc:creator>Rida</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.ridaalbarazi.com/blog/2006/05/13/local-development-environment-part-1/</guid>
		<description><![CDATA[Being a web developer who worked on several open source projects remotely with some friends and colleagues, I have faced some difficulties at the beginning getting my development setup done correctly and available online, specially as being behind the proxy of my internet provider. But now after some work I have a stable local development [...]]]></description>
			<content:encoded><![CDATA[<p>Being a web developer who worked on several open source projects remotely with some friends and colleagues, I have faced some difficulties at the beginning getting my development setup done correctly and available online, specially as being behind the proxy of my internet provider. But now after some work I have a stable local development environment that helped me get more organized, support all my development requirements and luckily available live and online.</p>
<p>In this article I&#8217;ll share how I prepared this environment on my Windows XP system, it will cover the installation of a web server, mail server, database server, open source programming languages, version control, and some other quick tools too, all of the tools and applications used here are either open source or freeware, below are the links to download them before we start:</p>
<ul>
<li><strong>Dynamic DNS</strong>: <a href="http://www.ridaalbarazi.com/files/lde/ducsetup.exe" title="684032 Byte">No-IP DUC (Dynamic Update Client) 2.2.1</a></li>
<li><strong>Web Server</strong>: <a href="http://www.ridaalbarazi.com/files/lde/apache_2.0.55-win32-x86-no_ssl.msi" title="4412416 Byte">Apache 2.0.55 for Windows</a>.</li>
<li><strong>Mail Server</strong>: <a href="http://www.ridaalbarazi.com/files/lde/mailenablestandard.exe" title="7711642 Byte">MailEnable Free Edition</a>.</li>
<li><strong>Database Server</strong>: <a href="http://www.ridaalbarazi.com/files/lde/mysql-essential-5.0.21-win32.msi" title="16702976 Byte">My SQL Essential 5.0.21</a>.</li>
<li><strong>Programming Languages</strong>: <a href="http://www.ridaalbarazi.com/files/lde/php-5.1.4-Win32.zip" title="9133167 Byte">PHP 5.1.4</a>, <a href="http://www.ridaalbarazi.com/files/lde/ruby182-15.exe" title="15492542 Byte">Ruby 1.8.2-15</a>.</li>
<li><strong>Version Control</strong>: <a href="http://www.ridaalbarazi.com/files/lde/TortoiseSVN-1.3.3.6219-svn-1.3.1.msi" title="7799296 Byte">TortoiseSVN 1.3.3 SVN 1.3.1</a>.</li>
<li><strong>Tools</strong>: <a href="http://www.ridaalbarazi.com/files/lde/turbodbadmin_0.2.3.zip" title="523842 Byte">TurboDbAdmin 0.2.3</a>, <a href="http://www.ridaalbarazi.com/files/lde/npp.3.5.Installer.exe" title="966374">Notepad++ 3.5</a> and <a href="http://www.ridaalbarazi.com/files/lde/FileZilla_2_2_22_setup.exe" title="3503265 Byte">FileZilla 2.2</a></li>
</ul>
<p>Just before we start let&#8217;s decide the directories we will use, I don&#8217;t recommend using the system drive for this (normally it&#8217;s Local Disk C:) in order to separate the development environment files from the system files, if you have another partition it would be much better but at the end it&#8217;s your own choice, mainly we will need two directories:</p>
<ul>
<li><strong>development</strong> where we are going to place all the program files of our tools and servers.</li>
<li><strong>webroot</strong> as the web root folder where we will put our scripts and projects files.</li>
</ul>
<p>Naturally you can use your own names and places for these folders, in this tutorial I&#8217;ll refer to them as <strong>D:\development</strong> and <strong>D:\webroot</strong>, now we have the files and the directory structure ready so let&#8217;s get to work.</p>
<h3>No-IP Dynamic Update Client</h3>
<p><a href="http://www.no-ip.com">No-IP</a> is a dynamic/managed DNS service. Simply when you don&#8217;t have a static IP, installing the dynamic updater provided by No-IP will automatically update your dynamic IP to a given subdomain of your choice.</p>
<p>As a start you have to <a href="http://www.no-ip.com/newUser.php">sign up</a> for a free account, after signing up and verifying your email it&#8217;s time to setup your subdomain, to do that login to your account and from the left sidebar, under &#8220;<strong>Hosts / Redirects</strong>&#8221; choose <strong>Add</strong>:</p>
<p><img id="no-IP_setup" class="centered" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/05/no-ip-setup_s.gif" alt="No-IP configuration screen" /></p>
<p>Never simpler, in the <strong>Hostname</strong> field type a subdomain of your choice to be the address that will always redirect to your local machine, you can choose the domain on which you want your address to be, confirm that the <strong>Host Type</strong> is <strong>DNS Host (A)</strong>, leave all the other options as is and <strong>Create Host</strong>.</p>
<p>Install the <strong>No-IP DUC</strong> that you have already downloaded earlier, choose the development path we have created <em>D:\development</em> to store the program files in. The first step after the installation is to enter the account details, the email address and password you signed up with, so we can reach our account window to see our hosts and activate them.</p>
<p>From the No-IP window go to <strong>Options</strong>, from the first tab <strong>Standard</strong> check the first and the third options that will make the dynamic updater <em>Run on startup</em> and <em>Run as system service</em> so you don&#8217;t have to worry about it anymore, if you use a proxy for your internet connection configure it from <strong>Connection</strong> -> <strong>Proxy</strong>. When you are done confirm your changes and close the Options dialog box.</p>
<p>Back to your No-IP window, the host you have created online is listed here with an empty checkbox next to it, checking this box will update your IP with this host, to test No-IP configurations you can either ping your subdomain from the command prompt and see if it&#8217;s replying with your IP or wait until we finish installing Apache and test your live web server.</p>
<h3>Apache Web Server</h3>
<p><a href="http://httpd.apache.org/">Apache</a> is an open-source HTTP server, <a href="http://news.netcraft.com/">Netcraft</a> <a href="http://news.netcraft.com/archives/2006/05/09/may_2006_web_server_survey.html">claims</a> that more than 62.72% of the websites online uses Apache, which makes it the most commonly used web server, specially for open-source projects. It&#8217;s easy to use, secure, efficient and extensible.</p>
<h4>Installing Apache</h4>
<p>Run the installation file downloaded earlier (named apache_2.0.55-win32-x86-no_ssl.msi), accept the license agreement, read about Apache, and then let&#8217;s configure the server:</p>
<p><img id="apache_install" class="centered" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/05/apache-install_s.jpg" alt="Apache configuration dialog box" /></p>
<p>In this dialog box we will use the No-IP hostname that we have created few minutes ago <em>yoursubdomain.no-ip.org</em> for both <strong>Network domain</strong> and <strong>Server name</strong>, use your own email address as the administrator&#8217;s email and finally keep the last option on Port 80 as we will change it later.</p>
<p>Typical install is fine, then we have to choose the installation folder, as we have decided to keep all our development files in one directory we will choose <em>D:\development</em> as the path.</p>
<p>If you have any firewall installed (most likely Windows XP SP2) you may see some warning message after the installation is done, simply unblock and here we go, Apache is up and running and welcoming you at <a href="http://localhost">http://localhost</a>.</p>
<p><img id="apache_welcome" class="centered" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/05/apache_s.gif" alt="Apache welcome screen" /></p>
<h4>Configuring Apache</h4>
<p><strong>The port</strong>, If you have such a great ISP like mine, that prevent you from enjoying the port 80, the only way to get your web server available online is by changing the port, we can do this by simply editing the <em>httpd.conf</em> file located inside <em>D:\development\Apache2\conf\</em> folder.</p>
<p>Search for &#8220;Listen 80&#8243; or simply go to line 120, now just change the port to your own, personally I use an easy to type number 8520, save and restart Apache from the system tray icon -> Open Apache Monitor -> Restart, let&#8217;s try again… <a href="http://localhost:8520">http://localhost:8520</a> the same apache welcome page has just moved, now let&#8217;s simply test it with our online No-IP hostname and see if it will work, http://yoursubdomain.no-ip.org:8520. Pingo our server is online too.</p>
<p><strong>Modules</strong>, Apache comes with the most used modules enabled already, but personally I recommend you uncomment the <em>rewrite_module</em>, <em>dav_module</em> and <em>dav_fs_module</em> as you may need them in your development, from <em>httpd.conf</em> file again simply remove the hash &#8220;#&#8221; from the beginning of each of the lines (145, 146, 164), save and restart Apache. We will add some more modules later when we will need them for our programming languages.</p>
<p><strong>Document Root</strong>, You may like to change your web document root also, which is currently under the Apache2 folder with the name <em>htdocs</em>, to do that we have to change to paths in <strong>httpd.conf</strong> you can find them by searching for &#8220;DocumentRoot&#8221;, you will find the <em>DocumentRoot</em> and the <em>Directory</em> directives that have to be changed. (careful with the reversed slashes), we will use the one we have created earlier for this purpose <em>D:/webroot</em>, save and restart Apache and check the results <a href="http://localhost:8520">http://localhost:8520</a>.</p>
<p>You will get 403 Forbidden message as you don&#8217;t have access to the root directory, or in other words you don&#8217;t have access to the directory listing of the web root folder, as this option is important for security reasons we will not change it, you can solve it by adding a simple html page in our webroot directory and name it index.html.</p>
<p>More information about installing Apache on Windows platform can be found online at <a href="http://httpd.apache.org/docs/2.0/platform/windows.html">Apache website</a>.</p>
<h3>MailEnable</h3>
<p><a href="http://www.mailenable.com/">MailEnable</a> Standard Edition is a freeware mail server with fully functional POP and SMTP mail services, which will allow us to send emails from our local server, mainly by connecting to a local SMTP server.</p>
<p>With the simplicity of its install MailEnable needs only two configuration steps during the installation process:</p>
<ul>
<li>Post office details, keep it simple, your name or your group name and a password, you will rarely need this. </li>
<li>Domain name, DNS servers and SMTP port, the domain name is the same No-IP hostname we have created <em>yourdomainname.no-IP.org</em> and your DNS should be already loaded there.</li>
</ul>
<p><strong>Note</strong>: If the DNS details are not mentioned automatically and you don&#8217;t know them, simply go to Start -> Run -> type &#8220;<strong>cmd</strong>&#8221; and run, type the command: &#8220;<strong>ipconfig /all</strong>&#8221; and you will get all the information you need, you will see two IPs for the DNS server(s) just copy them with a comma in the middle.</p>
<p>Finally the SMTP port, only if your ISP blocks this port change it, otherwise it&#8217;s much better to leave the default port, if you change this port you will have to change it every time you configure any mail function in your scripts.</p>
<p><img id="MailEnable_install" class="centered" src="http://www.ridaalbarazi.com/blog/wp-content/uploads/2006/05/MailEnable-install.gif" alt="MailEnable install configuration" /></p>
<p>To be sure you got your installation right, just run the &#8220;Diagnostic Utility&#8221; (if you have an antivirus it will prompt you for a virus, just ignore it as it is part of the diagnostic test and not a real virus), check the following items in the html result file and ensure that they have all their sub-items passed the test:</p>
<ul>
<li>Host TCP/IP Settings</li>
<li>SMTP Configuration Test</li>
<li>SMTP Relay Settings</li>
<li>SMTP Inbound Bindings Test</li>
<li>SMTP Outbound Configuration</li>
</ul>
<p>MailEnable is now installed successfully and any script that requires a mail server will use it as its SMTP server, it has many lovely features too, and a user friendly administration panel, you can find more about it on <a href="http://www.mailenable.com/standard_edition.asp">MailEnable - Standard Edition</a> page online.</p>
<h3>Summary</h3>
<p>Now we have a local http server (Apache) and a mail server (MailEnable), available online (via No-IP) with our own hostname which we can access it from anywhere.</p>
<p>Part two of this article will cover the installation of a database server (MySQL), programming languages and their Apache modules, and then we are going to test them by trying some quick scripts too.</p>
]]></content:encoded>
			<wfw:commentRss>http://rida.me/blog/2006/05/13/local-development-environment-part-1/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>

