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 OSS SDK for Ruby in Rails applications, add the following dependency to Gemfile
:
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-manager
NoteIn 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.
Modify the
oss-manager/Gemfile
file to add the dependency.gem 'aliyun-sdk', '~> 0.3.0'
Run the
bundle install
command inoss-manager/
.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, AccessKey ID, and AccessKey secret are stored 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 index
Generate the following files in the
oss-manager
directory: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.
Modify the buckets_controller.rb file and call the OSSClient instance to save the result of the
list_buckets
operation to the@buckets
variable.class BucketsController < ApplicationController def index @buckets = OSS.client.list_buckets end end
Modify 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>
Define the
bucket_objects_path
auxiliary function in the app/helpers/buckets_helper.rb file.module BucketsHelper def bucket_objects_path(bucket_name) "/buckets/#{bucket_name}/objects" end end
After you complete the preceding steps, you can list all buckets.
You must also configure the routing of Rails to ensure that the address that you enter in the browser can use the correct logic. Modify the
config/routes.rb
file and add the following content:resources :buckets do resources :objects end
Run
rails s
inoss-manager/
to start the Rails server, and then enterhttp://localhost:3000/buckets/
in the 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 index
Modify 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 end
You 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:
The content before the first forward slash (/) in the object name is considered as the upper-level directory.
Common prefixes are listed as directories.
Objects are displayed as files.
The auxiliary functions used in the preceding code, such as
with_prefix
andremove_prefix
, are defined in the app/helpers/objects_helper.rb file.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 end
Run the
rails s
command and enterhttp://localhost:3000/buckets/my-bucket/objects/
in the browser to view the object 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 the object that you want to download. For more information, see Overview.
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 by using the forms and temporary credentials generated by the server.
Add the
#new
method to the app/controllers/objects_controller.rb file to generate upload forms.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/' } end
Modify 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" /> <span>  </span> <%= link_to 'Back', objects_path(@bucket_name, @prefix) %> </td> </tr> </table> <% end %>
Noteupload_form
is an auxiliary function provided by OSS SDK for Ruby. It is used to generate upload forms and is defined in the rails/aliyun_oss_helper.rb file. You must copy the function to the app/helpers/ directory. Then, you can run therails s
command and accesshttp://localhost:3000/buckets/my-bucket/objects/new
to upload objects 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. Decompress the package and copy the
bootstrap.min.css
file extracted from the package to theapp/assets/stylesheets/
directory.Modify the
app/views/layouts/application.html.erb
file and change theyield
line to the following content:<div id="main"> <%= yield %> </div>
Add a
<div>
tag whose ID is main for each page. Modify theapp/assets/stylesheets/application.css
file and 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.