Module: JCropper::ClassMethods

Included in:
ActiveRecord::Base
Defined in:
lib/jcropper/jcropper.rb

Instance Method Summary collapse

Instance Method Details

#jcrop(attachment, style, options = {}) ⇒ Object



14
15
16
17
18
19
20
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/jcropper/jcropper.rb', line 14

def jcrop(attachment, style, options = {})
  raise "jcropper requires attachment to be of type Paperclip::Attachment" if self.attachment_definitions[attachment.to_sym].nil?
  
  attr_reader :cropped_image
  write_inheritable_hash :jcropper_defs, {:attachment => attachment, :style => style} 
  class_inheritable_reader :jcropper_defs
  attr_accessor :jcropper_should_reprocess
  before_save :jcropper_normalize_crop, :jcropper_check_for_reprocess
  after_save :jcropper_reprocess

  x, y, w, h = [:x, :y, :w, :h].map{|coord| JCropper.jattr(attachment, style, coord) }
  if defined?(Rails) and Rails.version.split('.').first.to_i > 2
    to_eval = <<-TO_EVAL
      after_initialize :jcropper_initialize
      def jcropper_initialize
        @cropped_image = CroppedImage.new(self, #{options.inspect})
      end
    TO_EVAL
  else
    to_eval = <<-TO_EVAL
      ###CRZ - alias chain this
      def after_initialize
        @cropped_image = CroppedImage.new(self, #{options.inspect})
      end
    TO_EVAL
  end        

  to_eval += <<-TO_EVAL
    def jcropper_reprocess
      cropped_image.attachment.reprocess! if @jcropper_should_reprocess
    end

    def jcropper_check_for_reprocess
      @jcropper_should_reprocess ||= !(changed & %w(#{x} #{y} #{w} #{h})).empty?
      true
    end

    def jcropper_coords
      [#{x}, #{y}, #{w}, #{h}]
    end
    
    def jcropper_needs_crop?
      cropped_image and cropped_image.original_geometry and (#{w} == 0 or #{h} == 0)
    end

    def jcropper_normalize_crop
      self.#{x}, self.#{y}, self.#{w}, self.#{h} = *cropped_image.max_crop if jcropper_needs_crop?
      true
    end

    def jcropper_crop_string
      "-crop \#{#{w}}x\#{#{h}}+\#{#{x}}+\#{#{y}}"
    end
  TO_EVAL
  class_eval to_eval
end