Tuesday, July 15, 2008

Install Phusion Passenger on Cent OS 5

Phusion Passenger (mod_rails/mod_rack) is an apache module that makes deployment of Ruby/Rails applications as simple as PHP applications. It does not require use of any ruby specific tools to deploy application. All you have to do is copy your source files in appropriate directories on server and your code changes will be deployed. Main advantage of passenger is it allows to deploy rails application reliably on shared hosting environment. Passenger is not available for windows. 

Lets see how to install Passenger on Cent OS. Cent OS 5.1 comes with Apache 2.2.3 installed. First of all make sure Ruby, Gems, Rails and ruby development headers is installed on the system, Issue following commands as root: 

yum install ruby
yum install irb
yum install rdoc
yum install ruby-devel
yum install rubygems
Now install rails gems:

gem install rails -y

Also install Apache development header files.

yum install httpd-devel
Now we have all prerequisites covered. Lets proceed with installation of Passenger gem.

gem install passenger
After installing passenger and its dependencies make sure that Apache is stopped, launch passenger installer for Apache module from command line.

passenger-install-apache2-module

The command line based installer is pretty good it will check all dependencies and inform you if any dependency is missing. After the module is installed. create a rails application in /var/www/htdocs folder.

rails demo
Now open httpd.conf file in /etc/httpd/conf folder. Add following lines in this file.

LoadModule passenger_module /usr/lib/ruby/gems/1.8/gems/passenger-2.0.1/ext/apache2/mod_passenger.so
PassengerRoot /usr/lib/ruby/gems/1.8/gems/passenger-2.0.1
PassengerRuby /usr/bin/ruby

These paths could be different for your system. Now lets configure virtual host for rails application at bottom of httpd.conf. Add these lines at bottom of file:

<VirtualHost *:80>
      ServerName www.demo.com
      DocumentRoot /var/www/html/myapp/public
</VirtualHost>
Make sure DocumentRoot points to public directory of your rails application. Also add server name alias to hosts file in /etc/ folder. Now start apache server from console.

service httpd start
Your new rails application should be running now with Phusion Passenger.

Sunday, March 23, 2008

Radiant CMS 0.6 has extension now


Radiant is most promising content management system to come out from fast growing Ruby on Rails community. The Radiant site advertises it as no fluff cms intended for small teams.

Radiant is fairly simple to install as gem and has structure common to all Ruby on Rails applications. No fluff means that there is no layers of code hiding core cms code and whole application code is simple to understand and change in true open source way.

So what is keeping Radiant from replacing Joomla or Drupal as most popular open source cms out there. In my opinion at the moment the Ruby on Rails community is small (even when it is growing at stellar pace), let alone developer community around Radiant

The reason for popularity of Joomla and similar PHP open source CMS is fact that they have been around for quite some time now. There is significant developer community around these projects which have been developing and extending these CMS. There is very large number of extensions available for Joomla allowing people to quickly mash up web applications into core cms.

So most important thing for Radiant to be adopted by more teams especially ones outside Ruby on Rails community is to have popular extension mechanism and number of extensions available to extend core cms. Release 0.6 comes with extension mechanism which appears to be fairly simple and there are some extensions available as well. Lets wait and see how many members of rails community contribute extensions to this project and will it be able to become leading open source cms as Joomla

Monday, March 17, 2008

Getting started with Merb and Sequel Part 2

Continuing from my last post. My previous post is based on merb 0.5, but since then newer merb 0.9.1 is available from merbivore. There has been several changes in this release from previous version.
Ok! Now lets add another model to our application to track user status. Type this command from your application root
% merb-gen model status
This will create model named status.rb in app/models directory as well as migration file named 002_add_model_statuses.rb, Go on and edit this file to create the statuses table.
class AddModelStatuses < Sequel::Migration
def up create_table :statuses do |u|
primary_key :id
integer :user_id
varchar :status, :size => 100
text :note
datetime :time_at
end
end

def down
execute "DROP TABLE statuses"
end

end
Now that we have status table setup lets manage the user status restfully. Lets create a controller for REST enabled actions.
% merb-gen controller status
This will create a new contoller now add four actions to allow for REST protocol.
class Statuses < Application

# GET /statuses
# GET /statuses.xml
def index
@statuses = Status.filter('user_id = ?', session[:user_id])
end

# GET /statuses/1
# GET /statuses/1.xml
def show
@status = Status.filter('id = ?', params[:id])
end

# GET /statuses/new
def new

end

