Rails 2.1 Uploads Files

Ruby on Rails 2.1 – File Uploading ”; Previous Next You may have a requirement in which you want your site visitors to upload a file on your server. Rails makes it very easy to handle this requirement. Now, we will proceed with a simple and small Rails project. As usual, let”s start off with a new Rails application called upload. Let”s create a basic structure of the application by using simple rails command. C:ruby> rails -d mysql upload Let”s decide where you would like to save your uploaded files. Assume this is data directory inside your public section. So, create this directory and check the permissions. C:ruby> cd upload C:rubyupload> mkdir uploadpublicdata Our next step will be as usual, to create controller and models. Creating the Model As this is not a database-based application, we can keep whatever name is comfortable to us. Assume we have to create a DataFile model. C:rubyupload> ruby script/generate model DataFile exists app/models/ exists test/unit/ exists test/fixtures/ create app/models/data_file.rb create test/unit/data_file_test.rb create test/fixtures/data_files.yml create db/migrate create db/migrate/001_create_data_files.rb Now, we will create a method called save in data_file.rb model file. This method will be called by the application controller. class DataFile < ActiveRecord::Base def self.save(upload) name = upload[”datafile”].original_filename directory = “public/data” # create the file path path = File.join(directory, name) # write the file File.open(path, “wb”) { |f| f.write(upload[”datafile”].read) } end end The above function will take the CGI object upload and will extract the uploaded file name using the helper function original_filename and finally, it will store the uploaded file into the “public/data” directory. You can call the helper function content_type to know the media type of the uploaded file. Here File is a ruby object and join is a helper function that will concatenate the directory name along with the file name and will return the full file path. Next, to open a file in write mode, we are using the open helper function provided by the File object. Further, we are reading data from the passed data file and writing into output file. Creating Controller Now, let”s create a controller for our upload project − C:rubyupload> ruby script/generate controller Upload exists app/controllers/ exists app/helpers/ create app/views/upload exists test/functional/ create app/controllers/upload_controller.rb create test/functional/upload_controller_test.rb create app/helpers/upload_helper.rb Now, we will create two controller functions. The first function index will call a view file to take user input, and the second function uploadFile takes file information from the user and passes it to the ”DataFile” model. We set the upload directory to the ”uploads” directory we created earlier “directory = ”data””. class UploadController < ApplicationController def index render :file => ”appviewsuploaduploadfile.html.erb” end def uploadFile post = DataFile.save( params[:upload]) render :text => “File has been uploaded successfully” end end Here, we are calling the function defined in the model file. The render function is being used to redirect to view file as well as to display a message. Creating View Finally, we will create a view file uploadfile.rhtml, which we have mentioned in the controller. Populate this file with the following code − <h1>File Upload</h1> <% form_tag ({:action => ”uploadFile”}, :multipart => true) do %> <p><label for=”upload_file”>Select File</label> : <%= file_field ”upload”, ”datafile” %></p> <%= submit_tag “Upload” %> <% end %> Here everything is same what we have explained in the earlier chapters. The only new tag is file_field, which will create a button to select a file from user”s computer. By setting the multipart parameter to true, you ensure that your action properly passes along the binary data from the file. Here, an important point to note is that we have assigned “uploadFile” as the method name in :action, which will be called when you click the Upload button. It will show you a screen as follows − Now, you select a file and upload it. This file will be uploaded into app/public/data directory with the actual file name and a message will be displayed saying that “File has been uploaded successfully”. NOTE − If a file with the same name already exists in your output directory, then it will be overwritten. Files Uploaded from Internet Explorer Internet Explorer includes the entire path of a file in the filename sent, so the original_filename routine will return something like − C:Documents and Filesuser_namePicturesMy File.jpg Instead of just − My File.jpg This is easily handled by File.basename, which strips out everything before the filename. def sanitize_filename(file_name) # get only the filename, not the whole path (from IE) just_filename = File.basename(file_name) # replace all none alphanumeric, underscore or perioids # with underscore just_filename.sub(/[^w.-]/,”_”) end Deleting an Existing File If you want to delete any existing file, it is quite simple. All that you need to do is write the following code − def cleanup File.delete(“#{RAILS_ROOT}/dirname/#{@filename}”) if File.exist?(“#{RAILS_ROOT}/dirname/#{@filename}”) end For a complete detail on File object, you need to go through our Ruby Reference Manual. Print Page Previous Next Advertisements ”;

Rails 2.1 Framework

Ruby on Rails 2.1 – Framework ”; Previous Next A framework is a program, set of programs, and/or code library that writes most of the applications for you. When you use a framework, your job is to write the parts of the application that make it do the specific things you want. When you set out to write a Rails application, leaving aside the configuration and other housekeeping chores, you have to perform three primary tasks − Describe and model your application”s domain − The domain is the universe of your application. The domain may be a music store, a university, a dating service, an address book, or a hardware inventory. So, you have to figure out what”s in it, what entities exist in this universe, and how the items in it relate to each other. This is equivalent to modeling a database structure to keep the entities and their relationship. Specify what can happen in this domain − The domain model is static. You have to make it dynamic. Addresses can be added to an address book. Musical scores can be purchased from music stores. Users can log in to a dating service. Students can register for classes at a university. You need to identify all the possible scenarios or actions that the elements of your domain can participate in. Choose and design the publicly available views of the domain − At this point, you can start thinking in Web-browser terms. Once you”ve decided that your domain has students, and they can register for classes, you can envision a welcome page, a registration page, or a confirmation page, etc. Each of these pages or views shows the user how things stand at a certain point. Based on the above three tasks, Ruby on Rails deals with a Model/View/Controller (MVC) framework. Ruby on Rails MVC Framework The Model View Controller principle divides the work of an application into three separate but closely cooperative subsystems. Model (ActiveRecord) Maintains the relationship between Object and Database and handles validation, association, transactions, and more. This subsystem is implemented in ActiveRecord library, which provides an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables. Active Record also provides dynamic attribute-based finders and a number of other helper methods that make database interaction easy and efficient. View (ActionView) It is a presentation of data in a particular format, triggered by a controller”s decision to present the data. They are script-based templating systems like JSP, ASP, PHP and very easy to integrate with AJAX technology. This subsystem is implemented in ActionView library, which is an Embedded Ruby (ERb) based system for defining presentation templates for data presentation. Every Web connection to a Rails application results in the displaying of a view. ActionView helps in separating the details of presentation from the core business logic of your application. Controller (ActionController) The facility within the application that directs traffic, on the one hand querying the models for specific data, and on the other hand, organizing that data (searching, sorting, massaging it) into a form that fits the needs of a given view. This subsystem is implemented in ActionController, which is a data broker sitting between the ActiveRecord (the database interface) and the ActionView (the presentation engine). Representation of MVC Framework A pictorial representation of Ruby on Rails Framework is given here − Directory Representation of MVC Framework Assuming a standard, default installation over Linux, you can find them like this − tp> cd /usr/local/lib/ruby/gems/1.8/gems tp> ls You will see subdirectories including (but not limited to) the following − actionpack-x.y.z activerecord-x.y.z rails-x.y.z Over a Windows installation, you can find them like this − C:>cd rubylibrubygems1.8gems C:rubylibrubygems1.8gems>dir You will see subdirectories including (but not limited to) the following − actionpack-x.y.z activerecord-x.y.z rails-x.y.z ActionView and ActionController are bundled together under ActionPack. ActiveRecord provides a range of programming techniques and shortcuts for manipulating data from an SQL database. ActionController and ActionView provides facilities for manipulating and displaying that data. Rails ties them all together. Print Page Previous Next Advertisements ”;