Thursday, February 10, 2011

Setup Ruby on Rails 3 for development on Ubuntu 10.10 aka Maverick Meerkat

Installation on Ruby on Rails 3 on Ubuntu 10.10 is really easy peasy, However Ruby doesn't come pre-installed on Ubuntu like Python and Perl. To start of with installation of development tools for Rails we first need to install basic build tools like Compilers collection etc. There is handy packaged pre-built for that in Canonical repositories:

Assuming you want to use My SQL server with Rails next we would need to setup Ruby, My SQL Server and Client as well as some other essential tools:

Now that Ruby and My SQL is setup We need to pull the latest version of Rubygems at run setup as a super user:

In case you want to Sqlite 3 as development database with Rails 3 you may want to install that as well:

As a last step install latest version on Ruby on Rails framework gems:

Now Ruby on Rails 3 is setup on your machine you can proceed with creating a new project and pulling in all the dependencies with bundler.

Monday, January 18, 2010

Testing ActiveResource classes with Fakeweb and Shoulda

It is not as simple to write unit tests for Active Resource models as they often depend on external web service. It is not mostly possible to get or create a Sandbox web service for unit testing your Active Resource classes. In such scenario you need a way to mock how the RESTful web service would behave in production.

I initially tried to use HttpMock which is used to test Active Resource framework within Rails. It is undocumented and you need to dig through web and Rails documentation it self to see how it works. Recently I came across excellent FakeWeb gem and ever since that I have been hooked on it. I am impressed by simplicity with which we I can mock RESTFul Rails web services.

Here is how I use Test::Unit and Shoulda with Rails to Mock RESTful web services for Active Resource classes. I am using XML based web services so I needed sample XML responses that Mock service should return. I create XML files containing those sample responses and store them under test/fixtures folder. After that I edited test_helper.rb file in test folder to have this utility method which loads sample responses from XML files located in fixtures folder.



After this lets jump on to unit test that we are going to write for our Active Resource class. Lets say we are testing an Active Resource class named User. Here is how I write unit test with FakeWeb and Shoulda gem.



First I am requiring both FakeWeb and Shoulda a gem. I would also add these gems to config/environments/test.rb as required gem for test environment.



After requiring these two gems I would disable real HTTP connections so not to mix real Web services calls with mock RESTful Web services by setting allow_net_connect property of FakeWeb class to false. Similarly in teardown method I would re-enable net HTTP connections by setting allow_net_connect property to true.

Now I am going to write actual test using FakeWeb within Shoulda context blocks.



Here within the context block I am setting up url to register as GET request to return response that is contained in XML file. After that a simple test checks the returned response object with some assertions. This shows how easy it is to create mock RESTful web services with FakeWeb and test your Active Resource classes with RSpec or  Test::Unit

Thursday, October 1, 2009

Using Questions Answers Foo Plugin to add Q&A to your Rails app

Questions Answers plugin adds linkedin like Questions and Answers functionality to your
Rails application. Plugin assumes existance of model named User and that model
contains information about users of system. If User model does not exist the
plugin will print warning message on console at startup. If you dont already
have authentication user model i recommend you install restful_authentication
plugin.

The plugin uses login attribute of user model in views by default. You can
change that default by declaring this constant in your environment.rb file


VIEW_QA_USER_ATTRIBUTE = "full_name"


To change look of the module change the css refrenced in
ui/views/layouts/qa.html.erb

Install this plugin in your rails application by running


./script/plugin install git://github.com/hasham2/questions_answers_foo.git


To complete installation of plugin run following rake task from root directory
of your application.


rake questions_answers:install


This will create database migration to hold Questions and Answers data. After
running this task run:


rake db:migrate


to commit changes to database structure.

Monday, May 11, 2009

Deploying rails applications with vlad

Vlad is application deployment automation tool much like Capistrano but with much less complexity and it integrates right into rake. so no need to capify your project again. Vlad is based on standard nix tools like ssh and rsync .

