module Shrine::Plugins::Model::AttachmentMethods

Public Class Methods

new(name, model: true, **options) click to toggle source

Allows disabling model behaviour:

Shrine::Attachment(:image)               # model (default)
Shrine::Attachment(:image, model: false) # entity
Calls superclass method
# File lib/shrine/plugins/model.rb, line 21
def initialize(name, model: true, **options)
  super(name, **options)
  @model = model
end

Public Instance Methods

included(klass) click to toggle source

We define model methods only on inclusion. This gives other plugins the ability to disable model behaviour for entity classes. In this case we want to skip defining model methods as well.

Calls superclass method
# File lib/shrine/plugins/model.rb, line 29
def included(klass)
  super
  define_model_methods(@name) if model?
end

Private Instance Methods

attacher(record, **options) click to toggle source

Memoizes the attacher instance into an instance variable.

Calls superclass method
# File lib/shrine/plugins/model.rb, line 60
def attacher(record, **options)
  return super unless model?

  if !record.instance_variable_get(:"@#{@name}_attacher") || options.any?
    attacher = class_attacher(**options)
    attacher.load_model(record, @name)

    record.instance_variable_set(:"@#{@name}_attacher", attacher)
  else
    record.instance_variable_get(:"@#{@name}_attacher")
  end
end
define_model_methods(name) click to toggle source

Defines attachment setter and enhances the copy constructor.

Calls superclass method
# File lib/shrine/plugins/model.rb, line 37
def define_model_methods(name)
  super if defined?(super)

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

  define_method :"#{name}_changed?" do
    send(:"#{name}_attacher").changed?
  end

  # The copy constructor that's called on #dup and #clone.
  define_method :initialize_copy do |other|
    super(other)
    attacher_copy = instance_variable_get(:"@#{name}_attacher")&.dup
    attacher_copy.set_entity(self, name) if attacher_copy
    instance_variable_set(:"@#{name}_attacher", attacher_copy)
    self
  end
  private :initialize_copy
end
model?() click to toggle source
# File lib/shrine/plugins/model.rb, line 73
def model?
  @model
end