Multiple actions on one form

By Brijesh Shah, November 19, 2009 10:46 pm

By using form tag we can define a action where we can submit the data and proceed further.

Now there are multiple submit button on the form and each required different action. So how to do that?

I found one easy solution for the this.


<form action="ACTION" name="formName"  id="formName">

<input type="text">

.....

<input type="submit" value="Submit">

<input type="button" value="Next" onclick="next()">

<input type="button" value="Previous" onclick="previous()">

</form>

function next(){

document.formName.action="Next Action";

document.formName.submit();

}

function previous(){

document.formName.action="Previous Action";

document.formName.submit();

}

So this way we can define multiple actions on the same page.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Webnews
  • Digg
  • del.icio.us
  • Reddit
  • Bloglines
  • LinkedIn
  • YahooMyWeb
  • Facebook
  • Google Bookmarks
  • Mixx
  • MySpace
  • Technorati
  • TwitThis

Labels in IE

By Brijesh Shah, October 20, 2009 1:09 am

Recently I develop one project which created by one of the plugin.

This project having pre configured css for the pages. Application is run well on all borwsers except IE.

In IE, labels are not displayed. Labels are displayed When I highlight on that by mouse.

This is a very strange problem for me because text is displayed sometime and sometime not. Even sometime some of the labels are shown where some labels are  not on a same page.

Finally I found that all browsers have own default font size. Like firefox having 14px and IE having 16px.

I felt that there are some padding issues with font styles in IE. So I applied the below patch for IE browsers..


body {font: 13px/1.5 Arial, Verdana, sans-serif;}

Still I don’t know what means this but it works for me. Now in IE browser labels are shown consist.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Webnews
  • Digg
  • del.icio.us
  • Reddit
  • Bloglines
  • LinkedIn
  • YahooMyWeb
  • Facebook
  • Google Bookmarks
  • Mixx
  • MySpace
  • Technorati
  • TwitThis

auto_complete problem in ruby 1.9

By Brijesh Shah, October 8, 2009 10:57 pm

Recently I upgrade my rails version from 2.3.2  to 2.3.4 and ruby version from 1.8 to 1.9 .

By changing version of ruby,  I was facing problem in auto complete functionality.

To solve the issue , I applied below patch in lib/autocomeplete_macro_helper.rb file

def auto_complete_result(entries, field, phrase = nil)
return unless entries
items = entries.map { |entry| content_tag("li", phrase ? highlight(entry[field], phrase) : h(entry[field])) }
content_tag("ul", items.uniq.join)
end

I changed content_tag (“ul”, items.uniq) to content_tag(“ul”,items.uniq.join)

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Webnews
  • Digg
  • del.icio.us
  • Reddit
  • Bloglines
  • LinkedIn
  • YahooMyWeb
  • Facebook
  • Google Bookmarks
  • Mixx
  • MySpace
  • Technorati
  • TwitThis

Pop up window problem in IE

By Brijesh Shah, September 18, 2009 3:35 am

Recently I was having problem to open pop up window in IE browsers. Although it works properly in all other browsers.

In IE , window is open on self window rather than another window.

Finally I found the error in my code, and that was window name problem.

I defined the window name with space (window name). It must be without space (window_name).

Syntax must be

window.open(url,'window_name','height=570,width=400,scrollbars=1');
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Webnews
  • Digg
  • del.icio.us
  • Reddit
  • Bloglines
  • LinkedIn
  • YahooMyWeb
  • Facebook
  • Google Bookmarks
  • Mixx
  • MySpace
  • Technorati
  • TwitThis

File upload in ruby on rails.

By Brijesh Shah, August 30, 2009 4:02 am

There are lots of plugins available for upload files in ruby on rails.

  • file_column plugin:
  • attachment_fu
  • flex_image
  • upload_column
  • and many more

Accoding to  me, all these file are more useful for image uplaoding not other files like voice file, pdf and other.

So I made a defination which check following things and then upload a file on defined location.

1. File extension.

2. Mime type (require mime type plugin)

3. Size of the file

#Define basic things in enviornment/development.rb file

FILE_EXTENSIONS = [".wav",".mp3",".gsm",".pdf"] #Allowed file types

FILE_TEMP_PATH="#{RAILS_ROOT}/public/temp/" #Where file is initialy uploaded

FILE_MIME_EXTENSIONS =["audio/x-wav","audio/mpeg","audio/gsm","audio/x-gsm","application/pdf"] #Allowed file types

FILE_ROOT_PATH= "#{RAILS_ROOT}/public/saved/" #Where file is uploaded permanently

