Module: Papercrop::ModelExtension::ClassMethods

Defined in:
lib/papercrop/model_extension.rb

Instance Method Summary collapse

Instance Method Details

#crop_attached_file(attachment_name, opts = {}) ⇒ Object

Initializes attachment cropping in your model

crop_attached_file :avatar

You can also define an initial aspect ratio for the crop and preview box through opts

crop_attached_file :avatar, :aspect => "4:3"

Or unlock it

crop_attached_file :avatar, :aspect => false

Parameters:

  • attachment_name (Symbol)

    Name of the desired attachment to crop

  • opts (Hash) (defaults to: {})

Options Hash (opts):

  • :aspect (Range, String, FlaseClass)


21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/papercrop/model_extension.rb', line 21

def crop_attached_file(attachment_name, opts = {})
  opts = opts.dup

  [:crop_x, :crop_y, :crop_w, :crop_h, :original_w, :original_h, :box_w, :aspect, :cropped_geometries].each do |a|
    attr_accessor :"#{attachment_name}_#{a}"
  end

  aspect = normalize_aspect opts[:aspect]

  send :define_method, :"#{attachment_name}_aspect" do
    aspect.first.to_f / aspect.last.to_f if aspect
  end

  if respond_to? :attachment_definitions
    # for Paperclip <= 3.4
    definitions = attachment_definitions
  else
    # for Paperclip >= 3.5
    definitions = Paperclip::Tasks::Attachments.instance.definitions_for(self)
  end

  processors = definitions[attachment_name][:processors] ||= []
  unless processors.include? :papercrop
    processors << :papercrop
  end

  after_update :"reprocess_to_crop_#{attachment_name}_attachment"
end

#normalize_aspect(aspect) ⇒ Range

Returns a valid and normalized value for aspect ratio It will return 1.. if aspect is nil or a invalid string

Parameters:

  • aspect (Range, String, FalseClass)

Returns:

  • (Range)


56
57
58
59
60
61
62
63
64
65
66
# File 'lib/papercrop/model_extension.rb', line 56

def normalize_aspect(aspect)
  if aspect.kind_of?(String) && aspect =~ Papercrop::RegExp::ASPECT
    Range.new *aspect.split(':').map(&:to_i)
  elsif aspect.kind_of?(Range)
    return aspect.first.to_i..aspect.last.to_i
  elsif aspect == false
    return aspect
  else
    1..1
  end
end