Wednesday, 28 November 2012

Guest user functionality in rails app

Hi,

In many requirements you may be asked to provide guest user functionality in application. Here are the simple steps to make that functionality simple.


rails g migration add_guest_to_users guest:boolean
rake db:migrate


index.html.erb
<p><%= button_to "Guest User!", users_path, method: :post %></p>



layouts/application.html.erb
Logged in as <strong><%= current_user.name %></strong>.
<% if current_user.guest? %>
  <%= link_to "Become a member", signup_path %>
<% else %>
  <%= link_to "Log Out", logout_path %>
<% end %>


user_controller.rb
def create
  @user = params[:user] ? User.new(params[:user]) : User.new_guest
  if @user.save
    current_user.move_to(@user) if current_user && current_user.guest?
    session[:user_id] = @user.id
    redirect_to root_url
  else
    render "new"
  end
end


models/user.rb
class User < ActiveRecord::Base
  has_many :tasks, dependent: :destroy

  attr_accessible :username, :email, :password, :password_confirmation

  validates_presence_of :username, :email, :password_digest, unless: :guest?
  validates_uniqueness_of :username, allow_blank: true
  validates_confirmation_of :password

  # override has_secure_password to customize validation until Rails 4.
  require 'bcrypt'
  attr_reader :password
  include ActiveModel::SecurePassword::InstanceMethodsOnActivation
 
  def self.new_guest
    new { |u| u.guest = true }
  end
 
  def name
    guest ? "Guest" : username
  end
 
  def move_to(user)
    tasks.update_all(user_id: user.id)
  end
end


lib/tasks/guests.rake
namespace :guests do
  desc "Remove guest accounts more than a week old."
  task :cleanup => :environment do
    User.where(guest: true).where("created_at < ?", 1.week.ago).destroy_all
  end
end


By applying above simple steps you can add guest user functionality in existing rails application easily .

Thank You,
Uma Mahesh.

ruby 1.9.3 perfomance

Hi,

Recently I have read article about ruby performance issue compared to ruby 1.9.2 and ruby 1.9.3 and came to see few important points that need to be noted. Below is the discussion.

We just switched a site from Apache + ruby 1.9.2 to nginx + ruby 1.9.3 a few days ago and I noticed that somehow the site speed has noticably dropped on the ruby side of things and I just couldn’t understand why.

/opt/nginx/logs# rvm use 1.9.3
Using /usr/local/rvm/gems/ruby-1.9.3-p327
/opt/nginx/logs# time ruby -e "count = 0; while(count < 100000000); count = count + 1; end; puts count"
100000000
real 0m7.655s
user 0m7.632s
sys 0m0.012s
/opt/nginx/logs# rvm use 1.9.2
Using /usr/local/rvm/gems/ruby-1.9.2-p320
/opt/nginx/logs# time ruby -e "count = 0; while(count < 100000000); count = count + 1; end; puts count"
100000000
real 0m4.716s
user 0m4.716s
sys 0m0.000s
Checking make.log showed that 1.9.3 was indeed compiled w/o any optimizations. After I hand-compiled a 1.9.3, I got this:

/opt/ruby193opt/bin# ./ruby -v
ruby 1.9.3p327 (2012-11-10 revision 37606) [x86_64-linux]
/opt/ruby193opt/bin# time ./ruby -e "count = 0; while(count < 100000000); count = count + 1; end; puts count"
100000000
real 0m4.641s
user 0m4.628s
sys 0m0.008s
/opt/ruby193opt/bin# ruby -v
ruby 1.9.2p320 (2012-04-20 revision 35421) [x86_64-linux]
puck352:/opt/ruby193opt/bin# time ruby -e "count = 0; while(count < 100000000); count = count + 1; end; puts count"
100000000
real 0m4.634s
user 0m4.624s
sys 0m0.012s
Now it performs on par with 1.9.2
 Thank You,
Uma Mahesh.



Thursday, 1 November 2012