FILE_MAXIMUM_SIZE_FOR_FILE=1048576 #Maximum Size (1MB) define in bytes

#In model

before_save :save_file

attr_accessor :file_data

def get_filename
#define your rename file method
t = Time.now
"file_#{t.strftime("%Y%m%d%H%M")}"
end

def save_file
begin
# No update necessary
return true if self.file_data.blank?
filename = get_filename
return false if filename.nil?

extension = File.extname(self.file_data.original_filename)
if extension.nil?
errors.add(:file_data,"Wrong Extension")
return false
end

# Check if the FILE_TEMP_PATH is created, if not try to create
if !File.directory?(FILE_TEMP_PATH)
File.makedirs(FILE_TEMP_PATH)
end

temp_source = File.join(FILE_TEMP_PATH, filename)
temp_source << extension
final_source = File.join(FILE_ROOT_PATH, filename)
final_source << extension

File.open(temp_source, "wb") { |f| f.write(self.file_data.read)}

size=File.size(temp_source)
extension = File.extname(temp_source)
mime_extension=File.mime_type?(temp_source)
if FILE_MIME_EXTENSIONS.include?(mime_extension) == false
logger.error("Trying to upload file with mime-type: #{mime_extension} ")
errors.add(:file_data,"Only wav, mp3,gsm and pdf files are allowed")
return false
end
if FILE_EXTENSIONS.include?(extension) == false
logger.error("Trying to upload file with extension: #{extension} ")
errors.add(:file_data,"File extension should be wav, mp3, gsm or pdf")
return false
end
if size > FILE_MAXIMUM_SIZE_FOR_FILE
logger.error("Trying to upload file with size: #{size} ")
errors.add(:file_data,"File should not be more than #{FILE_MAXIMUM_SIZE_FOR_FILE} bytes")
return false
end
if valid? #Upload in permanent folder
logger.error("#{self.errors.to_xml}")
self.file=filename
FileUtils.copy_file(temp_source,final_source)
FileUtils.rm(temp_source) if File.exists?(temp_source)
return true
else
errors.add(:file_data,"Invalid file format")
FileUtils.rm(temp_source) #Remove temp file
return false
end
rescue => e
logger.error(e)
errors.add(:file_data,"Invalid file format")
return false
end

end

# In View form

<% form_for :obj_name,:html=>{:multipart=>true} do |f| %>

<%= f.error_messages %>

File: <%=f.file_field :file_data%>
<%= f.submit "Create" %>

<% end %>

Let me know if you are facing any problem in this..

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Webnews
  • Digg
  • del.icio.us
  • Reddit
  • Bloglines
  • LinkedIn
  • YahooMyWeb
  • Facebook
  • Google Bookmarks
  • Mixx
  • MySpace
  • Technorati
  • TwitThis

Strip tags in Rails, Javascript and PHP

By Brijesh Shah, August 28, 2009 10:30 pm

Strip tag function is used to remove html tags from the string.

Here I will show you that how to use strip tag in ruby on rails, javascript and php.

#PHP:

Example 1: Remove all html tags.

<?php
$str '<h1>Test1.</h1><p> text2</p>';
echo strip_tags($str);
?>

Example 2: Allow p and h1 html tag.

<?php
$str '<h1>Test1.</h1><p> text2</p>';
echo strip_tags($str,"<h1><p>");
?>

#Ruby On Rails

Example 1: Remove all html tags

#model

class User < ActiveRecord::Base
include ActionView::Helpers
before_save :strip_comment
def strip_comment
return true if self.comment.nil?
self.comment=sanitize(self.comment,:tags =>%w())
save
return true
end

Example 2: Allow h1 and p html tags

#model

class User < ActiveRecord::Base
include ActionView::Helpers
before_save :strip_comment

def strip_comment
return true if self.comment.nil?
self.comment=sanitize(self.comment,:tags =>%w(p h1))
save
return true
end

#Javascript
#Add strip_tags.js

function strip_tags (str, allowed_tags) {

var key = '', allowed = false;
var matches = [];
var allowed_array = [];
var allowed_tag = '';
var i = 0;
var k = '';
var html = '';</pre>
var replacer = function (search, replace, str) {
return str.split(search).join(replace);
};

// Build allowes tags associative array
if (allowed_tags) {
allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
}

str += '';

// Match tags
matches = str.match(/(<\/?[\S][^>]*>)/gi);

// Go through all HTML tags
for (key in matches) {
if (isNaN(key)) {
// IE7 Hack
continue;
}

// Save HTML tag
html = matches[key].toString();

// Is tag not in allowed list? Remove from str!
allowed = false;

// Go through all allowed tags
for (k in allowed_array) {
// Init
allowed_tag = allowed_array[k];
i = -1;

if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}

// Determine
if (i == 0) {
allowed = true;
break;
}
}

if (!allowed) {
str = replacer(html, "", str); // Custom replace. No regexing
}
}

