Module: Cms::S3::Attachment

Defined in:
lib/bcms_s3/s3_module.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(model_class) ⇒ Object



86
87
88
89
# File 'lib/bcms_s3/s3_module.rb', line 86

def self.included(model_class)
  model_class.alias_method_chain :set_file_location, :s3
  model_class.alias_method_chain :write_temp_file_to_storage_location, :s3
end

Instance Method Details

#set_file_location_with_s3Object



90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/bcms_s3/s3_module.rb', line 90

def set_file_location_with_s3
  unless temp_file.blank? 
    prefix = temp_file.original_filename.sub(/\..+$/,'') 
    if temp_file.original_filename =~ /.+(\..+)$/ 
      suffix = $1 
    else 
      suffix = "" 
    end 
    new_filename = "#{prefix}-#{ActiveSupport::SecureRandom.hex(4)}#{suffix}" 
    self.file_location = "#{Time.now.strftime("%Y/%m/%d")}/#{new_filename}" 
  end 
end

#write_temp_file_to_storage_location_with_s3Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/bcms_s3/s3_module.rb', line 102

def write_temp_file_to_storage_location_with_s3
  unless temp_file.blank?
    FileUtils.mkdir_p File.dirname(full_file_location)  if !Cms::S3.enabled
    if temp_file.local_path

      if Cms::S3.enabled
        s3 = RightAws::S3.new(Cms::S3.options[:access_key_id], Cms::S3.options[:secret_access_key] )
        bucket = s3.bucket(Cms::S3.options[:bucket], true, 'public-read')
        key = RightAws::S3::Key.create(bucket, file_location)
        key.put(temp_file.read,'public-read', {"Content-Type" => file_type})
      else
        FileUtils.copy temp_file.local_path, full_file_location
      end
    else
      open(full_file_location, 'w') {|f| f << temp_file.read }
    end

    if Cms.attachment_file_permission  && !Cms::S3.enabled
      FileUtils.chmod Cms.attachment_file_permission, full_file_location
    end
  end
end