# # Author:: Jamie Winsor () # Copyright:: 2011, En Masse Entertainment, Inc # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module EnMasse module Dragonfly module MogileFS class DataStore include ::Dragonfly::Configurable configurable_attr :hosts configurable_attr :domain, 'dragonfly' configurable_attr :klass, nil configurable_attr :timeout configurable_attr :readonly configurable_attr :db_backend configurable_attr :remote_url configurable_attr :use_filesystem, true def initialize(options = {}) self.hosts = options[:hosts] self.domain = options[:domain] self.klass = options[:klass] if options[:klass] self.timeout = options[:timeout] if options[:timeout] self.readonly = options[:readonly] if options[:readonly] self.db_backend = options[:db_backend] if options[:db_backend] self.remote_url = options[:remote_url] if options[:remote_url] end def store(temp_object, options = {}) meta = options[:meta] || {} uid = options[:key] || generate_uid(meta[:name] || temp_object.original_filename || 'file') if use_filesystem temp_object.file do |fp| connection.store_file(uid, self.klass, fp) end else connection.store_file(uid, self.klass, temp_object.data) end store_meta_data(uid, meta) uid end def retrieve(uid) [ connection.get_file_data(uid), retrieve_meta_data(uid) ] rescue ::MogileFS::Backend::UnknownKeyError => e raise ::Dragonfly::DataStorage::DataNotFound, "#{e} - #{uid}" end def destroy(uid) connection.delete(uid) rescue ::MogileFS::Backend::UnknownKeyError => e raise ::Dragonfly::DataStorage::DataNotFound, "#{e} - #{uid}" end def connection options = { :hosts => self.hosts, :domain => self.domain } options[:timeout] = self.timeout if self.timeout options[:readonly] = self.readonly if self.readonly options[:db_backend] = self.db_backend if self.db_backend @connection ||= ::MogileFS::MogileFS.new(options) end def url_for(uid, options = {}) "#{remote_url}/#{uid}" end private def generate_uid(name) "#{Time.now.strftime '%Y/%m/%d/%H/%M/%S'}/#{rand(1000)}/#{name.gsub(/[^\w.]+/, '_')}" end def meta_data_key(data_key) "#{data_key}.meta" end def store_meta_data(data_key, meta) connection.store_content(meta_data_key(data_key), self.klass, Marshal.dump(meta)) end def retrieve_meta_data(data_key) data = connection.get_file_data(meta_data_key(data_key)) data ? Marshal.load(data) : {} end end end end end