Sha256: 8f670fa44d902c0efe866452cb66b2ca61ad5678b804a5833de6166ccaae60f0

Contents?: true

Size: 1.5 KB

Versions: 2

Compression:

Stored size: 1.5 KB

Contents

module Nifty
  module Attachments
    class Attachment < ActiveRecord::Base

      # Set the table name
      self.table_name = 'nifty_attachments'

      # This will be the ActionDispatch::UploadedFile object which be diseminated
      # by the class on save.
      attr_accessor :uploaded_file

      # Relationships
      belongs_to :parent, :polymorphic => true

      # Validations
      validates :file_name, :presence => true
      validates :file_type, :presence => true
      validates :data, :presence => true
      validates :digest, :presence => true
      validates :token, :presence => true, :uniqueness => true

      # All attachments should have a token assigned to this
      before_validation { self.token = SecureRandom.uuid if self.token.blank? }

      # Copy values from the `uploaded_file` and set them as the appropriate
      # fields on this model
      before_validation do
        if self.uploaded_file
          self.data = self.uploaded_file.tempfile.read
          self.file_name = self.uploaded_file.original_filename
          self.file_type = self.uploaded_file.content_type
          self.digest = Digest::MD5.hexdigest(self.data)
        end
      end

      # Return the attachment for a given role
      def self.for(role)
        self.where(:role => role).first
      end

      # Return the path to the attachment
      def path
        "/attachment/#{token}/#{file_name}"
      end

      # Is the attachment an image?
      def image?
        file_type =~ /\Aimage\//
      end

    end
  end
end

Version data entries

2 entries across 2 versions & 2 rubygems

Version Path
shoppe-paypal-1.1.0 vendor/bundle/ruby/2.1.0/gems/nifty-attachments-1.0.4/lib/nifty/attachments/attachment.rb
nifty-attachments-1.0.4 lib/nifty/attachments/attachment.rb