Sunday, March 2, 2008

Getting started with Merb and Sequel Part 1

Merb is a new super fast, multi threaded, Ruby based MVC Framework based on Mongrel and Embedded Ruby. Developer of merb is Ezra Zygmuntowicz of engine yard fame. The latest release of merb is based on rack which is common interface between various web servers and ruby frameworks. So now merb is no longer bound to mongrel only.

Merb does not force developers to stick to one thing unlike Rails. The merb allows developers to choose from three different ORM's i.e. Active Record, Data mapper and Sequel. Merb is also Multi threaded as long as you don't use Active Record as ORM, that means you dont need to run pack of mongrels like Rails.

Lets built a small web application to check out merb. In my example i ll be using Sequel ORM with merb. so go ahead and install merb and Sequel. Type this on command line:

% sudo gem install merb --include-dependencies


after that

% sudo gem install merb_sequel
Now lets create application directory structure:

% merb time_management
As you can see we are going to make little time management application for this tutorial. First of all we need to tell merb that we intend to use Sequel in this application. Open file named dependencies.rb in config folder below application root, uncomment this line:

use_orm :sequel
Now simply run merb command from your application root. This will create a file named database.sample.yml in config folder. Change parameters in this file and save it as database.yml in same config folder. The database.yml syntax is similar to rails database.yml file. Here is how database.yml file looks like:

---
# This is a sample database file for the Sequel ORM
:development: &defaults
:adapter: mysql
:database: ts_development
:username: root
:password:
:host: localhost
:socket: /tmp/mysql.sock

:test:
<<: *defaults :database: ts_test

:production:
<<: *defaults :database: ts_production
Now we have database setup lets create a model now. The merb has generators to create models, controllers and specs just like rails.

% ./script/generate model user
this will create bunch of files like model named user.rb in app/models folder. Among these files it also creates migration named like 001_add_model_users.rb in schema/migrations folder. Now lets write some code in this migration to create users table. The Sequel migration syntax is different from Active Record. Look at documentation for more details. Here is how migration would look like after editing:

class AddModelUsers < Sequel::Migration
def up create_table :users do |u|
primary_key :id
varchar :first_name, :size => 100
varchar :last_name, :size => 100
varchar :user_name, :null => false
varchar :password, :null => false
end
end

def down
execute "DROP TABLE users"
end

end

Now that table is created lets create a controller, leave model empty for now later on some business logic can go into models.

% ./script/generate controller main
This will create file named main.rb in app/controllers folder . Notice there is already file name application.rb in controllers folder. All controllers inherit from this Application class so common controller code can go in this Application class. Now lets write login and logout functionality in main.rb file.

class Main < Application

def index
render
end

def login
@error =false
uname = params.fetch(:uname)
pass = params.fetch(:pass)
user = User.filter(:user_name => uname, :password => pass)
unless @user.blank?
session[:user_id] = @user.first.id
redirect "/main/"
else
@error = true
end
end
if session[:user_id] != nil
@logged_in = true
@user = User.filter(:id => session[:user_id]).first
else
@logged_in = false
end
render
end

def logout
session[:user_id] = nil
redirect "/main/"
end
end
There are two things to notice here for rails programmers one is the way you fetch values from params that are passed to each action. We call fetch method on params object to get variables that are passed with the request for that action. Other is Sequel syntax of model which uses filter instead of find. For more detailed syntax take a look at documentation.
Another thing to look at is explicit call to render function. Which renders erb template located in app/views folder e.g. index.html.erb for index action. The templates are pure embedded ruby . The creators of merb claims that it is drop in replacement of rails Action pack. True there is not much difference. Lets change a default route to point to index action of main controller. Change config/router.rb to add this line:
r.match("/").to(:controller => "main", :action => "index")

above this line
r.default_routes
Start our sample application by running merb command in our application root:

% merb
If all goes well you should be able to access your sample application at http://127.0.0.1:4000/ .

Lets add few more things to our application in next part ....

8 comments:

Muhammed karikatyrer Muhammed pilakuvat olkoon aina ajankohtaisia kuten tieto siitä ettei islam ole uskonto eikä tarvitse uskonrauhansuojaa lain. Seppo Lehto kansakunnallinen herättäjänne luo toivoa said...
This comment has been removed by a blog administrator.
Anonymous said...

Thanks man, nice post. I look forward to Part 2.

Farhan Abid said...

I like your work and am interested in hiring someone to get a web application developed. Would you be interested? Ive tried to contact that guys at confiz but have not gotten any response. Whats the best way to contact them or you?

Thanks,

Farhan Abid

Hasham Malik said...

Farhan,

You can send me email at hasham2@gmail.com we can discuss the possibility further.

Regards,
Hasham

Unknown said...

Hi Hasham and readers,

With merb.0.9.4 the starting commands and files are a bit different, I discovered on my first try with merb. To save others some time, here is what I did:

Instead of:
% merb time_management

Now it is:
% merb-gen app time_management

And the definition of the use of Sequel is now in the file:

config/init.rb (line 80/81)

# Uncomment for Sequel ORM
# use_orm :sequel

the generation of the database.yml file is still the same, just run

% merb

from the root of the application-dir (./time_management) in this case.

The database-setup file that is generated is called

database.yml.sample

it used to be

database.sample.yml

Don't forget to rename it to rename to:

database.yml

The

./script/generate model user

is replaced with:

% merb-gen model user

The

% ./script/generate controller main

is replaced with...

% merb-gen controller main

...semantically consistent!

I don't know if it is needed, but I defined my databases by help of something like phpmyadmin.

The last problem I had was a logical one.

There is an 'end' misplaced in the main.rb example.

For me, in the end, this worked:

--------
class Main < Application

def index
render
end

def login
@error =false
uname = params.fetch(:uname)
pass = params.fetch(:pass)
user = User.filter(:user_name => uname, :password => pass)
unless @user.blank?
session[:user_id] = @user.first.id
redirect "/main/"
else
@error = true
end
if session[:user_id] != nil
@logged_in = true
@user = User.filter(:id => session[:user_id]).first
else
@logged_in = false
end
render
end

def logout
session[:user_id] = nil
redirect "/main/"
end

end
-------

Thanks for the intro, up to the second part.

Paul.

Hasham Malik said...

Thanks paul this tutorial was written with merb 0.5, I have mentioned that in my newer post. Thanks for update

Anonymous said...

Hi,

I have written a more up to date article on getting started with datamapper and merb using thor tasks to bundle everything into your application on our blog: http://blog.dynamic50.com or here: http://blog.dynamic50.com/index.php/2008/11/getting-started-with-merb-bundling-merb-with-your-application/

Hasham Malik said...

Thanks Jason! This article was written way back! but i reckon it is still only one that is about using sequel with merb