Module: Shrine::Plugins::Reform::AttachmentMethods

Defined in:
lib/shrine/plugins/reform.rb

Instance Method Summary collapse

Instance Method Details

#included(form) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
# File 'lib/shrine/plugins/reform.rb', line 7

def included(form)
  super

  return unless form < ::Reform::Form

  properties = [
    :"#{@name}",
    :"#{@name}_remote_url",
    :"#{@name}_data_uri",
    :"remove_#{@name}",
    :"cached_#{@name}_data",
  ]

  module_eval <<-RUBY, __FILE__, __LINE__ + 1
    def prepopulate!(*)
      super
      @#{@name}_data = model.#{@name}_data
    end

    def sync(*)
      super
      if instance_variable_defined?(:@#{@name}_data)
        model.#{@name} = @#{@name}_data if model.respond_to?(:#{@name}=)
      end
    end
  RUBY

  form.class_eval <<-RUBY, __FILE__, __LINE__ + 1
    def self.create_accessors(name, definition)
      super unless #{properties}.include?(name)
    end

    attr_accessor :#{@name}_data

    validate do
      #{@name}_attacher.errors.each do |message|
        errors.add :#{@name}, message
      end
    end
  RUBY

  (properties & instance_methods).each do |name|
    form.send(:property, name, virtual: true)
  end
end