File upload in ruby on rails.

By , 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 :o bj_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..

Strip tags in Rails, Javascript and PHP

By , 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 = '';
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>");

Find latitude-longitude in rails

By , 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

Waiting for gg.google.com

By , 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

GPolygon in Gmaps

By , 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

Panorama Theme by Themocracy