ActiveRecord::RecordNotUnique (PG::Error: ERROR: duplicate key value violates unique constraint

ActiveRecord::RecordNotUnique (PG::Error: ERROR:  duplicate key value violates unique constraint

ActiveRecord::RecordNotUnique: PG::Error: ERROR: duplicate key value violates unique constraint "users_pkey" DETAIL: Key (id)=(143) already exists.

The above issue will raise when you dump data to database and start creating records after that. You need to set the sequence value manually to over come this issue. Below is the command to set the value for 'users_id_seq'


SELECT setval('users_id_seq', (SELECT max(id) FROM users));

In the above query 'users' is the tale and you are manually changing the 'users_id_seq' value to max(id) of users.


Thank You,
Uma Mahesh.

Tuesday, 30 October 2012

free publicly facing url

Hi,

tunnlr provides you public interface url for your web application to access any where which was running in local machine.

If you're running your server locally and have no publicly facing endpoint, you can use a service like tunnlr to create one. This creates a publicly accessible URL with an SSH tunnel back to your local machine.


Website: http://tunnlr.com/

Create account in tunnlr and get a public url for you.


In order to use tunnlr in our rails application we have a gem 'tunnlr_connector'(A plugin for interacting with tunnlr on both unix and windows. Uses the net::ssh gem)

Add gem to your gem file.

gem 'tunnlr_connector', :require => "tunnlr"


run 'bundle install' to install the gems

Now you need to configure local system to tunnlr account. This can be done by running the below command.

rake tunnlr:configure

and enter the email address and password associated with your tunnlr account.

To create a tunnel, run

rake tunnlr:start

The above command will run tunnel server in local machine. You can browse the application with url: http://web1.tunnlr.com:12606/





Thank You,
Uma Mahesh.

Monday, 22 October 2012

Git config commands



Below is the list of git global configuration commands

> git config -l

The above command will display complete configuration for the present git login as how below

user.name=Uma Mahesh
user.email=umamaheshvarma@gmail.com
core.repositoryformatversion=0
core.filemode=true
core.bare=false
core.logallrefupdates=true
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
remote.origin.url=git@heroku.com:umamahesh.git
branch.master.remote=origin
branch.master.merge=refs/heads/master





You can change the above configuration with the below commands,



git config --global user.email "
umamaheshvarma.seeram@gmail.com"
git config --global user.name "uma"







Thank You,
Uma Mahesh.



Thursday, 13 September 2012

Generating barcode in ruby on rails

Hi,

In ruby we can generate bar code easily with nice wrapper using barby.


BARBY - The Ruby barcode generator. To know more about barby check the http://toretore.eu/barby/


Here are the simple ruby program to generate barcode in ruby file.

require 'barby'
require 'barby/barcode/code_128'
require 'barby/outputter/png_outputter'

barcode = Barby::Code128B.new('The noise of mankind has become too much')
File.open('code128b.png', 'w'){|f|
  f.write barcode.to_png(:height => 20, :margin => 5)
}



Below is the stepwise instructions to implement barcode in rails application.


Add the below gems to your gem file.


gem 'barby'
gem "has_barcode"


Add the below code to your model to which you would like to generate barcode

class Product < ActiveRecord::Base
  include HasBarcode

  has_barcode :barcode,
    :outputter => :svg,
    :type => :code_39,
    :value => Proc.new { |p| "#{p.id}" }

end



Display the barcode in your view as below

<%= @product.barcode_data.html_safe  %>


By using above simple steps you can generate barcode in rails application.

Thank You,
Uma Mahesh.

Tuesday, 11 September 2012

create anonymous user in devise

Hi,

I need to craeet the anonymous/guest user at some satuations and it was required to have email as the mandatory column in the DB. I have used the below process for creating the email on fly to make it more unique.

def create_anonymous_user
u = User.new(email: "guest_#{Time.now.to_i}#{rand(99)}
@example.com")
u.confirmed_at = Time.now
u.save(:validate => false, :confirm => false)
u
end



I hope this make the user record creation by eliminating all required validations and making the email unique.

Thank You,
Uma Mahesh.

generating pdf in rails application

Hi,

Recently for one of the requirement in my project I was supposed to create the pdf report in the rails application. I have made some research and found the "wicked_pdf" is one of the best gem available in rails.

wicked_pdf makes the life easy for pdf file generation directly from HTML page.

Wicked PDF uses the shell utility wkhtmltopdf to serve a PDF file to a user from HTML.

Wicked PDF works on Ruby 1.8.7 and 1.9.2; Rails 2 and Rails 3.

In order to use the wicked_pdf you need to install wkhtmltopdf from http://code.google.com/p/wkhtmltopdf/


next add this to your Gemfile

gem 'wicked_pdf'

You can get the gem from : https://github.com/umamahesh/wicked_pdf

In your controller:

class HomeController < ApplicationController
  def get_pdf
    respond_to do |format|
      format.html
      format.pdf do
        render :pdf => "pdf_file"
      end
    end
  end
end



There are buch of options avilable to make the pdf file look and feel nicely. You can have the clear information at https://github.com/umamahesh/wicked_pdf



Use it and let me know your comments on this gem.

One more things, if you are going to deploy application in heroku then this gem will not be usefull as heroku will not provide the option to install the wkhtmltopdf :(


You may need to use prawn gem for that.



Thank You,
Uma Mahesh.
 

Sunday, 9 September 2012

Adding ssl for active admin

Hi,

I would like to provide complete admin section with ssl, which provides high level of security for the admin section. I am using active admin for my application. I have searched for available options and finally I have found a perfect match for my requirement. gem 'rack-ssl-enforcer' provides the required functionality for us.

gem 'rack-ssl-enforcer'

add the gem to your gem file and run the command 'bundle install' to install the gem.

You need to add the required configurations settings to make the admin section work with ssl.

Add the below line in the config/application.rb

config.middleware.use Rack::SslEnforcer, :only => %r{^/admin/}

Points to be observed from the above line.

1) We are adding 'Rack::SslEnforcer' as a middleware.
2) We are adding rule based ssl.

The above configuration will make the middleware to force the ssl for the constraint that was passed as condition to it. So it will aforce ssl to be applied for admin section.

To me about the gem 'rack-ssl-enforcer', go through the complete section of github URL: https://github.com/umamahesh/rack-ssl-enforcer

Thank You,
Uma Mahesh.

Friday, 7 September 2012

memory management in ruby

In Ruby memory management is done by Garbage collector. In Ruby every thing is stored in heap memory. So in ruby memory allocation and freezing of memory will be done automatically.




As ruby is dynamic datatype, the default datatype will be taken as string and once the value was assigned to variable, depending on the datatype the memory will be allocated and remaining memory will be deleted in the heap. So it is not required to release the allocated memory by programmer as every thing will be taken care by the garbage collector.

Below is the URL, you can view the clear explanation of how the memory allocation and how garbage collector freed memory is ruby,

URL: http://patshaughnessy.net/2012/3/23/why-you-should-be-excited-about-garbage-collection-in-ruby-2-0

Question:
Q) Does ruby uses stack for memory allocation?
A) Here is the complete explanation of how memory management takes places was explained clearly on bases of ruby version wise.
URL: http://www.engineyard.com/blog/2010/mri-memory-allocation-a-primer-for-developers/

