Hussain Niazi
Hussain Niazi

Reputation: 619

Rails Carrierwave & Imagemagick, using conditions to resize image

I have been struggling to find any tutorial or question that explains how to upload image and resize it according to certain conditions provided by user.

I am easily able to upload and resize image using hard coded values, however I am stuck at using user provided parameters to be accessed from the Uploader.

I want the image to be resized to either 800x600 or 300x300 based on whether the user checks the image as Large or Small.

For that I have a boolean column named "large" in the model structure.

In the Uploader I am able to access model and its values easily in the store_dir block, but anywhere outside this block any model attribute returns as nil.

This is what I want to do:-

class BannerUploader < CarrierWave::Uploader::Base
    include CarrierWave::MiniMagick
    storage :file
    def store_dir
        "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
    end
    resize_to_fit(800,600) if model.large==true
    resize_to_fit(300,300) if model.large!=true
end

However this returns the error undefined local variable or method `model' for BannerUploader:Class

How to go about this issue.

Upvotes: 0

Views: 579

Answers (2)

Hussain Niazi
Hussain Niazi

Reputation: 619

Ok so @Alex Kojin has the right answer. However I was faced with another problem as well. When the user submitted the form, the image would be resized always as small (300x300) because for some reason the image resize process would be executed first and then the "large" attribute would be set as true. Therefore the Uploader would always get model.large as false. So this is how I had to change my action controller

def create
    @banner=Banner.new
    @banner.large=params[:large]
    @banner.update_attributes(banner_params)
    @banner.save
    redirect_to :back
end

Not sure if this is the right approach but does work for me.

Upvotes: 0

Alex Kojin
Alex Kojin

Reputation: 5204

To process an original file you can specify custom method:

class BannerUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  storage :file
  def store_dir
      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  process :process_original_version

  def process_original_version
    if model.large
      resize_to_fit(800,600)
    else
      resize_to_fit(300,300)
    end
  end
end

For a specific version:

class BannerUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  storage :file
  def store_dir
      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  version :normal do
    if model.large
      process resize_to_fit: [800,600]
    else
      process resize_to_fit: [300,300]
    end
  end
end

Upvotes: 1

Related Questions