Module: SimplyCouch::HasAttachment::ClassMethods

Defined in:
lib/simply_couch/has_attachment.rb

Instance Method Summary collapse

Instance Method Details

#attachment_registryObject

Registry of all attachments defined on this class



220
221
222
# File 'lib/simply_couch/has_attachment.rb', line 220

def attachment_registry
  @_has_attachment_registry ||= {}
end

#has_attachment(name, styles: {}, default_url: nil, default_style: :original) ⇒ Object



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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/simply_couch/has_attachment.rb', line 91

def has_attachment(name, styles: {}, default_url: nil, default_style: :original)
  # Auto-declare CouchDB properties for attachment metadata
  property :"#{name}_file_name"
  property :"#{name}_content_type"
  property :"#{name}_file_size", type: Integer
  property :"#{name}_updated_at", type: Time

  # Register configuration
  attachment_registry[name] = {
    styles: styles,
    default_url: default_url,
    default_style: default_style,
  }

  # ---- Setter: model.file = uploaded_file ----
  define_method(:"#{name}=") do |uploaded|
    # Handle clearing: nil, empty string
    if uploaded.nil? || (uploaded.respond_to?(:empty?) && uploaded.empty?)
      send(:"#{name}_file_name=", nil)
      send(:"#{name}_content_type=", nil)
      send(:"#{name}_file_size=", nil)
      send(:"#{name}_updated_at=", nil)
      return
    end

    config = self.class.attachment_registry[name]

    # Extract file info
    original_filename = if uploaded.respond_to?(:original_filename)
                          uploaded.original_filename
                        elsif uploaded.respond_to?(:path)
                          File.basename(uploaded.path)
                        else
                          "file"
                        end
    ext = File.extname(original_filename)
    ext = ".bin" if ext.blank?

    content_type = uploaded.respond_to?(:content_type) ? uploaded.content_type : nil
    file_size    = uploaded.respond_to?(:size) ? uploaded.size : nil

    # Read content (handle multiple upload types)
    content = if uploaded.respond_to?(:read)
                data = uploaded.read
                uploaded.rewind if uploaded.respond_to?(:rewind)
                data
              elsif uploaded.respond_to?(:path) && File.exist?(uploaded.path)
                File.binread(uploaded.path)
              elsif uploaded.respond_to?(:tempfile)
                uploaded.tempfile.read
              else
                uploaded.to_s
              end

    # Build storage path
    record_id = respond_to?(:id) && id.present? ? id.to_s : "tmp"
    base_dir = Rails.root.join("public", "system", name.to_s, record_id)
    FileUtils.mkdir_p(base_dir)

    begin
      # Write original file
      original_path = base_dir.join("original#{ext}")
      File.binwrite(original_path, content)

      # Generate thumbnail styles
      config[:styles].each do |style_name, geometry|
        style_path = base_dir.join("#{style_name}#{ext}")
        begin
          image = MiniMagick::Image.open(original_path.to_s)
          image.resize(geometry)
          image.write(style_path.to_s)
        rescue StandardError => e
          # If ImageMagick fails, copy original as fallback
          Rails.logger.warn(
            "[HasAttachment] Could not generate #{style_name} for #{name}: #{e.message}"
          )
          FileUtils.cp(original_path, style_path)
        end
      end

      # Store metadata as CouchDB properties
      send(:"#{name}_file_name=", original_filename)
      send(:"#{name}_content_type=", content_type)
      send(:"#{name}_file_size=", file_size || content.bytesize)
      send(:"#{name}_updated_at=", Time.current)
    rescue StandardError => e
      errors.add(name, "could not be processed: #{e.message}")
      Rails.logger.error("[HasAttachment] Error processing #{name}: #{e.message}")
    end
  end

  # ---- Getter: model.file → Proxy ----
  define_method(name) do
    Proxy.new(self, name)
  end

  # ---- URL helper: model.file_url(:thumb) ----
  define_method(:"#{name}_url") do |style_name = nil|
    config = self.class.attachment_registry[name]
    style_name ||= config[:default_style]

    fname = send(:"#{name}_file_name")
    if fname.blank?
      return config[:default_url] if config[:default_url]
      return nil
    end

    ext = File.extname(fname)
    record_id = respond_to?(:id) && id.present? ? id.to_s : "tmp"

    "/system/#{name}/#{record_id}/#{style_name}#{ext}"
  end

  # ---- Backward compat: *_path for Paperclip migrations ----
  define_method(:"#{name}_path") do |style_name = nil|
    config = self.class.attachment_registry[name]
    style_name ||= config[:default_style]

    fname = send(:"#{name}_file_name")
    return nil if fname.blank?

    ext = File.extname(fname)
    record_id = respond_to?(:id) && id.present? ? id.to_s : "tmp"

    Rails.root.join("public", "system", name.to_s, record_id, "#{style_name}#{ext}").to_s
  end
end