ruby-on-railsshrine

Rails and Shrine create model record with attachment


I need to upload image with Shrine using uploader, I have default uploader from example here including few derivatives.

Like here https://shrinerb.com/docs/getting-started

But I want to create new instance inside IRB, and I don't figure it out how to pass image properly to the Shrine. As I will finish it it will be used in a script for converting bunch of images.

If I do this:

Images.new(
  title: title,
  image: File.open("image.png")
)

It fails on validation because mime-type is empty. When I use form to upload image, there is ActionDispatch::Http::UploadedFile object containing complete information.

Please, how can I pass image to the uploader to be properly processed, mime type stored and created derivatives?

If I try this.

attacher = Shrine::Attacher.from_model(new_image, :image)
      attacher.assign(image)

inside image is path to image, it fails on:

*** JSON::ParserError Exception: 784: unexpected token at

And if I pass File.open(image) to assign method, I get uploaded orignal image, but without mime-type and without derivatives.

I am little bit confused.

Thanks


Solution

  • I have a solution.

    Shrine uploader needs a File object opened in binmode, so

            image: File.open(image, binmode: true)
    
    

    In creating instance of model class.