Clarification needed on refresh_metadata!

Hi,

I’m using shrine 3.0.1 with Rails 6.0.1 and I’m confused by the use of refresh_metadata!.

I successfully added two metadata fields to my uploader: exif (copied from the example in the docs) and has_alpha?:

  add_metadata :has_alpha? do |io, context|
    Shrine.with_file(io) do |file|
      ::Vips::Image.new_from_file(file.path).has_alpha?
    end
  end

I can upload new images and the metadata is attached and stored as expected.

I can also call model.image.refresh_metadata! and directly afterwards access the new metadata.

However, the metadata is not persisted to the database when calling model.save (and model.changed? returns false as well).

Additionally I wonder, why I can add Shrine.plugin :refresh_metadata to config/initializers/shrine.rb. It doesn’t seem to make a difference if is there or not. The refresh_metadata! method is available with and without explicitly loading the plugin. But saving doesn’t work either way.

Some help would be appreciated!

Hi :wave:

I can also call model.image.refresh_metadata! and directly afterwards access the new metadata.

However, the metadata is not persisted to the database when calling model.save (and model.changed? returns false as well).

Calling #refresh_metadata! on the uploaded file itself is not going to update the model attribute, as Shrine::UploadedFile objects are just value objects that don’t know anything about models. You need to call #refresh_metadata! on the Shrine::Attacher object instead:

model.image_attacher.refresh_metadata!
model.save

Additionally I wonder, why I can add Shrine.plugin :refresh_metadata to config/initializers/shrine.rb. It doesn’t seem to make a difference if is there or not. The refresh_metadata! method is available with and without explicitly loading the plugin.

The restore_cached_data plugin depends on the refresh_metadata plugin, so it loads it up automatically.

Wow, that was a quick answer. I tried your solution and it worked!
Thanks a lot!