To make it even better is that it comes with built in support for number of version control systems like Darcs, Subversion, Mercurial and best of all Git. To get started you need to install vlad gem on your machine and on each of servers you wish to deploy your ruby app.

sudo gem install vlad


The variables for deployment are typically setup in config/deploy.rb file just like capistrano. For trival one server deployment all you have to do is set four vaiables in deploy.rb file


set :application, "myblog"
set :domain, "blog.com"
set :deploy_to, "/var/rails/myblog"
set :repository", "http://svn.myserver.com/myblog/trunk"


Also add following lines to Rakefile as well to require vlad gem


Begin
require 'vlad'
Vlad.load
rescue LoadError
#do nothing
end


Just run following commands in this sequence to deploy your application


vlad:setup #run first time only
vlad:update
vlad:migrate #optional
vlad:start


As you might be aware Capistrano is not going to be maintained anymore by Jamis buck and there is lot of active development going on for vlad it should be good idea to give vlad a spin as alternative to capistrano.

DHH speaks of 5 years of ruby on rails and rails 3

DHH's keynote on Railsconf 2009 speaks about five years of ruby on rails. Rails 3 and secret of high productivity.

Tuesday, March 10, 2009

using multiple contexts block in test case with shoulda

Test::Unit which is a default unit testing framework with rails. It has only one context for each test case class. If we can have more than one context per class than it could reduce number of files and classes that we are required to make to test cases in multiple contexts.


Answer to this issue is support for multiple contexts in Shoulda. Shoulda is rspec like testing framework built upon Test::Unit. Shoulda allows you to have multiple context with thier own setup and teardown methods. For example see this context block in a test case




class UserTest < Test::Unit::TestCase
context "with user" do
setup do
@user = User.create(:login => "john", :password => "secret" )
end

should "be able to authenticate" do
assert User.authenticate("john", "secret")
end

should "return authenticated user" do
assert_equal @user, User.authenticate("john", "secret")
end
end
end


For more details on shoulda testing framework take a look at official rails wiki page

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

Saturday, August 18, 2007

Using .Net SOAP Services with wsdl2ruby

Easist way to use SOAP service in pure ruby is with wsdl2ruby. Simplest code would be to:


require 'soap/wsdlDriver'
wsdl = 'http://www.dotnetsite.com/MyService/Service.asmx?WSDL
driver = SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
puts driver.GetVals(:parameter => SOAP::SOAPInt.new(136))


Where GetVals is .Net web method to call. Generating stub files with wsdl2ruby.rb against a WSDL could what arguments you should pass.


% wsdl2ruby.rb --wsdl Foo.wsdl --type client --force


I would like to thank Hiroshi NAKAMURA for this last information

Wednesday, July 4, 2007

Using Gravatar plugin to embed avatars in rails views

Gravatar offers service to keep your globally recognizable avatars (gravatar). This tiny plugin offers rails view helper to embed gravatars in your views. It can also be used in blog, forums applications to insert gravatar to be visible instead of email. Here is how to install it:

$ ruby script/plugin install http://tools.assembla.com/svn/hasham/plugins/gravatar_tag


Here is sample usage in an erb template:

<%= gravatar_tag "user@domain.com", :size => "60x60"%>


The first parameter which is a email that user signed up with on gravatar.com is required. The other parameters are same as rails image_tag view helper.

Monday, July 2, 2007

SVN Cache made simple with Capistrano 2

You normally don't want to do complete checkout of your source control on every deployment with Capistrano. The SVN cache keeps copy of source code on server in separate directory on each deploy this copy of source code is updated and deployed to releases directory.

Implementing this kind of SVN cache is super simple in Capistrano 2, Just set deploy_via variable to remote_cache like this:

set :deploy_via, :remote_cache

Sunday, July 1, 2007

Mongrel is multi threaded, but rails is not thread safe

The main reason why we need to run multiple mongrel instances (pack of mongrels) for any high traffic website is that Ruby on Rails code is not thread safe. This is not the case with other Ruby frameworks like Camping, Merb and Og + Nitro. There is a synchronized block around the calls to Dispatcher.dispatch (in dispatch.rb) rest is multithreaded. so to get any sort of concurrency in serving request we need to run multiple mongrel instances.