Thank You,
Uma Mahesh.

Wednesday, 5 September 2012

learn git in 15 minutes

Hi,

If you are new to git and git commands you can learn the git easily with try.github.com.

 



It provides a very good interface where you can type git commands and can learn the git easily.

I hope you know the advantage of git and how the web world is knocking it. So lets start learning git today.

URL: http://try.github.com/

Thank You,
Uma Mahesh.

Monday, 3 September 2012

calling an ApplicationController method from console

Hi,

Recently I had a issue with one of the thing and I was supposed to debug it by calling an ApplicationController method from console. Below is the way of doing it.


> object_for_application = ActionController::Base::ApplicationController.new

> object_for_application.my_method


Thank You,
Uma Mahesh.

awesome_print : Ruby printer object

Hi,

awesome_print is the ruby tool to print ruby object with the useful and clear information.

We use 'p' and object.inspect to view the complete object parameters like non-persistent attributes. By using the new 'awesome_print' you can view the complete attributes clearly.

> gem "awesome_print"

In your controller method
> @event = Event.find(params[:id])
> ap @event

 In your console

>   :id => 65,
      :title => "XXXXXXXXXXXXXXXX",
      :description => "XXXXXXXXXXXXXXXXXXXXXXXXXXX",
      :price => 132.0,
      :created_at => XXXXXXXXXXXXXXXXXXXXXXX,
      :updated_at => XXXXXXXXXXXXXXXXXXXXXXX,
      :permalink => "XXXXX".

