Method: Atech::ObjectStore::File.add_file

Defined in:
lib/atech/object_store/file.rb

.add_file(filename, data = '', options = {}) ⇒ Object

Inserts a new File into the database. Returns a new object if successfully inserted or raises an error. Filename & data must be provided, options options will be added automatically unless specified.

Raises:



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/atech/object_store/file.rb', line 54

def self.add_file(filename, data = '', options = {})

  if data.bytesize > Atech::ObjectStore.maximum_file_size
    raise FileDataTooBig, "Data provided was #{data.bytesize} and the maximum size is #{Atech::ObjectStore.maximum_file_size}"
  end

  ## Create a hash of properties to be for this class
  options[:name]          = filename
  options[:size]        ||= data.bytesize
  options[:blob]          = data
  options[:created_at]  ||= Time.now
  options[:updated_at]  ||= Time.now

  ## Ensure that new files have a filename & data
  raise ValidationError, "A 'name' must be provided to add a new file" if options[:name].nil?

  ## Encode timestamps
  options[:created_at] = options[:created_at].utc
  options[:updated_at] = options[:updated_at].utc

  ##Create an insert query
  columns = options.keys.join('`,`')
  data    = options.values.map { |data| escape_and_quote(data) }.join(',')
  File.execute_query("INSERT INTO files (`#{columns}`) VALUES (#{data})")

  ## Return a new File object
  self.new(options.merge({:id => ObjectStore.backend.last_id}))
end