Thursday, 26 July 2012

How to Run a single migration file in rails

Here is the rake command to run the single migration in rails.

> rake db:migrate.up VERSION=20120402064142


Thank You,
Uma Mahesh.

Monday, 23 July 2012

configuring pushion passanger for rails app

Here are few steps that make you to configure pussion passenger with apache.

Many of the ruby on rails developer runs the application in webrick which comes as a default server with rails framework. But when you are deploying application to server we need to choose a good server as a application server. 

There are many servers that are available for rails application. Here I would like to explain about the  configuring passenger with apache. 

 

Need to install pushion passanger gem

gem install passenger
 
before that need you need to make the correct ruby version. i.e pussion passanger need to be install with appropriate ruby version of the rails application.

i.e if your rails application is using ruby 1.8.7 then.
> rvm use 1.8.7
gem install passenger

passenger-install-apache2-module


After installing, it will ask to add few lines on apache config files as below

The Apache 2 module was successfully installed.
Please edit your Apache configuration file, and add these lines:

 LoadModule passenger_module /usr/local/rvm/gems/ruby-1.8.7-p358/gems/passenger-3.0.13/ext/apache2/mod_passenger.so
 PassengerRoot /usr/local/rvm/gems/ruby-1.8.7-p358/gems/passenger-3.0.13
 PassengerRuby /usr/local/rvm/wrappers/ruby-1.8.7-p358/ruby

You need to add above lines in apache/httpd.conf file.

In my present sever it was located at 'user/local/apache/config.httpd.conf'

Need to add virtual host on the above configuration file

<VirtualHost 123.45.678:80>
  ServerName myapp.com
  DocumentRoot "/home/umamahesh/myapp/public"
  RailsEnv development
</VirtualHost>



Now you to restart the apache server. 
 
To check all the things given in httpd.conf file was correct run the below command

> /etc/init.d/httpd restart

Next restart the apache server.

Next need to restart the pushion passanger server as below

> in the application directory 
> touch tmp/restart.txt

Now your application with run with pussion passenger.


Thank You,
Uma Mahesh.

Full text search in postgres

Hi,

Here is the few things while working with full text search in postgres sql.

The first preference is by indexing the columns. The second one is by using lexema search

To implement full text search we have two functions in postgres tsvector from a document and a tsquery from a user query

PostgreSQL provides the function to_tsvector for converting a document to the tsvector data type.

SELECT to_tsvector('english', 'a man  bat rat on a doll - it took the ball');

> "'ball':11 'bat':3 'doll':7 'man':2 'rat':4 'took':9"


In the above result the tsvector does not contain a,on ..

 tsvector internally do parsing by breaking up to tokens and using some logic internally. To know more about what's tsvector actually doing please go through the postgres site

The next function tsquery:

PostgreSQL provides the functions to_tsquery for converting a query to the tsquery data type.

to_tsquery creates a tsquery value from querytext, which must consist of single tokens separated by the Boolean operators & (AND), | (OR) and ! (NOT).

 SELECT to_tsquery('english', 'The & mat & bats');
> "'mat' & 'bat'"


By using the above tow functions we can implement text search in postgres. Below is the sql query to implement it

select * from users where to_tsvector('english', description) @@ to_tsquery('english', 'good | person');


the above query will do the full text search in the description column in the user table.

Thank You,
Uma Mahesh.

Thursday, 19 July 2012

Creating new application in rails3

Creating new application in rails3

You need to install ruby and rails in your system before creating the new rails application

Run the below command to create new rails application

> rails new myapp

