Search code examples
ruby-on-railsrubyruby-on-rails-3.2carrierwavermagick

How can I pass arbitrary user-defined values into a CarrierWave image processor?


So I'm working on a rails 3.2 app where I have a CarrierWave uploader; which I use to upload images, and split crop them into a few different sizes - pretty standard stuff.

What I would like to do is composite a new image on top of the image being uploaded, which is also pretty straight forward. (very commonly done for watermarking). The difference is that instead of having static values for positioning the composited image, I need them to be dynamic.

The thing I'm having trouble with is figuring out how to pass dynamic user-defined positional arguments into my carrierwave processor in the 'version' block.

Any ideas?


Solution

  • you can store the value into model instance

    then, in the process method to get it by model attr

    # model class
    # define attr_accessor coords
    class User < ActiveRecord::Base
      attr_accessor :coords
      mount_uploader :icon, AvatarUploader
    end
    
    
    
    # controller
    # pass the params to @user.coords
    def crop_icon
      @user.coords = params[:coords]
      @user.icon = params[:icon]
      @user.save
    end
    
    
    
    # Uploader
    # the model in the function is same as @user in controll,
    # and can be invoked inside of process method 
     def crop_area
        manipulate! do |img|
          unless model.coords.nil?
            coords = JSON.parse(model.coords)
            img.crop("#{coords['w']}x#{coords['h']}+#{coords['x']}+#{coords['y']}")
          end
          img = yield(img) if block_given?
          img
        end
      end