return str;

}

#Used strip_tags function to remove html tags.
Example 1: remove all html tags.

var html_string= '<h1>Test1.</h1><p> text2</p>';
var strip_string= strip_tags(html_string);

Example 2: allow only p and h1 html tags

var html_string= '<h1>Test1.</h1><p> text2</p>';
var strip_string= strip_tags(html_string,"<p><h1>");
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Webnews
  • Digg
  • del.icio.us
  • Reddit
  • Bloglines
  • LinkedIn
  • YahooMyWeb
  • Facebook
  • Google Bookmarks
  • Mixx
  • MySpace
  • Technorati
  • TwitThis

Find latitude-longitude in rails

By Brijesh Shah, August 11, 2009 4:00 am

Recently I posted a blog about  How to generate Google Maps in ruby on rails. In this blog, I used hard coded latitude-longitude values.

In real app hard coded values does not work, so we have to store latitude or longitude details in database or get it runtime.

By using geokits ,we can get latitude -longitude details based on address details (street,city,state,country).

Install a geokit gem

sudo gem install geokit

or download geokit plugin from Github

#Configuration details : config/initializers/geokit_config.rb

# These defaults are used in Geokit::Mappable.distance_to and in acts_as_mappable
Geokit::default_units = :miles
Geokit::default_formula = :sphere

# This is the timeout value in seconds to be used for calls to the geocoder web
# services.  For no timeout at all, comment out the setting.  The timeout unit
# is in seconds.
Geokit::Geocoders::timeout = 3

# These settings are used if web service calls must be routed through a proxy.
# These setting can be nil if not needed, otherwise, addr and port must be
# filled in at a minimum.  If the proxy requires authentication, the username
# and password can be provided as well.
Geokit::Geocoders::proxy_addr = nil
Geokit::Geocoders::proxy_port = nil
Geokit::Geocoders::proxy_user = nil
Geokit::Geocoders::proxy_pass = nil

# This is your yahoo application key for the Yahoo Geocoder.
# See http://developer.yahoo.com/faq/index.html#appid
# and http://developer.yahoo.com/maps/rest/V1/geocode.html
Geokit::Geocoders::yahoo = 'REPLACE_WITH_YOUR_YAHOO_KEY'

# This is your Google Maps geocoder key.
# See http://www.google.com/apis/maps/signup.html
# and http://www.google.com/apis/maps/documentation/#Geocoding_Examples
Geokit::Geocoders::google = 'REPLACE_WITH_YOUR_GOOGLE_KEY'

# You can also set multiple API KEYS for different domains that may be directed to this same application.
# The domain from which the current user is being directed will automatically be updated for Geokit via
# the GeocoderControl class, which gets it's begin filter mixed into the ActionController.
# You define these keys with a Hash as follows:
#Geokit::Geocoders::google = { 'rubyonrails.org' => 'RUBY_ON_RAILS_API_KEY', 'ruby-docs.org' => 'RUBY_DOCS_API_KEY' }

# This is your username and password for geocoder.us.
# To use the free service, the value can be set to nil or false.  For
# usage tied to an account, the value should be set to username:password.
# See http://geocoder.us
# and http://geocoder.us/user/signup
Geokit::Geocoders::geocoder_us = false

# This is your authorization key for geocoder.ca.
# To use the free service, the value can be set to nil or false.  For
# usage tied to an account, set the value to the key obtained from
# Geocoder.ca.
# See http://geocoder.ca
# and http://geocoder.ca/?register=1
Geokit::Geocoders::geocoder_ca = false

# require "external_geocoder.rb"
# Please see the section "writing your own geocoders" for more information.
# Geokit::Geocoders::external_key = 'REPLACE_WITH_YOUR_API_KEY'

# This is the order in which the geocoders are called in a failover scenario
# If you only want to use a single geocoder, put a single symbol in the array.
# Valid symbols are :google, :yahoo, :us, and :ca.
# Be aware that there are Terms of Use restrictions on how you can use the
# various geocoders.  Make sure you read up on relevant Terms of Use for each
# geocoder you are going to use.
Geokit::Geocoders::provider_order = [:google,:us]

