Carrierwave; multiple uploaders or just one?

2020-05-20 02:30发布

问题:

I have a post model and a podcast model. Both models have an attribute titled: image. I'm using one Carrierwave uploader (named ImageUploader) to handle both models. I have two questions before I go into production.

Dumb question:

Is it ok to use the same uploader for two different models when they both have the same attribute name for their file attachements? sorry if it seems obvious

Main question:

I want to create three versions of each blog post image (thumb, large, sepia) and only 1 version of each podcast image (thumb).

Do I need to use two uploaders now or can I namespace with the one that I'm already using?

Again it probably seems obvious. I could probably have written the second uploader in the time its taken me to ask these questions

回答1:

You can use the same uploader on different models even if they have different attribute names. e.g.

class Post
  mount_uploader :image, ImageUploader
end

class Podcast
  mount_uploader :photo, ImageUploader
end

Whether or not you'd want to is a different matter. In your case, I'd create different uploaders for each model, because they have different requirements. You can always use subclasses if you want to keep your code dry:

class ImageUploader < Carrierwave::Uploader::Base; end  # thumbnail
class PostImageUploader < ImageUploader; end  # thumbnail (from superclass), large & sepia
class PodcastImageUploader < ImageUploader; end # thumbnail (from superclass)