Skip to content

Instantly share code, notes, and snippets.

@special-k
Last active December 17, 2015 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save special-k/5644071 to your computer and use it in GitHub Desktop.
Save special-k/5644071 to your computer and use it in GitHub Desktop.
Openstack swift using
require 'yajl'
require "rest-client"
require "digest/md5"
module Swift
class Object
attr_reader :name, :container
def initialize container, name
@container = container
@name = name
end
def write file, params = { 'ETag' => Digest::MD5.hexdigest(file) }
container.put( name, file, params ).code == 201
end
end
class Container
attr_reader :name, :connection
def initialize connection, name
@connection = connection
@name = name
end
def objects
Yajl::Parser.parse connection.get( name ).body
end
def object name
Object.new self, name
end
def delete_object object_name
delete( object_name ).code == 204
end
def put object_name, file = nil, params = {}
connection.put( "#{name}/#{ object_name }", file, params )
end
def delete v
connection.delete "#{name}/#{ v }"
end
end
class Connection
attr_reader :temp_url, :auth_token
def initialize( user: String, key: String, auth_url: String )
response = RestClient.get auth_url, x_auth_user: user, x_auth_key: key
@temp_url = response.headers[:x_storage_url]
@auth_token = response.headers[:x_auth_token]
end
def container name
Container.new self, name
end
def delete_container container_name
delete( container_name ).code == 204
end
def create_container container_name
put( container_name ).code == 201
end
def get v
RestClient.get "#{ temp_url }/#{v}", x_auth_token: auth_token, accept: 'json'
end
def delete v
RestClient.delete "#{ temp_url }/#{v}", x_auth_token: auth_token, accept: 'json'
end
def put v, file = nil, params = {}
RestClient.put "#{ temp_url }/#{v}", file, params.merge(x_auth_token: auth_token, accept: 'json')
end
end
end
#using
swift = Swift::Connection.new user: '<user>', key: '<key>', auth_url: '<auth_url>'
c = swift.container( 'assets' )
o = c.object('file')
o.write File.new('local_file').read, 'text/plain; charset=utf-8'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment