Archive for October, 2006
RoR(Ruby on Rails) in India – Ruby on Rails based Indian Company
Ruby on Rails is creating the storms in the web development all over the world. RoR is even capable to challenge Big Caps like Microsoft’s Asp.NET and so everything else in the specific area. World is continuously changing… The current WEB not solely depends on the old,encoded,paid,stressful technologies but the fresh,open-source,free,joyful technologies like Ruby on Rails are now creating the new highways to connect the WEB… What else ?.. Providing a beautiful atmosphere to web-developers. At the moment the whole world of web-development is cherishing the fresh breeze of RoR.
How much of INDIA is delighted by Ruby on Rails ?
Currently, the INDIAN side of Rails is a small community…but growing at a rapid rate. I am proudly working at VINSOL(New Delhi,India), a company full fledged working on rails.
VINSOL is currently holding some good clients for web-development and providing efficient services in Ruby on Rails.
3 comments October 25, 2006
Captcha in Ruby on Rails – Customize the use of captcha in the plugin validates_captcha
Hello Everyone !!
I have released a captcha plugin Simple Captcha. It is really simple to implement, and provides a cool feature of multiple styles of images.
Previous Post for validates_captcha
To implement captcha in RubyonRails, validates_captcha plugin can be a good option but a small customization i need with this plugin was to use it on some specific action and not to be validated the captcha field every time an instance of the model is saved or updated.
Here is a small work-around for its customization…
How to use customized captcha in RoR ?
Install the plugin validates_captcha in your rails application by running this command from the root of your application
ruby script/plugin install http://svn.2750flesk.com/validates_captcha
Make sure that you can now see the directory vedor/plugins/validates_captcha.
Now run these commands from your application root to make the image and data directories
ruby script/generate captcha store_directory ruby script/generate captcha image_directory
Here is the complete API for the usage of this plugin. I am describing the same idea as given in this API but in a bit more specific means.
Lets consider a model User in which we will implement the captcha.
Add the following code in the file app/models/user.rb
class User < ActiveRecord::Base
validates_captcha :if => :request_captcha_validation?
attr_accessor :request_captcha_validation
def request_captcha_validation?
(self.request_captcha_validation==true)? true : false
end
end
Handle View and Controller
Add the code in the view inside your existing form.
<% c = prepare_captcha :type => :image -%> <%= captcha_hidden_field c, 'user' %> <%= captcha_image_tag c %> <%= captcha_label 'user', 'Type in the text from the image above' %> <%= captcha_text_field 'user' %>
Your controller will look like
def save
# the line in bold represents that you need captcha validation.
# if captcha validation is not required then remove this line from your controller.
@user = User.new(params[:user])
@user.request_captcha_validation = true
@user.save
end
However image is too noisy and it contains repeated strings.
To improve the quality of images generated by the plugin validates_captcha visit Here.
50 comments October 24, 2006
MicroSoft’s IE-7 Released – another headache for web developers.
Current World’s software giant Microsoft finally released the new milestone IE-7.
Once again web programmers have to reload their guns to cross a new barrirer of all new standards of MicroSoft another thing IE-7.
Its a feel of proud for Microsoft to not to follow the web-standards of W3C and to give themselves a fresh new region of narrow mentality people and a feel of headache for web developers to again customizing their previous running web-sites which already been specially customized to go ok with a mess IE-6 and here is a repeated story again coz the most amazing thing is that IE-7 is even not following the styles of IE-6…
Go FireFox !! Go Flock !!
2 comments October 21, 2006
Using Regular Expression in Ruby on Rails — Regexp for Password Validation
A regular expression (abbreviated as regexp or regex, with plural forms regexps, regexes, or regexen) is a string that describes or matches a set of strings, according to certain syntax rules. Regular expressions are used by many text editors and utilities to search and manipulate bodies of text based on certain patterns. Many programming languages support regular expressions for string manipulation. Ruby has a strong Regular Expression engine built directly as a class of Ruby Programming language as Regexp
Here we will go through an example which will validate the password string.
Lets say we have to implement the following validations to validate a password…
- Password should contain atleast one integer.
- Password should contain atleast one alphabet(either in downcase or upcase).
- Password can have special characters from 20 to 7E ascii values.
- Password should be minimum of 8 and maximum of 40 cahracters long.
To fulfill above requirements we can have a regular expression like…
/^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$/
in ruby programming language we can have a number of ways to define this regular expression as…
■ reg = Regexp.new(“^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$”)
or
■ reg = %r(^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$)
or simply
■ reg = /^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$/
Now look what exactly this regex is doing…
(?=.*\d) shows that the string should contain atleast one integer.
(?=.*([a-z]|[A-Z])) shows that the string should contain atleast one alphabet either from downcase or upcase.
([\x20-\x7E]) shows that string can have special characters of ascii values 20 to 7E.
{8,40} shows that string should be minimum of 8 to maximum of 40 cahracters long.
We can simply use this regular expression for manual handling of password in an action as…
def validate_password(password)
reg = /^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$/
return (reg.match(password))? true : false
end
How to implement this regular expression in a model class in ruby on rails for password validation ?
To implement this regular expression in the model class in the rails way we can do it like…
class MyModel
validates_format_of :password, :with => /^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$/
end
4 comments October 19, 2006
Rake task to prepare test database from migrations
To use your migrations for preparing test database create a file testdb.rake
in the directory lib/tasks.
Now add the following code in the lib/tasks/testdb.rake file…
module Rake
module TaskManager
def redefine_task(task_class, args, &block)
task_name, deps = resolve_args(args)
task_name = task_class.scope_name(@scope, task_name)
deps = [deps] unless deps.respond_to?(:to_ary)
deps = deps.collect {|d| d.to_s }
task = @tasks[task_name.to_s] = task_class.new(task_name, self)
task.application = self
task.add_comment(@last_comment)
@last_comment = nil
task.enhance(deps, &block)
task
end
end
class Task
class << self
def redefine_task(args, &block)
Rake.application.redefine_task(self, args, &block)
end
end
end
end
def redefine_task(args, &block)
Rake::Task.redefine_task(args, &block)
end
namespace :db do
namespace :test do
desc 'Prepare the test database and migrate schema'
redefine_task :prepare => :environment do
Rake::Task['db:test:migrate_schema'].invoke
end
desc 'Use the migrations to create the test database'
task :migrate_schema => 'db:test:purge' do
ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
ActiveRecord::Migrator.migrate("db/migrate/")
end
end
end
To prepare the test database from migrations run this command
$ rake db:test:migrate_schema
3 comments October 17, 2006
How to improve the image quality and generate random string image in the plugin validates_captcha
Hello Everyone !!
I have released a captcha plugin Simple Captcha. It is really simple to implement, and provides a cool feature of multiple styles of images.
Previous post about improving validates_captcha’s images
Validates captcha is a good plugin to implement captcha in your rails application.
However i found that there is repetition of the string of the image and the quality of image is not that good. To get a good quality image and random string
something like this

