When you install fckeditor module in drupal you might get problem that editor's background color is applied from body background color. To fix this background color problem add another line in fckeditor.config.js:
FCKConfig.EditorAreaStyles = "body{background:#FFFFFF;text-align:left;}";
Other tips for fckeditor in drupal http://drupal.fckeditor.net/tricks
Saturday, March 27, 2010
Friday, March 26, 2010
Get IP address of the site visitor in rails application
In RAILS_ROOT/app/controllers/show_my_ip_controller.rb
class ShowMyIpController < ApplicationController
def index
@client_ip = request.remote_ip
end
end
In RAILS_ROOT/app/views/show_my_ip/index.html.erb
Your IP address is <%= @client_ip %>
class ShowMyIpController < ApplicationController
def index
@client_ip = request.remote_ip
end
end
In RAILS_ROOT/app/views/show_my_ip/index.html.erb
Your IP address is <%= @client_ip %>
Tuesday, March 23, 2010
Commands to start apache server and mysql server in linux
To start Apache webserver in linux (LAMP)
#service httpd start
the above command will start both apache and mysql servers.
To start Mysql server in linux (LAMP)
#service mysqld start
#service httpd start
the above command will start both apache and mysql servers.
To start Mysql server in linux (LAMP)
#service mysqld start
Thursday, March 18, 2010
Working with Float values
While you are working with float numbers and you should always want to display 1 or 2 numbers only after precission ex: You like to display 5.30 instead of 5.29088388434. To display in that format we have to use below functions
In Ruby:
f=1.23456
puts sprintf('%.2f', f).sub(/0{1,2}$/, '')
In php:
$$grandtotal = $rate*$miles;
echo number_format($grandtotal,2);
?>
In Ruby:
f=1.23456
puts sprintf('%.2f', f).sub(/0{1,2}$/, '')
In php:
$$grandtotal = $rate*$miles;
echo number_format($grandtotal,2);
?>
Monday, March 15, 2010
Multiple layouts for each Wordpress Page
The solution:
Edit ‘page.php’ to check what page your on, and then load the appropriate template.
The implementation:
If you edit page.php you’ll notice that it calls the get_header() and get_footer() functions. This is about the only bit of code that we want to keep in this file.
First Step:
First, make a copy of page.php and give it a name. This is your first template. Delete the header and footer calls from your template, because we’re going to load this into page.php, and it will have already called them.
Second Step:
Open page.php and delete everything between the header and footer calls. In this space, add a PHP conditional that uses the is_page() function.
if(is_page(107) == true) {
include ‘page_full.php’;
} else {
include ‘page_twocolumn.php’;
}
?>
Here’s an example of what I did to load multiple page layouts:
if(is_page(107) == true) {
include ‘page_films.php’;
} else if(is_page(array(518, 28, 13)) == true) {
include ‘page_full.php’;
} else {
include ‘page_twocolumn.php’;
}
?>
This sets page with ID 107 to use the template specific for the ‘films’ page. It also sets pages with ID’s 518, 28, and 13 to use the full page layout. All others use the two column layout.
That’s it!
Edit ‘page.php’ to check what page your on, and then load the appropriate template.
The implementation:
If you edit page.php you’ll notice that it calls the get_header() and get_footer() functions. This is about the only bit of code that we want to keep in this file.
First Step:
First, make a copy of page.php and give it a name. This is your first template. Delete the header and footer calls from your template, because we’re going to load this into page.php, and it will have already called them.
Second Step:
Open page.php and delete everything between the header and footer calls. In this space, add a PHP conditional that uses the is_page() function.
if(is_page(107) == true) {
include ‘page_full.php’;
} else {
include ‘page_twocolumn.php’;
}
?>
Here’s an example of what I did to load multiple page layouts:
if(is_page(107) == true) {
include ‘page_films.php’;
} else if(is_page(array(518, 28, 13)) == true) {
include ‘page_full.php’;
} else {
include ‘page_twocolumn.php’;
}
?>
This sets page with ID 107 to use the template specific for the ‘films’ page. It also sets pages with ID’s 518, 28, and 13 to use the full page layout. All others use the two column layout.
That’s it!
Tuesday, February 23, 2010
css tric to set containers height with minimum and auto values
.selector {
width:200px;
min-height:100px;
height:auto !important;
height:500px;
border:1px solid #000000;
padding:5px;
}
when you assign this class to any contaner like div or span, its minimum height is 100px if there is no content, then it is automatically exanded instead of scrolling when loaded content is more. Maximum height is 500px it is for IE browser only.
width:200px;
min-height:100px;
height:auto !important;
height:500px;
border:1px solid #000000;
padding:5px;
}
when you assign this class to any contaner like div or span, its minimum height is 100px if there is no content, then it is automatically exanded instead of scrolling when loaded content is more. Maximum height is 500px it is for IE browser only.
Monday, February 22, 2010
Sending emails with Gmail smtp server rather than your server's smtp
Download the phpmailer classes At http://sourceforge.net/projects/phpmailer/files/phpmailer%20for%20php5_6/
Then use the below code to send emails.
require(“includes/class.phpmailer.php”);
$mailer = new PHPMailer();
$mailer->IsSMTP();
$mailer->Host = ’ssl://smtp.gmail.com:465′;
$mailer->SMTPAuth = TRUE;
$mailer->Username = ‘{somename}@gmail.com’; // Change this to your gmail adress
$mailer->Password = ‘{password}’; // Change this to your gmail password
$mailer->From = ‘{someid}@gmail.com’; // This HAVE TO be your gmail adress
$mailer->FromName = ‘Venkat’; // This is the from name in the email, you can put anything you like here
$mailer->Body = ‘Message body’;
$mailer->Subject = ‘Message subject’;
$mailer->AddAddress(‘{toaddress email id}’); // This is where you put the email adress of the person you want to mail
if(!$mailer->Send())
{
echo “Message was not sent
”;
echo “Mailer Error: ” . $mailer->ErrorInfo;
}
else
{
echo “Message has been sent”;
}
?>
Then use the below code to send emails.
require(“includes/class.phpmailer.php”);
$mailer = new PHPMailer();
$mailer->IsSMTP();
$mailer->Host = ’ssl://smtp.gmail.com:465′;
$mailer->SMTPAuth = TRUE;
$mailer->Username = ‘{somename}@gmail.com’; // Change this to your gmail adress
$mailer->Password = ‘{password}’; // Change this to your gmail password
$mailer->From = ‘{someid}@gmail.com’; // This HAVE TO be your gmail adress
$mailer->FromName = ‘Venkat’; // This is the from name in the email, you can put anything you like here
$mailer->Body = ‘Message body’;
$mailer->Subject = ‘Message subject’;
$mailer->AddAddress(‘{toaddress email id}’); // This is where you put the email adress of the person you want to mail
if(!$mailer->Send())
{
echo “Message was not sent
”;
echo “Mailer Error: ” . $mailer->ErrorInfo;
}
else
{
echo “Message has been sent”;
}
?>
Friday, February 19, 2010
Cron job settings in server
Cron jobs are used to run a script automatically with some time interval Example if you want to send emails daily morining to all newsletter subscribers when new jobs were added to your jobs portal these cron jobs are used. Below are the steps to setup cron jobs
For php:
Login to hosting server and goto the cron job settings page and select the time interval you want to run the script then give the command to run the php file as below
php /path-to-your-phpfile.php
(OR)
/usr/local/bin/php /path-to-your-phpfile.php
For Ruby:
/usr/local/bin/ruby /home/user/domainname/script/runner /home/user/domainname/app/cron_job.rb
For php:
Login to hosting server and goto the cron job settings page and select the time interval you want to run the script then give the command to run the php file as below
php /path-to-your-phpfile.php
(OR)
/usr/local/bin/php /path-to-your-phpfile.php
For Ruby:
/usr/local/bin/ruby /home/user/domainname/script/runner /home/user/domainname/app/cron_job.rb
Understanding of Restful Architecture
RESTful interface means clean URLs, less code, CRUD interface.
CRUD means Create-READ-UPDATE-DESTROY.
You might heard about HTTP verbs, GET, POST. In REST, they add 2 new verbs, i.e, PUT, DELETE.
There are 7 default actions, those are – index, show, new, create, edit, update, destroy
GET is used when you retrieve data from database. POST is used when you create new record in database. PUT is used when you are updating any existing record in database, and DELETE is used when you are destroying any record in database. Following table may clear the concept.
Action VERB
index GET
show GET
new GET
create POST
edit GET
update PUT
destroy DELETE
CRUD means Create-READ-UPDATE-DESTROY.
You might heard about HTTP verbs, GET, POST. In REST, they add 2 new verbs, i.e, PUT, DELETE.
There are 7 default actions, those are – index, show, new, create, edit, update, destroy
GET is used when you retrieve data from database. POST is used when you create new record in database. PUT is used when you are updating any existing record in database, and DELETE is used when you are destroying any record in database. Following table may clear the concept.
Action VERB
index GET
show GET
new GET
create POST
edit GET
update PUT
destroy DELETE
Tuesday, February 16, 2010
PHP and Flash Interaction Through XML and Actionscript
Flash can interact with dynamic data using XML files and also submit data to the php code using Action Script's getURL function. The getURL function in ActionScript can be used to set the external url to links and also for the flash form submissions. You can send any variable value from within the flash file to a PHP file. For example the following code,
getURL("fromFlash.php", "_blank", "POST");
can be used to send variables from Flash to a PHP file fromFlash.php. The variable sent according to the code above use the POST method. You can use the $_POST('variable_name') to get the data from the flash file and assign that value to some other variable within the PHP file. It is so easy to do it.
To load XML data in flash you can create an XML object and use that object's Load method to load the XML file you need.
getURL("fromFlash.php", "_blank", "POST");
can be used to send variables from Flash to a PHP file fromFlash.php. The variable sent according to the code above use the POST method. You can use the $_POST('variable_name') to get the data from the flash file and assign that value to some other variable within the PHP file. It is so easy to do it.
To load XML data in flash you can create an XML object and use that object's Load method to load the XML file you need.
Monday, February 15, 2010
Open multiple urls at a time
To open multiple windows at a time use the below code in Javascript
window.open('http://www.yahoo.com');
window.open('http://www.gmail.com');
take the above lines in one js function and call the function when you want to open yahoo and google at a time in two different tabs.
window.open('http://www.yahoo.com');
window.open('http://www.gmail.com');
take the above lines in one js function and call the function when you want to open yahoo and google at a time in two different tabs.
All about Ajax and its states
Ajax (Asynchronous Javascript And XML) is used to update part of the webpage's content Asynchronously without reloading the entire page. Below are the five possible response states in Ajax
0: The request is uninitialized (before you've called open()).
1: The request is set up, but not sent (before you've called send()).
2: The request was sent and is in process (you can usually get content headers from the response at this point).
3: The request is in process; often some partial data is available from the response, but the server isn't finished with its response.
4: The response is complete; you can get the server's response and use it.
0: The request is uninitialized (before you've called open()).
1: The request is set up, but not sent (before you've called send()).
2: The request was sent and is in process (you can usually get content headers from the response at this point).
3: The request is in process; often some partial data is available from the response, but the server isn't finished with its response.
4: The response is complete; you can get the server's response and use it.
About ORM (Object Relation Mapping)
Accessing database using a layer of classes is called ORM. The rest of the application uses these classes and their objects. It never allow directly interacting with database.
1. ORM libraries map database tables to classes. If a database has a table users(plural).Our program will have a class named user(singular) stored in model folder,
2. Rows in this table correspond to objects of the class—a particular user is represented as an object of class user.
3. By using this object's attributes we can set and get the individual columns.
So an ORM layer maps tables to classes, rows to objects and columns to attributes of that object(methods).
Class methods are used to perform table-level operations.
Instance methods are used to perform operations on the individual rows.
It is all taken care by ActiveRecord class.
1. ORM libraries map database tables to classes. If a database has a table users(plural).Our program will have a class named user(singular) stored in model folder,
2. Rows in this table correspond to objects of the class—a particular user is represented as an object of class user.
3. By using this object's attributes we can set and get the individual columns.
So an ORM layer maps tables to classes, rows to objects and columns to attributes of that object(methods).
Class methods are used to perform table-level operations.
Instance methods are used to perform operations on the individual rows.
It is all taken care by ActiveRecord class.
Zend installation steps
Zend framework requires php5 or later
1)Download the zend framework package from http://framework.zend.com/download/latest
2)Unzip the package and place it where ever you want
Here in my system /usr/var/zendframework
3)Open the zendframework/library and copy the folder path.
4)Open the php.ini file and set the include_path for this libray
Here in my system I have found include_path like include_path = ".:/usr/share/php5:/usr/share/pear , And i added the zend library path like include_path = ".:/usr/share/php5:/usr/share/pear:/var/www/ZendFramework/library"
5)Now we have create alias for zf.sh (self executable file in console for linux) ,To do this run the fallowing command in terminal.
alias zf.sh= /var/www/ZendFramework/bin
6)Run the fallowing command in terminal
zf create project myproject
7)Now directory structure has been created with the name myproject.In this directory you will be given with some sub directories in order to develop your application(project).
1)Download the zend framework package from http://framework.zend.com/download/latest
2)Unzip the package and place it where ever you want
Here in my system /usr/var/zendframework
3)Open the zendframework/library and copy the folder path.
4)Open the php.ini file and set the include_path for this libray
Here in my system I have found include_path like include_path = ".:/usr/share/php5:/usr/share/pear , And i added the zend library path like include_path = ".:/usr/share/php5:/usr/share/pear:/var/www/ZendFramework/library"
5)Now we have create alias for zf.sh (self executable file in console for linux) ,To do this run the fallowing command in terminal.
alias zf.sh= /var/www/ZendFramework/bin
6)Run the fallowing command in terminal
zf create project myproject
7)Now directory structure has been created with the name myproject.In this directory you will be given with some sub directories in order to develop your application(project).
PHP Design Patterns
Design pattern is nothing but how a civil engineer planed before start constructing any building i.e where a kitchen is, and how it will be, where temple room, where dining hall etc., In a software engineering design pattern is nothing but a blueprint for your software to avoid tight coupling of modules means when you modify some code in one module which doesn't take effect on other modules. The most usefull and common design patterns are
Sigleton pattern: Used to restrict instantiation of a class to one object only. The real time use of this pattern is connection to database is opened only once.
Factory pattern: Used to implement loosecoupled modules.
Observer pattern: Used to maintain all dependents and notifies them automatically when any change made
Sigleton pattern: Used to restrict instantiation of a class to one object only. The real time use of this pattern is connection to database is opened only once.
Factory pattern: Used to implement loosecoupled modules.
Observer pattern: Used to maintain all dependents and notifies them automatically when any change made
Friday, February 12, 2010
Generating rsa public and private keys in linux
Open terminal and run ssh-keygen with below optional params
$ ssh-keygen -t rsa -C "venkatadapa@gmail.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/venkat/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/venkat/.ssh/id_rsa.
Your public key has been saved in /home/venkat/.ssh/id_rsa.pub.
The key fingerprint is:
01:0f:f4:3b:ca:85:d6:17:a1:7d:f0:68:9d:f0:a2:db venkatadapa@gmail.com
Use "ssh-add path/to/my_key" If you want to change the path of the keys to store at Your public key has been saved in /home/venkat/.ssh/id_rsa.pub.
To know more about passphrases just visit http://help.github.com/working-with-key-passphrases/
After finished the above steps an hidden .ssh folder was created in that specified path containing with files id_rsa,id_rsa.pub and known_hosts. id_rsa contains private key. id_rsa_pub contains your public key.
You can use this key for your github account to manage your data from your computer.
$ ssh-keygen -t rsa -C "venkatadapa@gmail.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/venkat/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/venkat/.ssh/id_rsa.
Your public key has been saved in /home/venkat/.ssh/id_rsa.pub.
The key fingerprint is:
01:0f:f4:3b:ca:85:d6:17:a1:7d:f0:68:9d:f0:a2:db venkatadapa@gmail.com
Use "ssh-add path/to/my_key" If you want to change the path of the keys to store at Your public key has been saved in /home/venkat/.ssh/id_rsa.pub.
To know more about passphrases just visit http://help.github.com/working-with-key-passphrases/
After finished the above steps an hidden .ssh folder was created in that specified path containing with files id_rsa,id_rsa.pub and known_hosts. id_rsa contains private key. id_rsa_pub contains your public key.
You can use this key for your github account to manage your data from your computer.
Tuesday, February 9, 2010
Real time usage of polymorphism concept
One of the basic concepts of Object Oriented Programming is that we use polymorphism instead of conditional logic when we want to change runtime behaviour of a program. The Open Closed Principle clarifies this idea by suggesting that software should be open to extension (means can be flexible for adding new features), but closed to modification (means not able change the existng functionality).
Conditional assignment operator in Ruby
Hi, ||= is an operator for assigning value to a variable conditionally in Ruby. See the example below
Here a @secrete is an instance variable contains array of four values. End user guess that values along with the order
If value found and at same position you will see T, If found but not at same position output is 't'. If your guessed value is not at all in the @secrete list your output is F
<%
@secret = %w[chiru ballaya nag venki]
def guess(guess) #where guess is an array of having four values
result = [nil,nil,nil,nil] #array with four nil values
guess.each_with_index do |value, index|
if @secret[index] == value
result[index] = "T"
elsif @secret.include?(value)
result[@secret.index(value)] ||= "t" # ||= is conditional assignment operator, means which will only assign the value if it is currently nil or false. It will not replace if it is already have any value in that variable.
end
end
result.compact.sort.join
end
end
end
guess(%w[chiru nag ballay venki]) #here you are guessing the names and orders.
%>
#output TttT
#Chiru and Venki are exists and also at same positions.
#nag and ballayya are exists but not at same positions.
Here a @secrete is an instance variable contains array of four values. End user guess that values along with the order
If value found and at same position you will see T, If found but not at same position output is 't'. If your guessed value is not at all in the @secrete list your output is F
<%
@secret = %w[chiru ballaya nag venki]
def guess(guess) #where guess is an array of having four values
result = [nil,nil,nil,nil] #array with four nil values
guess.each_with_index do |value, index|
if @secret[index] == value
result[index] = "T"
elsif @secret.include?(value)
result[@secret.index(value)] ||= "t" # ||= is conditional assignment operator, means which will only assign the value if it is currently nil or false. It will not replace if it is already have any value in that variable.
end
end
result.compact.sort.join
end
end
end
guess(%w[chiru nag ballay venki]) #here you are guessing the names and orders.
%>
#output TttT
#Chiru and Venki are exists and also at same positions.
#nag and ballayya are exists but not at same positions.
Monday, February 8, 2010
Files upload without any plugins in ROR
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
01.FILE_EXTENSIONS = [".wav",".mp3",".gsm",".pdf"] #Allowed file types
02.
03.FILE_TEMP_PATH="#{RAILS_ROOT}/public/temp/" #Where file is initialy uploaded
04.
05.FILE_MIME_EXTENSIONS =["audio/x-wav","audio/mpeg","audio/gsm","audio /x-gsm","application/pdf"] #Allowed file types
06.
07.FILE_ROOT_PATH= "#{RAILS_ROOT}/public/saved/" #Where file is uploaded permanently
08.
09.FILE_MAXIMUM_SIZE_FOR_FILE=1048576 #Maximum Size (1MB) define in bytes
#In model
01.before_save :save_file
02.
03.attr_accessor :file_data
04.
05.def get_filename
06.#define your rename file method
07.t = Time.now
08."file_#{t.strftime("%Y%m%d%H%M")}"
09.end
10.
11.def save_file
12.begin
13.# No update necessary
14.return true if self.file_data.blank?
15.filename = get_filename
16.return false if filename.nil?
17.
18.extension = File.extname(self.file_data.original_filename)
19.if extension.nil?
20.errors.add(:file_data,"Wrong Extension")
21.return false
22.end
23.
24.# Check if the FILE_TEMP_PATH is created, if not try to create
25.if !File.directory?(FILE_TEMP_PATH)
26.File.makedirs(FILE_TEMP_PATH)
27.end
28.
29.temp_source = File.join(FILE_TEMP_PATH, filename)
30.temp_source << extension
31.final_source = File.join(FILE_ROOT_PATH, filename)
32.final_source << extension
33.
34.File.open(temp_source, "wb") { |f| f.write(self.file_data.read)}
35.
36.size=File.size(temp_source)
37.extension = File.extname(temp_source)
38.mime_extension=File.mime_type?(temp_source)
39.if FILE_MIME_EXTENSIONS.include?(mime_extension) == false
40.logger.error("Trying to upload file with mime-type: #{mime_extension} ")
41.errors.add(:file_data,"Only wav, mp3,gsm and pdf files are allowed")
42.return false
43.end
44.if FILE_EXTENSIONS.include?(extension) == false
45.logger.error("Trying to upload file with extension: #{extension} ")
46.errors.add(:file_data,"File extension should be wav, mp3, gsm or pdf")
47.return false
48.end
49.if size > FILE_MAXIMUM_SIZE_FOR_FILE
50.logger.error("Trying to upload file with size: #{size} ")
51.errors.add(:file_data,"File should not be more than #{FILE_MAXIMUM_SIZE_FOR_FILE} bytes")
52.return false
53.end
54.if valid? #Upload in permanent folder
55.logger.error("#{self.errors.to_xml}")
56.self.file=filename
57.FileUtils.copy_file(temp_source,final_source)
58.FileUtils.rm(temp_source) if File.exists?(temp_source)
59.return true
60.else
61.errors.add(:file_data,"Invalid file format")
62.FileUtils.rm(temp_source) #Remove temp file
63.return false
64.end
65.rescue => e
66.logger.error(e)
67.errors.add(:file_data,"Invalid file format")
68.return false
69.end
70.
71.end
# In View form
1.<% form_for :obj_name,:html=>{:multipart=>true} do |f| %>
2.
3.<%= f.error_messages %>
4.
5.File: <%=f.file_field :file_data%>
6.<%= f.submit "Create" %>
7.
8.<% end %>
* 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
01.FILE_EXTENSIONS = [".wav",".mp3",".gsm",".pdf"] #Allowed file types
02.
03.FILE_TEMP_PATH="#{RAILS_ROOT}/public/temp/" #Where file is initialy uploaded
04.
05.FILE_MIME_EXTENSIONS =["audio/x-wav","audio/mpeg","audio/gsm","audio /x-gsm","application/pdf"] #Allowed file types
06.
07.FILE_ROOT_PATH= "#{RAILS_ROOT}/public/saved/" #Where file is uploaded permanently
08.
09.FILE_MAXIMUM_SIZE_FOR_FILE=1048576 #Maximum Size (1MB) define in bytes
#In model
01.before_save :save_file
02.
03.attr_accessor :file_data
04.
05.def get_filename
06.#define your rename file method
07.t = Time.now
08."file_#{t.strftime("%Y%m%d%H%M")}"
09.end
10.
11.def save_file
12.begin
13.# No update necessary
14.return true if self.file_data.blank?
15.filename = get_filename
16.return false if filename.nil?
17.
18.extension = File.extname(self.file_data.original_filename)
19.if extension.nil?
20.errors.add(:file_data,"Wrong Extension")
21.return false
22.end
23.
24.# Check if the FILE_TEMP_PATH is created, if not try to create
25.if !File.directory?(FILE_TEMP_PATH)
26.File.makedirs(FILE_TEMP_PATH)
27.end
28.
29.temp_source = File.join(FILE_TEMP_PATH, filename)
30.temp_source << extension
31.final_source = File.join(FILE_ROOT_PATH, filename)
32.final_source << extension
33.
34.File.open(temp_source, "wb") { |f| f.write(self.file_data.read)}
35.
36.size=File.size(temp_source)
37.extension = File.extname(temp_source)
38.mime_extension=File.mime_type?(temp_source)
39.if FILE_MIME_EXTENSIONS.include?(mime_extension) == false
40.logger.error("Trying to upload file with mime-type: #{mime_extension} ")
41.errors.add(:file_data,"Only wav, mp3,gsm and pdf files are allowed")
42.return false
43.end
44.if FILE_EXTENSIONS.include?(extension) == false
45.logger.error("Trying to upload file with extension: #{extension} ")
46.errors.add(:file_data,"File extension should be wav, mp3, gsm or pdf")
47.return false
48.end
49.if size > FILE_MAXIMUM_SIZE_FOR_FILE
50.logger.error("Trying to upload file with size: #{size} ")
51.errors.add(:file_data,"File should not be more than #{FILE_MAXIMUM_SIZE_FOR_FILE} bytes")
52.return false
53.end
54.if valid? #Upload in permanent folder
55.logger.error("#{self.errors.to_xml}")
56.self.file=filename
57.FileUtils.copy_file(temp_source,final_source)
58.FileUtils.rm(temp_source) if File.exists?(temp_source)
59.return true
60.else
61.errors.add(:file_data,"Invalid file format")
62.FileUtils.rm(temp_source) #Remove temp file
63.return false
64.end
65.rescue => e
66.logger.error(e)
67.errors.add(:file_data,"Invalid file format")
68.return false
69.end
70.
71.end
# In View form
1.<% form_for :obj_name,:html=>{:multipart=>true} do |f| %>
2.
3.<%= f.error_messages %>
4.
5.File: <%=f.file_field :file_data%>
6.<%= f.submit "Create" %>
7.
8.<% end %>
Subscribe to:
Posts (Atom)