class Attachment < ActiveRecord::Base include Tire::Model::Search include Tire::Model::Callbacks # after_save :save_to_git belongs_to :attachable, :polymorphic => true validates_presence_of :attachable def self.create_from_uploaded_file(file, user, options = {}) filename = file.original_filename attachment = Attachment.create( options.merge( filename: filename, content_type: file.content_type, size: file.size, )) if attachment.errors.none? attachment.save_to_gollum( file, user, "uploading file: #{filename}" ) end attachment end def file_data format = File.extname(filename).gsub(".", "") $wiki.file(wiki_dir + "/" + wiki_attachment_data + "." + format).raw_data end def save_to_gollum(file, user, message) commit = { message: message, name: user.name, email: user.email } file_name = file.try(:original_filename) || File.basename(file.path) extension = File.extname(file_name).gsub(".", "") data_file = file.try(:tempfile) || file $wiki.write_page(wiki_attachment_data, extension, data_file, commit, wiki_dir) end protected def wiki_attachment_data "#{id}-data" end def wiki_dir "attachments/#{id}" end end