# The IP provider order. Valid symbols are :ip,:geo_plugin.
# As before, make sure you read up on relevant Terms of Use for each.
# Geokit::Geocoders::ip_provider_order = [:external,:geo_plugin,:ip]

#How to use

a=Geokit::Geocoders::YahooGeocoder.geocode '140 Market St, San Francisco, CA'
puts a.lat #Display latitude
puts a.lng #Display longitude

I assume that you have model USER with following fields.

id, username, street, city, state, country, latitude,longitude

#In User.rb

def address
return ("#{self.street},#{self.city},#{self.state},#{self.country}")
end

#In User controller

def update_users
@users=User.find(:all)
for user in @users
geocode=Geokit::Geocoders::GoogleGeocoder.geocode(user.address)
user.latitude=geocode.lat
user.longitude=geocode.lng
user.save
end
end
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Webnews
  • Digg
  • del.icio.us
  • Reddit
  • Bloglines
  • LinkedIn
  • YahooMyWeb
  • Facebook
  • Google Bookmarks
  • Mixx
  • MySpace
  • Technorati
  • TwitThis

Waiting for gg.google.com

By Brijesh Shah, August 7, 2009 5:09 am

When I was working on Google Maps API , I was getting error of “waiting for gg.google.com” on status bar.

Later on I found out that if script debugging is diabled, this problem can not raise.

So just disable script debugging from the firebug.

Firebug Script Debug

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Webnews
  • Digg
  • del.icio.us
  • Reddit
  • Bloglines
  • LinkedIn
  • YahooMyWeb
  • Facebook
  • Google Bookmarks
  • Mixx
  • MySpace
  • Technorati
  • TwitThis

GPolygon in Gmaps

By Brijesh Shah, August 7, 2009 3:47 am

By using Gpolygon we can display a path on gmap. You need to just define order of locations(latitude,longitude) in this.

But you have to know How to generate Gmaps in ruby on rails

Create a polygone array #From Sri Lanka to Afghanistan

polyline=GPolyline.new([[7.880794,80.507813],
[22.792388,79.497070],
[29.874945, 69.345703],
[33.757228,65.522461]],
&amp;quot;#ff0000&amp;quot;,1,5.0)

Add into your map


@map.overlay_init(polyline)

You will get following output.

gmap_polygon

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Webnews
  • Digg
  • del.icio.us
  • Reddit
  • Bloglines
  • LinkedIn
  • YahooMyWeb
  • Facebook
  • Google Bookmarks
  • Mixx
  • MySpace
  • Technorati
  • TwitThis

Google Maps in Ruby on Rails

By Brijesh Shah, August 6, 2009 11:49 pm

To generate google maps in ruby on rails is so easy and simple. I had recently generated a few maps in my projects by  YM4R/GM plugin.

There are few steps that you need to follow to generate simple gmap.

1. Install YM4R/GM plugin in your rails app.

ruby script/plugin install svn://rubyforge.org/var/svn/ym4r/Plugins/GM/trunk/ym4r_gm

2. Copy  the javascripts files from YM4R/GM plugin to public/javascript folder

3. Copy the gmaps_api_key.yml.example file to config folder and rename to gmaps_api_key.yml. Set the api key in that YML file.

If application is  in development mode then no necessary to change it.

4. Add below code in your controller.

def gmap

@map = GMap.new("map_div")

@map.control_init(:large_map => true,:map_type => true)

@map.center_zoom_init([22.792388,79.497070],4)

@map.overlay_init(GMarker.new([22.792388,79.497070],:title =>"India", :info_window =>"India"))

@map.record_init @map.add_overlay(GMarker.new([22.792388, 72.421875],:title =>"Ahmedabad", :info_window =>"Ahmedabad"))

end

#control_init : By  default false.

:large_map: true means you can get options of zoom in /zoom out of map on left side of map.

:map_type: true means you can change the type of map.

#center_zoom_init: Set the center point of map.

#overlay_init: Mark the position on map.

#record_init @map.add_overlay: Mark more position on map.

5. Add below code in your view.

<html><head><title>Test</title>
<%= GMap.header %>
<%= @map.to_html %>
</head><body>
<%= @map.div(:width => 600, :height => 400) %>
</body></html>

#You will get following output
Google Map

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Webnews
  • Digg
  • del.icio.us
  • Reddit
  • Bloglines
  • LinkedIn
  • YahooMyWeb
  • Facebook
  • Google Bookmarks
  • Mixx
  • MySpace
  • Technorati
  • TwitThis

Panorama Theme by Themocracy