Module: Refile::Attachment

Included in:
Refile::ActiveRecord::Attachment
Defined in:
lib/refile/attachment.rb

Instance Method Summary collapse

Instance Method Details

#attachment(name, cache: :cache, store: :store, raise_errors: true, type: nil, extension: nil, content_type: nil) ⇒ Object

Macro which generates accessors for the given column which make it possible to upload and retrieve previously uploaded files through the generated accessors.

The raise_errors option controls whether assigning an invalid file should immediately raise an error, or save the error and defer handling it until later.

Parameters:

  • name (String)

    Name of the column which accessor are generated for

  • cache (#to_s) (defaults to: :cache)

    Name of a backend in Refile.backends to use as transient cache

  • store (#to_s) (defaults to: :store)

    Name of a backend in Refile.backends to use as permanent store

  • raise_errors (true, false) (defaults to: true)

    Whether to raise errors in case an invalid file is assigned

  • type (:image, nil) (defaults to: nil)

    The type of file that can be uploaded, currently :image is the only valid value and restricts uploads to JPEG, PNG and GIF images

  • extension (String, Array<String>, nil) (defaults to: nil)

    Limit the uploaded file to the given extension or list of extensions

  • content_type (String, Array<String>, nil) (defaults to: nil)

    Limit the uploaded file to the given content type or list of content types



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/refile/attachment.rb', line 21

def attachment(name, cache: :cache, store: :store, raise_errors: true, type: nil, extension: nil, content_type: nil)
  mod = Module.new do
    attacher = :"#{name}_attacher"

    define_method attacher do
      ivar = :"@#{attacher}"
      instance_variable_get(ivar) or begin
        instance_variable_set(ivar, Attacher.new(self, name,
          cache: cache,
          store: store,
          raise_errors: raise_errors,
          type: type,
          extension: extension,
          content_type: content_type
        ))
      end
    end

    define_method "#{name}=" do |uploadable|
      send(attacher).cache!(uploadable)
    end

    define_method name do
      send(attacher).get
    end

    define_method "#{name}_cache_id=" do |cache_id|
      send(attacher).cache_id = cache_id
    end

    define_method "#{name}_cache_id" do
      send(attacher).cache_id
    end

    define_method "remove_#{name}=" do |remove|
      send(attacher).remove = remove
    end

    define_method "remove_#{name}" do
      send(attacher).remove
    end

    define_method "remote_#{name}_url=" do |url|
      send(attacher).download(url)
    end

    define_method "remote_#{name}_url" do
    end
  end

  include mod
end