OSDN Git Service

fix: heroku
[pettanr/pettanr.git] / lib / s3_picture.rb
1 require 'picture_io'
2 class PictureIO
3   Aws.config.update(
4     region: Rails.application.secrets.aws_region, 
5     credentials: Aws::Credentials.new(
6       Rails.application.secrets.aws_access_key_id, 
7       Rails.application.secrets.aws_secret_access_key
8     )
9   )
10   class S3Picture
11     @@client = Aws::S3::Client.new
12     
13     def initialize host_dir = 'pettanr', base_dir = ''
14       @host_dir = host_dir
15       @base_dir = base_dir
16       s3 = Aws::S3::Resource.new
17       @bucket = s3.bucket(@host_dir)
18     end
19     
20     def self.client
21       @@client
22     end
23     
24     def bucket
25       @bucket
26     end
27     
28     def host_dir
29       @host_dir
30     end
31     
32     def host_dir=(d)
33       @host_dir = d
34     end
35     
36     def self.subdirs
37       ['', 'v', 'h', 'vh', 'thumbnail']
38     end
39     
40     def dir(subdir = nil)
41       sd = if subdir.to_s.empty?
42         ''
43       else
44         subdir.to_s + '/'
45       end
46       @base_dir + '/' + sd
47     end
48     
49     def exist?(filename, subdir = nil)
50       res = true
51       begin
52         res = self.bucket.object(dir(subdir) + filename).exists?
53       rescue
54         raise PictureIO::Error
55       end
56       res
57     end
58     
59     def put(bindata, filename, subdir = nil)
60       res = true
61       begin
62         @@client.put_object(bucket: self.host_dir, key: dir(subdir) + filename, body: bindata)
63       rescue
64         raise PictureIO::Error
65       end
66       res
67     end
68     
69     def get(filename, subdir = nil)
70       bindata = ''
71       begin
72         @@client.get_object(bucket: self.host_dir, key: dir(subdir) + filename) do |st|
73           bindata += st if st
74         end
75       rescue
76         raise PictureIO::Error
77       end
78       bindata
79     end
80     
81     def delete(filename, subdir = nil)
82       res = true
83       begin
84         @@client.delete_object(bucket: self.host_dir, key: dir(subdir) + filename)
85       rescue
86         raise PictureIO::Error
87       end
88       res
89   end
90     
91   end
92 end