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.