Here is the application directory structure that was created by rails

      create 
      create  README.rdoc
      create  Rakefile
      create  config.ru
      create  .gitignore
      create  Gemfile
      create  app
      create  app/assets/images/rails.png
      create  app/assets/javascripts/application.js
      create  app/assets/stylesheets/application.css
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/mailers
      create  app/models
      create  app/views/layouts/application.html.erb
      create  app/mailers/.gitkeep
      create  app/models/.gitkeep
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb
      create  config/environments
      create  config/environments/development.rb
      create  config/environments/production.rb
      create  config/environments/test.rb
      create  config/initializers
      create  config/initializers/backtrace_silencers.rb
      create  config/initializers/inflections.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/secret_token.rb
      create  config/initializers/session_store.rb
      create  config/initializers/wrap_parameters.rb
      create  config/locales
      create  config/locales/en.yml
      create  config/boot.rb
      create  config/database.yml
      create  db
      create  db/seeds.rb
      create  doc
      create  doc/README_FOR_APP
      create  lib
      create  lib/tasks
      create  lib/tasks/.gitkeep
      create  lib/assets
      create  lib/assets/.gitkeep
      create  log
      create  log/.gitkeep
      create  public
      create  public/404.html
      create  public/422.html
      create  public/500.html
      create  public/favicon.ico
      create  public/index.html
      create  public/robots.txt
      create  script
      create  script/rails
      create  test/fixtures
      create  test/fixtures/.gitkeep
      create  test/functional
      create  test/functional/.gitkeep
      create  test/integration
      create  test/integration/.gitkeep
      create  test/unit
      create  test/unit/.gitkeep
      create  test/performance/browsing_test.rb
      create  test/test_helper.rb
      create  tmp/cache
      create  tmp/cache/assets
      create  vendor/assets/javascripts
      create  vendor/assets/javascripts/.gitkeep
      create  vendor/assets/stylesheets
      create  vendor/assets/stylesheets/.gitkeep
      create  vendor/plugins
      create  vendor/plugins/.gitkeep
         run  bundle install
Fetching source index for https://rubygems.org/
Using rake (0.9.2.2)
Using i18n (0.6.0)
Using multi_json (1.3.6)
Using activesupport (3.2.2)
Using builder (3.0.0)
Using activemodel (3.2.2)
Using erubis (2.7.0)
Using journey (1.0.4)
Using rack (1.4.1)
Using rack-cache (1.2)
Using rack-test (0.6.1)
Using hike (1.2.1)
Using tilt (1.3.3)
Using sprockets (2.1.3)
Using actionpack (3.2.2)
Installing mime-types (1.19)
Using polyglot (0.3.3)
Using treetop (1.4.10)
Using mail (2.4.4)
Using actionmailer (3.2.2)
Using arel (3.0.2)
Using tzinfo (0.3.33)
Using activerecord (3.2.2)
Using activeresource (3.2.2)
Using bundler (1.0.22)
Using coffee-script-source (1.3.3)
Using execjs (1.4.0)
Using coffee-script (2.2.0)
Using rack-ssl (1.3.2)
Using json (1.7.3)
Using rdoc (3.12)
Using thor (0.14.6)
Using railties (3.2.2)
Using coffee-rails (3.2.2)
Using jquery-rails (2.0.2)
Using rails (3.2.2)
Installing sass (3.1.20)
Using sass-rails (3.2.5)
Using sqlite3 (1.3.6)
Installing uglifier (1.2.6)
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.


By default rails application was created with sqlite database, which is a light weight database.


Now its time to start the server and check the welcome page

Run the below command in the application directory structure.

> rails s

=> Booting WEBrick
=> Rails 3.2.2 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2012-07-19 12:16:05] INFO  WEBrick 1.3.1
[2012-07-19 12:16:05] INFO  ruby 1.9.2 (2011-07-09) [i686-linux]
[2012-07-19 12:16:05] INFO  WEBrick::HTTPServer#start: pid=27799 port=3000


Now you can browse the application with url: http://localhost:3000 to see the welocme page.


Thank You,
Uma Mahesh

Wednesday, 18 July 2012

In Ruby 1.9, blocks introduce their own scope

With the latest release of ruby 1.9, blocks introduce their own scope. Below is the example.


x = 1

10.times do |u; x|

x =u
p "value of x - #{x}"

end

p "value of x - #{x}"


In the above case, x is treated as a local variable and we are assigning value of u to x in the loop.


Thank You,

Tuesday, 17 July 2012

no block given (yield) (LocalJumpError)

