Module: HasAttached::ClassMethods

Defined in:
lib/has-attached.rb

Instance Method Summary collapse

Instance Method Details

#has_attached(name, options = {}) ⇒ Object



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
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/has-attached.rb', line 34

def has_attached(name, options = {})
  
  options[:url]  ||= "/attachments/:class/:id/:attachment/:style/:basename.:extension"
  options[:path] ||= ":rails_root/public/attachments/:class/:id/:attachment/:style/:basename.:extension"
  options[:processors] ||= [:auto_orient, :thumbnail]
  
  unless options[:styles]
    @all_styles ||= (YAML.load_file(Rails.root.join("config", "styles.yml")) rescue {"styles" => {}})["styles"]      
    options[:styles] = @all_styles.fetch(self.name.underscore, {}).fetch(name.to_s, {}).symbolize_keys
  end
  
  if Rails.env.production? && Rails.application.config.respond_to?(:upload_attachments_to_s3) && Rails.application.config.upload_attachments_to_s3
    options[:storage] = 's3'
    options[:s3_credentials] = Rails.root.join("config", "s3.yml")
    options[:path] = "/attachments/:class/:id/:attachment/:style/:basename.:extension"
    options[:url] = ":s3_domain_url"
  else
    options[:storage] = 'filesystem'
  end
  has_attached_file(name, options)
  
  field :"#{name}_file_name"
  field :"#{name}_content_type"
  field :"#{name}_file_size", :as => :integer
  field :"#{name}_updated_at", :as => :datetime

  validate do |record|
    if record.send(name) && !record.send(name).errors.empty?
      file_name = record.send(:"#{name}_file_name")
      record.errors.add name, "Paperclip returned errors for file '#{file_name}' - check ImageMagick installation or image source file."
      false
    end
  end
  
  attr_accessor :"#{name}_delete"

  define_method :"#{name}_delete" do
    false
  end 
  
  define_method :"#{name}_delete=" do |val|
    if val == "1"
      send(name).clear
    end
  end

end