Module: Shrine::Attachment::InstanceMethods

Included in:
Shrine::Attachment
Defined in:
lib/shrine/attachment.rb

Instance Method Summary collapse

Instance Method Details

#attachment_nameObject

Returns name of the attachment this module provides.



67
68
69
# File 'lib/shrine/attachment.rb', line 67

def attachment_name
  @name
end

#build_attacher(object, options) ⇒ Object

Creates an instance of the corresponding Attacher subclass.



62
63
64
# File 'lib/shrine/attachment.rb', line 62

def build_attacher(object, options)
  shrine_class::Attacher.new(object, @name, @options.merge(options))
end

#define_attachment_methods!Object

Defines attachment methods for the specified attachment name. These methods will be added to any model that includes this module.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/shrine/attachment.rb', line 36

def define_attachment_methods!
  attachment = self
  name = attachment_name

  define_method :"#{name}_attacher" do |**options|
    if !instance_variable_get(:"@#{name}_attacher") || options.any?
      instance_variable_set(:"@#{name}_attacher", attachment.build_attacher(self, options))
    else
      instance_variable_get(:"@#{name}_attacher")
    end
  end

  define_method :"#{name}=" do |value|
    send(:"#{name}_attacher").assign(value)
  end

  define_method :"#{name}" do
    send(:"#{name}_attacher").get
  end

  define_method :"#{name}_url" do |*args|
    send(:"#{name}_attacher").url(*args)
  end
end

#initialize(name, **options) ⇒ Object

Instantiates an attachment module for a given attribute name, which can then be included to a model class. Second argument will be passed to an attacher module.



27
28
29
30
31
32
# File 'lib/shrine/attachment.rb', line 27

def initialize(name, **options)
  @name    = name.to_sym
  @options = options

  define_attachment_methods!
end

#inspectObject

Returns class name with attachment name included.

Shrine[:image].inspect #=> "#<Shrine::Attachment(image)>"


86
87
88
# File 'lib/shrine/attachment.rb', line 86

def inspect
  "#<#{self.class.inspect}(#{attachment_name})>"
end

#optionsObject

Returns options that are to be passed to the Attacher.



72
73
74
# File 'lib/shrine/attachment.rb', line 72

def options
  @options
end

#shrine_classObject

Returns the Shrine class that this attachment’s class is namespaced under.



92
93
94
# File 'lib/shrine/attachment.rb', line 92

def shrine_class
  self.class.shrine_class
end

#to_sObject

Returns class name with attachment name included.

Shrine[:image].to_s #=> "#<Shrine::Attachment(image)>"


79
80
81
# File 'lib/shrine/attachment.rb', line 79

def to_s
  "#<#{self.class.inspect}(#{attachment_name})>"
end