Class: COS::Resource

Inherits:
Object
  • Object
show all
Defined in:
lib/cos/resource.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bucket, path, options = {}) ⇒ Resource

实例化COS资源迭代器



10
11
12
13
14
15
16
17
# File 'lib/cos/resource.rb', line 10

def initialize(bucket, path, options = {})
  @bucket      = bucket
  @path        = path
  @more        = options
  @results     = Array.new
  @dir_count   = 0
  @file_count  = 0
end

Instance Attribute Details

#bucketObject (readonly)

Returns the value of attribute bucket.



7
8
9
# File 'lib/cos/resource.rb', line 7

def bucket
  @bucket
end

#dir_countObject (readonly)

Returns the value of attribute dir_count.



7
8
9
# File 'lib/cos/resource.rb', line 7

def dir_count
  @dir_count
end

#file_countObject (readonly)

Returns the value of attribute file_count.



7
8
9
# File 'lib/cos/resource.rb', line 7

def file_count
  @file_count
end

#pathObject (readonly)

Returns the value of attribute path.



7
8
9
# File 'lib/cos/resource.rb', line 7

def path
  @path
end

Instance Method Details

#fetchObject

获取列表



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/cos/resource.rb', line 39

def fetch
  client = bucket.client
  resp = client.api.list(path, @more.merge({bucket: bucket.bucket_name}))

  # 遍历结果转换为对应的对象
  @results = resp[:infos].map do |r|
    if r[:filesize].nil?
      # 目录
      COSDir.new(r.merge({
                             bucket: bucket,
                             path: Util.get_list_path(path, r[:name])
                         }))
    else
      # 文件
      COSFile.new(r.merge({
                              bucket: bucket,
                              path: Util.get_list_path(path, r[:name], true)
                          }))
    end
  end || []

  @dir_count  = resp[:dir_count]
  @file_count = resp[:file_count]

  @more[:context]  = resp[:context]
  @more[:has_more] = resp[:has_more]
end

#nextObject

实现迭代器



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/cos/resource.rb', line 20

def next
  loop do
    # 从接口获取下一页结果
    fetch_more if @results.empty?

    # 取出结果
    r = @results.shift
    break unless r

    yield r
  end
end

#to_enumObject

返回迭代器



34
35
36
# File 'lib/cos/resource.rb', line 34

def to_enum
  self.enum_for(:next)
end