CarrierWave with ActiveResource

Does anyone have any ideas on using CarrierWave with the ActiveResource model (in Rails 3)? I have an ActiveResource model with a field for the file name, and I want to save the file to a remote file system.

I tried several things without much success (or the confidence that I was doing something remotely correctly), so I will be grateful for the suggestions from anyone who successfully implemented CarrierWave, without using the ORM modules already included in the gem.

+4
source share
1 answer

I'm probably late for this since the original author moved on, but this question comes up above when someone searches for “operatorwave activeresource”, so I thought it was still worth the answer.

For discussion, suppose we have a model named Artist with an artist_picture image mounted as a CarrierWave loader. With ActiveRecord, you must assign a file to this image:

artist.artist_picture=File.open('ravello.jpg') 

And when you save the artist:

 artist.save! 

The image will also be saved.

Now let's say I create a resource based on this:

 class Artist < ActiveResource::Base end 

If later I will read with the artist:

 artist = Artist.find(1) 

and look at it, I will find it there:

 #<Artist:0x39432039 @attributes={"id"=>1, "name"=>"Ravello", "artist_picture"=>#<ArtistPicture:0x282347249243 @attributes={"url"=>"/uploads/artists/artist_picture/1/ravello.jpg"}, @prefix_options={}, @persisted=false>, @prefix_options={}, @persisted=false> 

Interestingly, artist_picture itself is a model, and we could declare it and play with it if we want. Be that as it may, you can use the url to capture the image if you want. But let’s talk instead about loading another picture.

We can add this little code to the server model Artist:

  def artist_picture_as_base64=(picsource) tmpfile = Tempfile.new(['artist','.jpg'], Rails.root.join('tmp'), :encoding => 'BINARY') begin tmpfile.write(Base64.decode64(picsource.force_encoding("BINARY"))) file = CarrierWave::SanitizedFile.new(tmpfile) file.content_type = 'image/jpg' self.artist_picture = file ensure tmpfile.close! end end 

I am just showing a simple example - you should probably pass in the original file name. Anyway, on the resource side:

 class Artist < ActiveResource::Base def artist_picture=(filename) self.artist_picture_as_base64=Base64.encode64(File.read(filename)) end end 

At this point, on the resource side, you only need to set "artist_picture" in the file name, and it will be encoded and sent when the resource is saved. On the server side, the file will be decoded and saved. Presumably, you can skip base64 encoding just by forcing a binary encoding string, but it crap when I do this and I have no patience to keep track of it. Encoding works like base64.

+9
source

Source: https://habr.com/ru/post/1342935/


All Articles