This will help us on debugging the code.

Thank You,
Uma Mahesh.




Metaprogramming in ruby

Hi, 



creating code at runtime that defines new methods. In fact, in a sense all Ruby programming is metaprogramming, since even a class definition is not a declaration as it is in Java but actually code that is executed at runtime. Given that this is true, you might wonder whether you can modify a class at runtime. In fact you can, by adding or changing instance methods or class methods, even for Ruby’s built-in classes.


It is a basic feature of Ruby that you can re-open a class definition 
and add or redefine methods.


Thank You,
Uma Mahesh 

Sunday, 26 August 2012

Active admin relationships between models

I have used active admin for my rails application admin section.

I have 2 tables products and category.

Product class

belongs_to :category


Category class

has_many :products



I have created two resources for the above two models in admin folder. Every thing went well and for both the resources its displaying the list view perfectly.

When I try to create the product from product new screen its displaying the categories options as list of all categories objects and not the categories records.

I have made some goggling and came to find solution that we need add the below method in my category class to display the category names in the drop down to choose while creating the product.


In my category class

  def to_s
    category_name
  end


Thank You,
Uma Mahesh.

generating active admin controller

Hi,

Active admin provides a good admin interface. Inorder to generate a controller in active admin you need to run the below command

> rails g active_admin:resource User

The actual notation that should be used for active for a model is 'resource'. By running the above command you will create a resource for user class.

We need to refer the active admin classes as resource for model class.

Thank You,
Uma Mahesh.

Wednesday, 22 August 2012

Engine Yard Has Steped forward by adding Node.js support

Hi,


Enine Yard is one of the top most PAAS providers in the Cloud environment. Presently Ruby On Rails and PHP are playing around at Engine Yrad. Now Engine has added Node.js to its Support and This will help startups to build application fastly.

With the addition of Node.js to the Engine Yard Cloud supported frameworks, developers can deploy highly scalable and concurrent systems.

You can start deploying Node.js application into Engine yard and let share your views.

Thank You,
Uma Mahesh.

Custamize active admin find_by request instead of ID

Hi,

I have a requirement, where I need to find the record with find_by_name in active admin. But by default active admin finds the records with id. After googling I came to see this can be done by using before_filter as below

ActiveAdmin.register Product do
    before_filter :only => [:show, :edit, :update, :destroy] do
        @product = Product.find_by_name(params[:id])
      end
end

Thank You,
Uma Mahesh.

Agent admitted failure to sign using the key. Permission denied (publickey).

Hi,

solution : ssh-add ~/.ssh/id_rsa


I have faced the below error while cloning the code from github. I have added my keys to heroku and every thing went good. But I am facing the below error

Agent admitted failure to sign using the key. Permission denied (publickey).

Cloning into master...
Agent admitted failure to sign using the key.
Permission denied (publickey).
fatal: The remote end hung up unexpectedly


Finally after google I found the solution as below

> ssh-add ~/.ssh/id_rsa

I have ran the above command and works for me.


Thank You,
Uma Mahesh.

Thursday, 16 August 2012

PG ERROR While creating GIN Index

Hi,

I am getting below error while creating GIN Index in rails through migration

rake aborted!
An error has occurred, this and all later migrations cancelled:

PG::Error: ERROR:  data type text has no default operator class for access method "gin"
HINT:  You must specify an operator class for the index or define a default operator class for the data type.
: CREATE INDEX discussions_gin_question ON discussions USING GIN(question)

Tasks: TOP => db:migrate
(See full trace by running task with --trace)


After goggling I came to see its due to not making that column as to_tsvector

I have changed my migration to execute as below

CREATE INDEX products_gin_question ON products USING GIN(to_tsvector('english', question))


Thank You,
Uma Mahesh.

Creating GIN Index for database columns in rails Migration.


Hi,

Indexing the database columns plays an important role in database query optimisation. Indexing also increases the application performance.

While working with full text search, I recommend to use the GIN Index. It will speed-up the full-text search.


GIN (Generalised Inverted Index)-based index. While creating Column as GIN Index we need to make that column as tsvector type.

Here is the full stack view of GIN Index : http://www.postgresql.org/docs/8.3/static/textsearch-indexes.html