replace the code of the file /vendor/plugins/validates_captcha/lib/captcha_challenge.rb with the following code…
require 'digest/sha1'
module AngryMidgetPluginsInc #:nodoc:
# CaptchaChallenge
class CaptchaChallenge
include CaptchaConfig
extend CaptchaConfig
DEFAULT_TTL = 1200#Lifetime in seconds. Default is 20 minutes.
attr_reader :id, :created_at
attr_accessor :ttl
def initialize(options = {}) #:nodoc:
generate_id
options = {
:ttl => config['default_ttl'] || DEFAULT_TTL
}.update(options)
self.ttl = options[:ttl]
@created_at = Time.now
self.class.prune
end
# Implement in subclasses.
def correct? #:nodoc:
raise NotImplementedError
end
private
def generate_id #:nodoc:
self.id = Digest::SHA1.hexdigest(Time.now.to_s+rand.to_s)
end
def id=(i) #:nodoc:
@id = i
end
def write_to_store #:nodoc:
store.transaction{
store[:captchas] = Array.new unless store.root?(:captchas)
store[:captchas] << self
}
end
class << self
# Removes old instances from PStore
def prune
store.transaction{
if store.root?(:captchas)
store[:captchas].each_with_index{|c,i|
if Time.now > c.created_at+c.ttl
store[:captchas].delete_at(i)
end
}
end
}
end#prune
end#class << self
end
# A CAPTCHA challenge where an image with text is
# generated. A human can read the text with relative
# ease, while most robots can not. There are accessibility
# problems with this challenge, though, as people
# with reduced or no vision are unlikely to pass the test.
class CaptchaImageChallenge < CaptchaChallenge
WORDS = 'gorilla costume, superman, banana bender, chuck norris, xray vision, ahoy me hearties,
chunky bacon, latex, rupert murdoch, clap your hands, year 2000,
sugar coated, coca cola, rastafarian, airbus a380'.split(/,s+/)
DEFAULT_DIR = 'captcha'#public/images/captcha
WRITE_DIR = File.join(RAILS_ROOT, 'public', 'images')
DEFAULT_FILETYPE = 'jpg'
attr_reader :image
attr_accessor :string, :dir, :filename, :filetype
# Creates an image challenge.
def initialize(options = {})
super
options = {
:string => config['words'] ? config['words'][rand(config['words'].size)] : WORDS[rand(WORDS.size)],
:dir => config['default_dir'] || DEFAULT_DIR,
:filetype => config['default_filetype'] || DEFAULT_FILETYPE
}.update(options)
self.string = Digest::SHA1.hexdigest(Time.now.to_s)[0..4].upcase #options[:string]
self.dir = options[:dir]
self.filetype = options[:filetype]
self.filename = options[:filename] || generate_filename
write_to_store
end
# Generates the image.
def generate(options = {})
options = {
:fontsize => 50,
:padding => 20,
:color => '#000',
:background => '#fff',
:fontweight => 'bolw',
:rotate => true
}.update(options)
options[:fontweight] = case options[:fontweight]
when 'bold' then 700
else 400
end
#added
text = Array.new
0.upto(4) do |i|
text[i] = Magick::Draw.new
text[i].pointsize = options[:fontsize]
text[i].font_weight = 600 #options[:fontweight]
text[i].fill = 'black' #options[:color]
text[i].gravity = Magick::CenterGravity
text[i].rotation = (rand(2)==1 ? rand(30) : -rand(30)) if options[:rotate]
end
metric = text[2].get_type_metrics(self.string)
#add bg
canvas = Magick::ImageList.new
fill = Magick::HatchFill.new('white','black')
x = metric.width+options[:padding]
y = metric.height+options[:padding]
#ADDING NOISE
img1 = Magick::Image.new(x,y,fill)
gc = Magick::Draw.new
gc.stroke_linejoin('round')
gc.stroke('black')
gc.stroke_width(1)
100.times do |i|
x1 = rand(x)
y1 = rand(y)
gc.circle(x1,y1,x1.next,y1)
end
gc.draw(img1)
canvas << img1
0.upto(4) do |i|
canvas << Magick::Image.new(metric.width+options[:padding], metric.height+options[:padding]){
self.background_color = '#000F'
y_loc = rand(y)
}.annotate(text[i], 0, 0, (i-2)*30, rand(y/4), self.string[i,1]) #.wave(5, 20)
end
canvas << Magick::Image.new(metric.width+options[:padding], metric.height+options[:padding]){
#changed
p = Magick::Pixel.from_color(options[:background])
p.opacity = Magick::MaxRGB
self.background_color = p
} #.add_noise(Magick::LaplacianNoise)
self.image = canvas.flatten_images.blur_image(1)
end
# Writes image to file.
def write(dir = self.dir, filename = self.filename)
self.image.write(File.join(WRITE_DIR, dir, filename))
end
# Determine if the supplied +string+ matches
# that used when generating the image.
def correct?(string)
string.downcase == self.string.downcase
end
# The full path to the image file, relative
# to <tt>public/images</tt>.
def file_path
File.join(dir,filename)
end
class << self
# Deletes old image files. Also calls CaptchaChallenge.prune
def prune
store.transaction{
if store.root?(:captchas)
store[:captchas].each_with_index{|c,i|
if Time.now > c.created_at+c.ttl
if File.exists?(File.join(WRITE_DIR, c.file_path))
begin
File.unlink(File.join(WRITE_DIR, c.file_path))
rescue Exception
end
end
end
}
end
}
super
end#prune
end#class << self
private
def generate_filename #:nodoc:
self.id+'.'+self.filetype
end
def image=(i) #:nodoc:
@image = i
end
end
end
visit Here to view the customized use of the plugin validates_captcha in RoR.
22 comments October 17, 2006
Rake task to remove the image and audio files created by captcha
To add a rake task to the rails application which removes all the image and audio files created by captcha, create a file named remove_captcha_files.rake in the lib/tasks directory.
Add the following code to the lib/tasks/remove_captcha_files.rake file…
desc "Remove captcha images and audio files"
task :remove_captcha_files do
image_path = "#{RAILS_ROOT}/public/images/captcha/"
audio_path = "#{RAILS_ROOT}/public/captcha_audio/"
Dir.foreach(image_path){|file| File.delete(image_path+file) if (/^.*.jpg$/).match(file)} if File.exist?(image_path)
Dir.foreach(audio_path){|file| File.delete(audio_path+file) if (/^.*.wav$/).match(file)} if File.exist?(audio_path)
puts "Captcha files removed."
end
You can confirm that task is added to your app by running
rake –task
To remove all the files created by captcha, simply run the command
rake remove_captcha_files
from the command line from your application root.
To better view the code visit here
Add comment October 16, 2006










Rss Feeds