Class: EasyS3

Inherits:
Object
  • Object
show all
Defined in:
lib/easy-s3.rb,
lib/easy-s3/version.rb

Defined Under Namespace

Classes: DirectoryDoesNotExist, FileNotFound, MissingOptions

Constant Summary collapse

VERSION =
'0.2.0'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dir_name, options = {}) ⇒ EasyS3

Returns a new instance of EasyS3.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/easy-s3.rb', line 11

def initialize(dir_name, options={})
  options[:access_key_id]     ||= Fog.credentials[:aws_access_key_id]
  options[:secret_access_key] ||= Fog.credentials[:aws_secret_access_key]

  Fog.credentials = {
      aws_access_key_id:      options[:access_key_id],
      aws_secret_access_key:  options[:secret_access_key]
  }

  begin
    @fog = Fog::Storage.new(provider: 'AWS')
    @dir = @fog.directories.get(dir_name)
  rescue ArgumentError
    raise MissingOptions, 'access_key_id or secret_access_key'
  rescue Excon::Errors::MovedPermanently, 'Expected(200) <=> Actual(301 Moved Permanently)'
    raise DirectoryDoesNotExist, dir_name
  end
  raise DirectoryDoesNotExist, dir_name if @dir.nil?

  true
end

Instance Attribute Details

#dirObject (readonly)

Returns the value of attribute dir.



9
10
11
# File 'lib/easy-s3.rb', line 9

def dir
  @dir
end

#fogObject (readonly)

Returns the value of attribute fog.



9
10
11
# File 'lib/easy-s3.rb', line 9

def fog
  @fog
end

Instance Method Details

#create_file(file_path, options = {}) ⇒ Object

Create private or public file into directory



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/easy-s3.rb', line 34

def create_file(file_path, options={})
  options[:digest] ||= false
  options[:public] ||= false

  begin
    file = File.open(file_path)
  rescue
    raise FileNotFound, file_path
  end

  filename = "#{File.basename(file_path)}"
  filename += "_#{Digest::SHA1.hexdigest(File.basename(file_path))}" if options[:digest]

  file = @dir.files.create(
      key:    filename,
      body:   file,
      public: options[:public]
  )

  return file.public_url if options[:public] && file.public_url

  file.url((Time.now + 3600).to_i) # 1 hour
end

#delete_file(url) ⇒ Object

Delete file by url



59
60
61
62
63
# File 'lib/easy-s3.rb', line 59

def delete_file(url)
  file_name = get_filename_by_url(url)
  return false unless @dir.files.head(file_name)
  @dir.files.get(file_name).destroy
end

#filesObject

Get all files into directory



66
67
68
# File 'lib/easy-s3.rb', line 66

def files
  @dir.files.all
end