Coming rails migration we can create GIN Index by simple commands as below

Create migration file:

> rails g migration add_ginindex_products

class AddGinindexProductions < ActiveRecord::Migration
  def up
    execute "CREATE INDEX products_gin_question ON products USING GIN(to_tsvector('english', question))"
  end

  def down
    execute "DROP INDEX products_gin_question"
  end
end


> rake db:migrate

The above migration will create the GIN Index for the products table.

Thank You,
Uma Mahesh.

knockout.js in ruby on rails

knockout.js helps you to simplify dynamic JavaScript UIs using the Model-View-ViewModel (MVVM) pattern.

Key features :

1) Easily associate DOM elements with model data using a concise, readable syntax.

2) Pure JavaScript and works with any web framework.

3) When your data model's state changes, your UI updates automatically.

4) Small and Lightweight.

5) Implicitly set up chains of relationships between model data, to transform and combine it.

6) Supports all mainstream browsers.

7) Quickly generate sophisticated, nested UIs as a function of your model data.

Knockout.js follows Model-View-View Model (MVVM) is a design pattern for building user interfaces.

The official website for knockout.js is http://knockoutjs.com/

Coming to using knockout.js in ruby on rails application. After googling I came to see its been using ruby on rails application with the help of gem 'knockout-rails' https://github.com/dnagir/knockout-rails

Here is one of the useful URL which explains the benefits of knockoutjs over backbone.js
URL:http://jeffdeville.com/javascript-development-and-frameworks


some useful links related to knockout.js with rails Implementation

http://obruening.github.com/projects/knockoutjs/help.html

https://github.com/umamahesh/Knockout-On-Rails

Thank You,
Uma Mahesh.

Wednesday, 15 August 2012

Best SCRUM tools

Hi,

I would like to share few thought on SCRUM tools that are most popular in the Tech world.

Agile methodology plays an important role in the software application development, Its bought a wide difference in the application development strategy.

Here are the few tools I have used till now.

1)  Basecamp  Its a product of 37 signals.

2) JIRA

3) Pivotal Tracker 

Here are few more tools that I have seen.

4) Rally 

Let share your views with the tools you have used, by posting comments to this.

Thank You,
Uma Mahesh.

error installing mysql with native extensions

Hi,

Here is the error with mysql on bundle install in my system


Installing mysql (2.8.1) with native extensions
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

        /usr/local/rvm/rubies/ruby-1.9.3-p194/bin/ruby extconf.rb
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lm... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lz... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lsocket... no
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lnsl... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lmygcc... no
checking for mysql_query() in -lmysqlclient... no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
--with-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/usr/local/rvm/rubies/ruby-1.9.3-p194/bin/ruby
--with-mysql-config
--without-mysql-config
--with-mysql-dir
--without-mysql-dir
--with-mysql-include
--without-mysql-include=${mysql-dir}/include
--with-mysql-lib
--without-mysql-lib=${mysql-dir}/lib
--with-mysqlclientlib
--without-mysqlclientlib
--with-mlib
--without-mlib
--with-mysqlclientlib
--without-mysqlclientlib
--with-zlib
--without-zlib
--with-mysqlclientlib
--without-mysqlclientlib
--with-socketlib
--without-socketlib
--with-mysqlclientlib
--without-mysqlclientlib
--with-nsllib
--without-nsllib
--with-mysqlclientlib
--without-mysqlclientlib
--with-mygcclib
--without-mygcclib
--with-mysqlclientlib
--without-mysqlclientlib


Gem files will remain installed in /usr/local/rvm/gems/ruby-1.9.3-p194/gems/mysql-2.8.1 for inspection.
Results logged to /usr/local/rvm/gems/ruby-1.9.3-p194/gems/mysql-2.8.1/ext/mysql_api/gem_make.out
An error occured while installing mysql (2.8.1), and Bundler cannot continue.
Make sure that `gem install mysql -v '2.8.1'` succeeds before bundling.


I have searched in google and came to see its missing some required libraries i.e 'libmysqlclient15-dev'

To install the 'libmysqlclient15-dev' library run the below command,

> sudo apt-get install libmysqlclient15-dev


Now it will solve the above issue.

Thank You,
Uma Mahesh.