This error will occur when working with blocks.

When you used the 'yield' statement inside the method and didn't pass block as parameter then it will raise the 'no block given (yield) (LocalJumpError)' error.

def my_method
yield
end

puts my_method

In the above method call we are not passing parameter as a block so it will throw '(LocalJumpError) error'.

Here is the correct way to pass block as a parameter


def my_method
yield
end

puts my_method{puts 'Hi Uma Mahesh'}


Thank You,
Uma Mahesh.

paperclip image validation

Hi,

I am using paperclip gem  for image uploading in rails application.

In my application I have made photo model to work with polymorphic association  i.e to store photos related content in single table to make application look clean.

So I have associated in user model as below

Class User << ActiveRecord

has_many :photos, :as => :photoable, :dependent => :destroy

end

In photo model

class Photo < ActiveRecord::Base
  belongs_to :photoable, :polymorphic => true

  validates_attachment_presence :image
  validates_attachment_size :image, :less_than => 5.megabyte
  validates_attachment_content_type :image, :content_type => ['image/jpeg', 'image/png', 'image/gif']

end

I have faced issue at a satuation where I need to have photo field and it should validate only when there was image uploaded. Due to present validations its trowing validation error's while saving the user data.

I have solved the above issue by adding conditional validations in photo model as below

 validates_attachment_presence :image, :if => lambda { |images| !images.image_file_name.nil?}


The above validation will be invoked only when image was uploaded.


Thank You,
Uma Mahesh.

Tuesday, 3 July 2012

mongodb tutorial

MongoDB is an open source, high-performance, open source NoSQL database.

Compared to relational DBMS, Mongodb is quite different. In MongoDB you store JSON-like documents with dynamic schemas.


Install mongodb depending on the OS you are working on.

Here is the link where you can download them

http://www.mongodb.org/display/DOCS/Quickstart

I have Installed mongodb directly from ubuntu software center.

after installation restart the mongo server

> sudo service mongodb start

You may prompted with "start: Job is already running: mongodb". This means mongo server was already running.

run the below command to connect to mongodb

> mongo

MongoDB shell version: 1.8.2
Tue Jul  3 12:41:59 *** warning: spider monkey build without utf8 support.  consider rebuilding with utf8 support
connecting to: test

In the above case mongodb by default connect to test database.

lets now create your first record as below

> db.test.save({a: 1})

The above command will create record in database. To view the record just run the find statement as below

> db.test.find({a: 1})
{ "_id" : ObjectId("4ff29c16ab6b02ddb38d978a"), "a" : 1 }


create second record by adding another column parameter

> db.test.save({b: 1, name: 'uma mahesh'})

to view the record

> db.test.find({b: 1})
{ "_id" : ObjectId("4ff29c41ab6b02ddb38d978b"), "b" : 1, "name" : "uma mahesh" }


to find all the records that were created, just run the below command

> db.test.find()

{ "_id" : ObjectId("4ff29c16ab6b02ddb38d978a"), "a" : 1 }
{ "_id" : ObjectId("4ff29c41ab6b02ddb38d978b"), "b" : 1, "name" : "uma mahesh" }


To view list of all databases in mongodb, run the below command

> show dbs

Thsi will display list of databases as below

admin    (empty)
local    (empty)
test    0.0625GB




Thank You,
Uma Mahesh.

Sunday, 1 July 2012

remove trailing whitespace before git commit

Hi,

Trailing whitespace always makes noises in version control system. We should remove trailing whitespace to avoid annoying other team members.

While working with remote developers we should follow some coding standarts and should form a habit to remove trailing whitespace before committing.


We can do it by git pre commit hook or deleting trailing whitespace by our own.

I hope all the IDE will support the code re-factoring. I am using rubymine and I used to refactotr code as below.

In rubymine

> On the main menu, choose Code | Reformat Code, or press Ctrl+Alt+L.

> In the Reformat Code dialogue box, specify the reformatting scope:
The current file.
Selected text.
All files in the current directory, including or omitting subdirectories.

> Click Run.


Thank You,
Uma Mahesh.