Sha256: 830c68ab29b6551498fd170c29f1baabc0797ae6853beef0fd37e7aa671803a9

Contents?: true

Size: 1.34 KB

Versions: 1

Compression:

Stored size: 1.34 KB

Contents

require "uploadcare/rails/file"

module Uploadcare
  module Rails
    module ActiveRecord
      def has_uploadcare_file attribute, options={}
  
        define_method "has_uploadcare_file?" do
          true
        end

        define_method "has_uploadcare_group?" do
          false
        end

        # attribute method - return file object
        # it is not the ::File but ::Rails::File
        # it has some helpers for rails enviroment
        # but it also has all the methods of Uploadcare::File so no worries.
        define_method "#{attribute}" do
          cdn_url = attributes[attribute.to_s].to_s
          
          return nil if cdn_url.empty?

          api = UPLOADCARE_SETTINGS.api
          file = Uploadcare::Rails::File.new api, cdn_url
        end

        # before saving we checking what it is a actually file cdn url
        # or uuid. uuid will do.
        # group url or uuid should raise an erorr
        before_save "check_#{attribute}_for_uuid"

        define_method "check_#{attribute}_for_uuid" do
          url = self.attributes[attribute.to_s]
          unless url.empty?
            result = Uploadcare::Parser.parse(url)
            raise "Invalid Uploadcare file uuid" unless result.is_a?(Uploadcare::Parser::File)
          end
        end
      end
    end
  end
end

ActiveRecord::Base.extend Uploadcare::Rails::ActiveRecord

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
uploadcare-rails-1.0.0.rc4 lib/uploadcare/rails/active_record_has_file.rb