cannot load such file -- zlib

Hi,

I have faced issue with zlib while installing rails.

Here is the error

root@umamahseh-desktop:/home/umamahseh# gem install rails

ERROR:  Loading command: install (LoadError)
    cannot load such file -- zlib
ERROR:  While executing gem ... (NameError)
    uninitialized constant Gem::Commands::InstallCommand


I have solved the issue by installing mysql in my system. Use Ubuntu software center for installing mysql client and mysql server.


Thank You,
Uma Mahesh.

Tuesday, 14 August 2012

Installing Ruby On Rails in Ubuntu 12.04 LTS


Hi,

The latest version of Ubuntu 12.04 was relaesed, Ubuntu 12.04 LTS (Long Term Support)

Installing Ruby On Rails is easy and cane be done using RVM.

Here are the simple steps for installation

1) Install CURL
> sudo apt-get install curl

2) Install GIT
> sudo apt-get install curl git-core

3) Install RVM and Dependencies
> curl -L get.rvm.io | bash -s stable

Once that’s done, we’re going to need to add a line to ~/.bashrc file (the file responsible for setting up our bash session) which will load RVM. Do this by running this command in the terminal:


echo '[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"' >> ~/.bashrc 

Then we’ll need to reload the ~/.bashrc file which we can do with this small command:

. ~/.bashrc



4) Then install additional dependencies specified by the RVM
> rvm requirements

The above command will list all the requirements.
> sudo apt-get -y install build-essential openssl libreadline6 libreadline6-dev zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev automake libtool bison subversion

5) Installing Javascript Runtime
> sudo apt-get install nodejs

6) Install ruby
> rvm install 1.9.3
> ruby -v

Now it should display the ruby version that was installed in your system


7) Install Rails
> gem install rails


Now you are done with Installation of Ruby On Rails in your Ubuntu system. Now you can start creating rails application.


Help full links: RVM Installations - https://rvm.io/rvm/install/


Thank You,
Uma Mahesh.

Saturday, 4 August 2012

Installing RVM in ubuntu

Hi,

Below are the steps to install RVM in ubuntu

curl -L https://get.rvm.io | bash -s stable --ruby
 
Run the above command as root user in console
 
This will install the latest version of rvm and latest version of ruby in your system.
 
Thank You,
Uma Mahesh.
 
 
 
 
 

Wednesday, 1 August 2012

latest version of rails 3.2.7 released

Hi,

Rails 3.2.7 has been released. It has some important security fixes. Below is the reference url

URL: http://weblog.rubyonrails.org/2012/7/26/ann-rails-3-2-7-has-been-released/


Thank You,
Uma Mahesh.

url to latest jquery version

Hi,

Here is the url for the latest jquery file that you required to include in html page for jquery library.

http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js

Thank You,
Uma Mahesh.

diplay data in webpage on page load

Hi,

In the webworld, displaying webpage in less time plays an important role. So in many satuations you may required to load the page parts separately i.e through ajax call in the page load.

You can see in many webpage page will be loaded first and parts of the webpage is loaded after that.

This can be done using jquery ".load()" method.

This method will load data from server and place the returned html in the element.


  .load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] )

  url =>  url of the request to be send.
  data => data that is sent to server.
  complete => its an call back that will inoke after the load was done.



 ex : $('#content').load('umamahesh/sample.html');


 here 'content' => div id
 url => umamahesh/sample.html


sample code:

<! DOCUMENT HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
</head>
<body>
<h1>Response block</h1>
<div id="success"> </div>
<b>Error block:</b>
<div id="error"></div>
<script>
$("#success").load("success.html", function(response, status, xhr) {

  if (status == "error") {
    var msg = "Sorry but there was an error: ";
    $("#error").html(msg + xhr.status + " " + xhr.statusText);
  }
});
  </script>
</body>
</html>


success.html

<! DOCUMENT HTML>
<html>
<head>
</head>
<body>
<div>
Hi my name is uma mahesh
</div>
</body>
</html>


You can load part of data from the url page as below

$('#content').load('umamahesh/sample.html #data');

When this method executes, it retrieves the content of umamahesh/sample.html, but then jQuery parses the returned document to find the element with an ID of data. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.


Thank You,
Uma Mahesh.

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.