# GET /statuses/1;edit
def edit

end

# POST /statuses
# POST /statuses.xml
def create
Status.insert(:user_id => session[:user_id], :status => params["select_status"], :note => params["status_note"], :time_at => Time.now)
end

# PUT /statuses/1
# PUT /statuses/1.xml
def update
Status.filter('id = ?', params[:id]).update(:status => params["select_status"])
end

# DELETE /statuses/1
# DELETE /statuses/1.xml
def destroy
Status.filter(:id => params[:id]).delete
end

end
Now that we have this in controller, lets setup router.rb to use this controller restfully, Add thi s line to router.rb
r.resources :statuses
Now you can call the the statuses controller restfully from anywhere. Check out Ezra's post on Restful routes

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 ....

Tuesday, February 26, 2008

Getting TinyMCE 3.0 Spellchecker to work with Rails

In new version of TinyMCE editor there are many changes in plug ins. The Plug in code is changed. The popular spell checker plug in now uses JSON as transport mechanism instead of XML. In my example we are using Aspell to check spellings, so you must have Aspell installed on your system for this example to work

Issue this command on CLI to check if Aspell is installed:

% aspell


You should see help output related to command

First of all you need to install JSON gem to parse JSON requests

% sudo gem install json


Then write this action in a controller:

require json

def spellcheck
raw = request.env['RAW_POST_DATA']
req = JSON.parse(raw)
lang = req["params"][0]
if req["method"] == 'checkWords'
text_to_check = req["params"][1].join(" ")
else
text_to_check = req["params"][1]
end
suggestions = check_spelling_new(text_to_check, req["method"], lang)
render :json => {"id" => nil, "result" => suggestions, "error" => nil}.to_json
return
end


Now also write this method in private section of controller:

def check_spelling_new(spell_check_text, command, lang)
json_response_values = Array.new
spell_check_response = `echo "#{spell_check_text}" | aspell -a -l #{lang}`
if (spell_check_response != '')
spelling_errors = spell_check_response.split(' ').slice(1..-1)
if (command == 'checkWords')
i = 0
while i < spelling_errors.length
spelling_errors[i].strip!
if (spelling_errors[i].to_s.index('&') == 0)
match_data = spelling_errors[i + 1]
json_response_values << match_data
end
i += 1
end
elsif (command == 'getSuggestions')
arr = spell_check_response.split(':')
suggestion_string = arr[1]
suggestions = suggestion_string.split(',')
for suggestion in suggestions
suggestion.strip!
json_response_values << suggestion
end
end
end
return json_response_values
end


now you need to open /plugins/spellchecker/editor_plugin.js file under your Tiny MCE directory. Search for this line;

t.url = url;


and change it to:

t.url = 'http://www.yourhostname.com';


then search for this line:

var t = this, url = t.editor.getParam("spellchecker_rpc_url", this.url+'/rpc.php');


and change it to:

var t = this, url = t.editor.getParam("spellchecker_rpc_url", this.url+'/spellcheck');


and to make this work just add this route to routes.rb under config folder

map.connect '/spellcheck', :controller => 'your_controller_name', :action => 'spellcheck'
#replace your_controller_name with name of our controller in which the spellcheck action is written

Wednesday, November 7, 2007

No default PTY in Capistrano 2.1

Add this line your Capistrano scripts to work with new Capistrano 2.1 gem.

default_run_options[:pty] = true


Capistrano no longer requests a pty on each command, which means your .profile (or .bashrc etc) will be properly loaded on each command. Some commands will go into non-interactive mode automatically. If you’re not seeing commands at CLI, You can return to old behavior by adding this line to your deploy.rb

For more changes in Capistrano 2.1 
http://weblog.jamisbuck.org/2007/10/14/capistrano-2-1

Wednesday, October 24, 2007

Multiview Templates in Rails 2.0

Along with many other enhancements and changes in Rails 2.0 now there are new multi view templates. I think multi view templates are going to be most visible and important change in Rails 2.0.

What essentially has happened is that template format has been separated from  rendering engine. This allows you to parse any type of template (csv, haml, rtf etc)  with erb rendering engine. So this takes respond_to  next level by having different template format for each respond_to.

So the new format for templates is action.format.renderer (i.e. show.html.erb, show.rtf.erb etc). you can declare own mime-type aliases in the config/initializers/mime_types.rb file. This file is included by default in all new applications.

For other new features coming in rails 2.0

http://weblog.rubyonrails.org/2007/9/30/rails-2-0-0-preview-release