In my experience 128 MB RAM is required to run single instance of mongrel server. which means you should not run more than 8 mongrels on your 1 GB RAM VPS. If the rails could be thread safe it would require lot less server resources to deploy rails with mongrels.

Thursday, June 28, 2007

Ignoring common exceptions in exception_notification plugin

Exception Notification is a great plugin, that helps to you to get trace of exception on your app running in production mode. Without this plugin you probably would have to SSH to production machine and tail the production.log file to get last exception trace which is extremely inconvenient to do. FTP to get to production.log is also an option but production.log files tend to become too large. only problem is that you may get too many emails form this plugin especially when you have just launched your site in production mode.

some of the exception are not too much intresting like typical ActiveRecord::RecordNotFound exceptions, To ignore these kind of trivial exceptions you must overide it in rescue_action_in_public method of your application.rb file.

Here is how you do it:



def rescue_action_in_public(exception)
case exception
when ::ActiveRecord::RecordNotFound,
::ActionController::UnknownController,
::ActionController::UnknownAction,
::ActionController::RoutingError
render_404
else
render_500
deliverer = self.class.exception_data
data = case deliverer
when nil then {}
when Symbol then send(deliverer)
when Proc then deliverer.call(self)
end
ExceptionNotifier.deliver_exception_notification(exception, self, request, data)
end
end

Sunday, June 24, 2007

Capistrano 2 and custom SCM modules

I was using Capistrano 2 to deploy our latest project, as we had our SVN repository behind the corporate firewall and was not accessible remotely. I had originally planned to use a custom SCM module for local svn access.

I discovered that custom SCM modules are not supported at the moment in Capistrano 2.

If there are any workarounds i would be interested to know about them

Friday, March 16, 2007

STI vs. Polymorphic association

This is a common to have join between two tables based on condition. suppose we have table in database called comments and we can have comments on different thing like a video, profile or picture. So keeping DRY (Don’t repeat yourself) principle in mind while designing your database. You may want to have relationship between single comments table and videos or profiles table.

At database level you should have two fields in table one field (i.e. type) that identifies the type of comment whether it is a comment on video or it’s a comment on profile, and another field (i.e source_id) that contains id of the video or profile that comment was on.

In Ruby on Rails currently there are two ways to define this kind of association between your activerecord models:

Single Table Inheritance:

Here you ‘ll create a single table of comments and Comment AR class, there would be two additional classes ProfileComment and VideoComment inheriting from same Comment AR class. Instead of having association between Profile and Comment model there would be association between Profile and ProfileComment subclass. Same will be the case with Video model and VideoComment subclass.

If we take a look at comment table we ‘ll see that class name for each record will be automatically stored in type field. The reference to associated table would be in source_id field.


class Comment < ActiveRecord::Base
end
class VideoComment < Comment
belongs_to :video, :foreign_key => “source_id”
end
class ProfileComment < Comment
belongs_to :profile, :foreign_key => “source_id”
end


Polymorphic Association:

Since Rails 1.1 there is a simpler way to create this kind of relationship called polymorphic association. In case of polymorphic association you ‘ll have two fields called commentable_type and commentable_id, instead of type and source_id. The commentable_type field will store name of class which that instance relates to and commentable_id saves the reference to instance of that class. The relations will be created like this:


class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
class Video < ActiveRecord::Base
has_many :comments, :as => :commentable
end
class Profile < ActiveRecord::Base
has_many :comments, :as => :commentable
end

Pros and Cons:

  • The STI approach offers more flexibilty by allowing you to have additional fields that only have value in case of one sub class. For access from other sub class can be disallowed be overridden accessors.
  • The STI requires you to create a seperate class to implement a relation between two models, resulting in more classses. which is not case with polymorphic association
  • The STI results in more code.It is confusing to some programmers to understand relation between STI classes
  • The polymorphic association is very easy to implement.