"version" in the block passed to mount_uploader. #835

Closed
Exoth opened this Issue Sep 11, 2012 · 3 comments

Comments

Projects
None yet
4 participants

Exoth commented Sep 11, 2012

If I pass a block with "version" to mount_uploader, it goes into an infinite recursion, because the block is applied to versions AFTER the uploader itself, whilst, I believe, it should be applied before.

konsti commented Nov 14, 2012

Have the same issue. It's not possible to pass version in the block to mount_uploader

Owner

bensie commented Nov 28, 2012

Similar issue reported in #898. Any chance you could provide a failing test for this?

bensie closed this Nov 28, 2012

The issue is still here, it's because of the following line:
https://github.com/jnicklas/carrierwave/blob/master/lib/carrierwave/mount.rb#L146

Basically, if you define a version in the block you are passing to mount_uploader, the same block is passed to each version defined, defining more versions, leading to the infinite loop.

You can achieve a dynamic version with an anonymous uploader with the following.

# app/config/positions.yml

positions:
  top_left:
    thumb:
      resize_and_pad: [200, 150, "white"]
    medium:
      resize_and_pad: [600, 778, "white"]
  top_right:
    thumb:
      resize_and_pad: [200, 150, "white"]
    medium:
      resize_and_pad: [600, 159, "white"]

And in your model

POSITIONS = YAML.load(ERB.new(File.read(Rails.root.join('config', 'positions.yml'))).result)['positions']

class Attachment
  field :position
  validate :position_value_valid?

  def position=(position)
    self[:position] = position

    self.class.instance_eval do  # As if we were running code in the Attachment definition
      uploader = Class.new(CarrierWave::Uploader::Base)
      POSITIONS[position].each do |version_name, processes|
        uploader.class_eval do
          version version_name do
            processes.each do |process_name, arg_array|
              process process_name.to_sym, arg_array
            end
          end
        end
      end

      mount_uploader :image, uploader
    end
  end

  def position_value_valid?
    POSITIONS.keys.include? position
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment