Class: Upyun::Rest

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/upyun/rest.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Utils

included, #md5

Constructor Details

#initialize(bucket, operator, password, options = {timeout: 60}, endpoint = Upyun::ED_AUTO) ⇒ Rest

Returns a new instance of Rest.



11
12
13
14
15
16
17
# File 'lib/upyun/rest.rb', line 11

def initialize(bucket, operator, password, options={timeout: 60}, endpoint=Upyun::ED_AUTO)
  @bucket = bucket
  @operator = operator
  @password = md5(password)
  @options = options
  @endpoint = endpoint
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



9
10
11
# File 'lib/upyun/rest.rb', line 9

def options
  @options
end

Instance Method Details

#delete(path) ⇒ Object



45
46
47
# File 'lib/upyun/rest.rb', line 45

def delete(path)
  request(:delete, path)
end

#get(path, savepath = nil) ⇒ Object



31
32
33
34
35
36
37
38
# File 'lib/upyun/rest.rb', line 31

def get(path, savepath=nil)
  res = request(:get, path)
  return res if res.is_a?(Hash) || !savepath

  dir = File.dirname(savepath)
  FileUtils.mkdir_p(dir) unless File.directory?(dir)
  File.write(savepath, res)
end

#getinfo(path) ⇒ Object



40
41
42
43
# File 'lib/upyun/rest.rb', line 40

def getinfo(path)
  hds = request(:head, path)
  hds = hds.key?(:error) ? hds : format_info(hds)
end

#getlist(path = '/') ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/upyun/rest.rb', line 53

def getlist(path='/')
  res = request(:get, path)
  return res if res.is_a?(Hash)

  res.split('\n').map do |f|
    attrs = f.split('\t')
    {
      name: attrs[0],
      type: attrs[1] == 'N' ? :file : :folder,
      length: attrs[2].to_i,
      last_modified: attrs[3].to_i
    }
  end
end

#mkdir(path) ⇒ Object



49
50
51
# File 'lib/upyun/rest.rb', line 49

def mkdir(path)
  request(:post, path, {headers: {folder: true, mkdir: true}})
end

#put(path, file, headers = {}) ⇒ Object

Raises:

  • (ArgumentError)


19
20
21
22
23
24
25
26
27
28
29
# File 'lib/upyun/rest.rb', line 19

def put(path, file, headers={})
  raise ArgumentError, "'file' is not an instance of String" unless file.is_a?(String)
  headers = headers.merge({'mkdir' => true}) unless headers.key?('mkdir')
  options = if File.file?(file)
              {body: File.read(file), length: File.size(file), headers: headers}
            else
              {body: file, length: file.length, headers: headers}
            end

  request(:put, path, options)
end

#usageObject



68
69
70
71
72
73
74
75
# File 'lib/upyun/rest.rb', line 68

def usage
  res = request(:get, '/', {query: 'usage'})
  return res if res.is_a?(Hash)

  # RestClient has a bug, body.to_i returns the code instead of body,
  # see more on https://github.com/rest-client/rest-client/pull/103
  res.dup.to_i
end