This topic describes how to use Object Storage Service (OSS) SDK for Ruby in Rails applications to list buckets, upload objects, and download objects.
Preparations
To use the OSS SDK for Ruby in a Rails application, add the following dependency to the Gemfile file.
gem 'aliyun-sdk', '~> 0.3.0
Add the following dependency when you use OSS SDK for Ruby:
require 'aliyun/oss'
Integration with Rails
You can perform the following steps to integrate OSS SDK for Ruby with Rails:
Create a project.
Install Rails and create a Rails application named oss-manager.
gem install rails rails new oss-managerNoteIn this example, the oss-manager application is a management tool for OSS objects. It can list all buckets, list objects in a bucket by directory, upload objects, and download objects.
Use git to manage the project code.
cd oss-manager git init git add . git commit -m "init project"
Add the SDK dependency.
Edit
oss-manager/Gemfileto add the SDK dependency.gem 'aliyun-sdk', '~> 0.3.0'In the
oss-manager/directory, runbundle install.Save the changes.
git add . git commit -m "add aliyun-sdk dependency"
Initialize an OSSClient instance
To avoid initialization each time you use an OSSClient instance in the project, we recommend that you create an initialization file in the project.
# oss-manager/config/initializers/aliyun_oss_init.rb
require 'aliyun/oss'
module OSS
def self.client
unless @client
Aliyun::Common::Logging.set_log_file('./log/oss_sdk.log')
@client = Aliyun::OSS::Client.new(
endpoint:
Rails.application.secrets.aliyun_oss['endpoint'],
access_key_id:
Rails.application.secrets.aliyun_oss['access_key_id'],
access_key_secret:
Rails.application.secrets.aliyun_oss['access_key_secret']
)
end
@client
end
end The preceding code is stored in the rails/ directory of the installation path of OSS SDK for Ruby. You can use the OSSClient instance in the project after initialization.
buckets = OSS.client.list_buckets The endpoint, access_key_id, and access_key_secret values are saved in the oss-manager/conf/secrets.yml file.
development:
secret_key_base: xxxx
aliyun_oss:
endpoint: xxxx
access_key_id: aaaa
access_key_secret: bbbb Save the changes.
git add .
git commit -m "add aliyun-sdk initializer" List all buckets
You can perform the following steps to list all buckets:
Use Rails to generate the controller to manage buckets.
rails g controller buckets indexThe following files are generated in the
oss-managerfolder.app/controller/buckets_controller.rb: contains the logical code related to buckets.
app/views/buckets/index.html.erb: contains the code used to display the content related to buckets.
app/helpers/buckets_helper.rb: defines the auxiliary functions.
Edit `buckets_controller.rb`. Call the OSS client and save the result of the
list_bucketsoperation to the@bucketsvariable.class BucketsController < ApplicationController def index @buckets = OSS.client.list_buckets end endModify the views/buckets/index.html.erb file to list the buckets.
<h1>Buckets</h1> <table class="table table-striped"> <tr> <th>Name</th> <th>Location</th> <th>CreationTime</th> </tr> <% @buckets.each do |bucket| %> <tr> <td><%= link_to bucket.name, bucket_objects_path(bucket.name) %></td> <td><%= bucket.location %></td> <td><%= bucket.creation_time.localtime.to_s %></td> </tr> <% end %> </table>In `app/helpers/buckets_helper.rb`, define the
bucket_objects_pathhelper function.module BucketsHelper def bucket_objects_path(bucket_name) "/buckets/#{bucket_name}/objects" end endAfter you complete the preceding steps, you can list all buckets.
You also need to configure Rails routing so that the address entered in the browser calls the correct logic. Edit
config/routes.rband add the following content.resources :buckets do resources :objects endIn the
oss-manager/directory, runrails sto start the Rails server. Then, navigate tohttp://localhost:3000/buckets/in your browser to view the bucket list.Save the changes.
git add . git commit -m "add list buckets feature"
List all objects in a bucket by directory
You can perform the following steps to list all objects in a bucket by directory:
Generate a controller to manage objects.
rails g controller objects indexModify the app/controllers/objects_controller.rb file.
class ObjectsController < ApplicationController def index @bucket_name = params[:bucket_id] @prefix = params[:prefix] @bucket = OSS.client.get_bucket(@bucket_name) @objects = @bucket.list_objects(:prefix => @prefix, :delimiter => '/') end endYou can obtain the bucket name from the parameters in the URL. Add a prefix to list objects by directory and call the list_object operation of the OSSClient instance to obtain the object list.
NoteIn this example, objects whose names contain the specified prefix and a forward slash (/) as a delimiter are obtained. For more information, see Overview.
Modify the app/views/objects/index.html.erb file.
<h1>Objects in <%= @bucket_name %></h1> <p> <%= link_to 'Upload file', new_object_path(@bucket_name, @prefix) %></p> <table class="table table-striped"> <tr> <th>Key</th> <th>Type</th> <th>Size</th> <th>LastModified</th> </tr> <tr> <td><%= link_to '../', with_prefix(upper_dir(@prefix)) %></td> <td>Directory</td> <td>N/A</td> <td>N/A</td> </tr> <% @objects.each do |object| %> <tr> <% if object.is_a?(Aliyun::OSS::Object) %> <td><%= link_to remove_prefix(object.key, @prefix), @bucket.object_url(object.key) %></td> <td><%= object.type %></td> <td><%= number_to_human_size(object.size) %></td> <td><%= object.last_modified.localtime.to_s %></td> <% else %> <td><%= link_to remove_prefix(object, @prefix), with_prefix(object) %></td> <td>Directory</td> <td>N/A</td> <td>N/A</td> <% end %> </tr> <% end %> </table>Objects are listed by directory based on the following logic:
'../' always refers to the parent directory.
Common prefixes are listed as directories.
Objects are displayed as files.
The preceding code uses helper functions such as
with_prefixandremove_prefix. These helper functions are defined in `app/helpers/objects_helper.rb`.module ObjectsHelper def with_prefix(prefix) "?prefix=#{prefix}" end def remove_prefix(key, prefix) key.sub(/^#{prefix}/, '') end def upper_dir(dir) dir.sub(/[^\/]+\/$/, '') if dir end def new_object_path(bucket_name, prefix = nil) "/buckets/#{bucket_name}/objects/new/#{with_prefix(prefix)}" end def objects_path(bucket_name, prefix = nil) "/buckets/#{bucket_name}/objects/#{with_prefix(prefix)}" end endWhen you are finished, run
rails s. Then, navigate tohttp://localhost:3000/buckets/my-bucket/objects/in your browser to view the file list.Save the changes.
git add . git commit -m "add list objects feature"
Download objects
In the steps in the preceding section, URLs are added to the objects. You can use the URL of an object to download the object.
<td><%= link_to remove_prefix(object.key, @prefix),
@bucket.object_url(object.key) %></td> You can also use bucket.object_url to generate a temporary URL for a file. For more information, see Download files.
Upload objects
To upload objects in Rails applications on the server, you can use the following methods:
Upload objects in a similar manner as normal upload. You need to upload an object to the Rails server. Then, the Rails server uploads the object to OSS.
Upload objects using the forms and temporary credentials generated by the server.
In `app/controllers/objects_controller.rb`, add the
#newmethod to generate the upload form.def new @bucket_name = params[:bucket_id] @prefix = params[:prefix] @bucket = OSS.client.get_bucket(@bucket_name) @options = { :prefix => @prefix, :redirect => 'http://localhost:3000/buckets/' } endModify the app/views/objects/new.html.erb file.
<h2>Upload object</h2> <%= upload_form(@bucket, @options) do %> <table class="table table-striped"> <tr> <td><label>Bucket:</label></td> <td><%= @bucket.name %></td> </tr> <tr> <td><label>Prefix:</label></td> <td><%= @prefix %></td> </tr> <tr> <td><label>Select file:</label></td> <td><input type="file" name="file" style="display:inline" /></td> </tr> <tr> <td colspan="2"> <input type="submit" class="btn btn-default" value="Upload" />  Noteupload_formis a helper function provided by the SDK that you can use to easily generate an upload form. This helper function is stored in `rails/aliyun_oss_helper.rb`. Copy it to the `app/helpers/` directory. After that, runrails sand navigate tohttp://localhost:3000/buckets/my-bucket/objects/newto upload files to OSS.Save the changes.
git add . git commit -m "add upload object feature"
Add styles
You can perform the following steps to add styles to the interface of the Rails application:
Download Bootstrap. After you decompress the package, copy the
bootstrap.min.cssfile to theapp/assets/stylesheets/directory.Modify
app/views/layouts/application.html.erband replace theyieldline with the following code.<div id="main"> <%= yield %> </div>For each page, add a
<div>with the ID `main`. Then, modifyapp/assets/stylesheets/application.cssand add the following content.body { text-align: center; } div#main { text-align: left; width: 1024px; margin: 0 auto; }
For the complete demo code, visit OSS Rails Demo.