Class: Shrine::Plugins::Hanami::RepositoryMethods

Inherits:
Module
  • Object
show all
Defined in:
lib/shrine/plugins/hanami.rb

Instance Method Summary collapse

Constructor Details

#initialize(name, attacher_class) ⇒ RepositoryMethods

Returns a new instance of RepositoryMethods.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/shrine/plugins/hanami.rb', line 51

def initialize(name, attacher_class)
  class_eval <<-RUBY, __FILE__, __LINE__ + 1
    def self.prepended(base)
      base.send(:include, ::Hanami::Utils::ClassAttribute)
      base.send(:class_attribute, :_attachments)
      base.class_eval do
        self._attachments ||= []
        self._attachments << { name: :#{name}, class: #{attacher_class} }
      end
    end
  RUBY

  class_eval do
    def create(entity)
      save_attachments(entity) { |new_entity| super(new_entity) }
    end

    def update(id, entity)
      save_attachments(entity) { |new_entity| super(id, new_entity) }
    end

    def persist(entity)
      save_attachments(entity) { |new_entity| super(new_entity) }
    end

    def delete(id)
      delete_attachments(id) { super(id) }
    end

    private
    def _attachments
      self.class._attachments
    end

    def save_attachments(entity)
      _attachments.each do |a|
        entity = save_attachment(entity, a[:name], a[:class])
      end
      yield(entity)
    end

    def save_attachment(original_entity, name, uploader_class)
      file = original_entity.send(name)

      if file
        attacher = uploader_class::Attacher.new(OpenStruct.new, name)

        attacher.assign(file)
        attacher.finalize

        original_entity_attributes = original_entity.attributes
        original_entity_attributes.delete(name)

        entity = original_entity.class.new(original_entity_attributes.merge(:"#{name}_data" => attacher.read))
      else
        entity = original_entity
      end
    end

    def delete_attachments(id)
      entity = find(id)
      yield
      _attachments.each do |a|
        entity.send("#{a[:name]}_attacher").destroy
      end
    end
  end
end