Module: LocusFocus::Acts::PolymorphicPaperclip::InstanceMethods

Defined in:
lib/sga/acts_as_polymorphic_paperclip.rb

Instance Method Summary collapse

Instance Method Details

#after_saveObject



97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/sga/acts_as_polymorphic_paperclip.rb', line 97

def after_save
  super
  Asset.transaction do
    if data.is_a?(Array)
      data.each do |data_item|
        create_and_save_asset(data_item) unless data_item.nil? || data_item.blank?
      end
    else
      create_and_save_asset(data)
    end
  end unless data.nil? || data.blank?
end

#create_and_save_asset(data_item) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/sga/acts_as_polymorphic_paperclip.rb', line 110

def create_and_save_asset(data_item)
  the_asset = Asset.find_or_initialize_by_data_file_name(data_item.original_filename)
  override_default_styles, normalised_styles = override_default_styles?(data_item.original_filename)
  the_asset.data.instance_variable_set("@styles", normalised_styles) if override_default_styles
  the_asset.data = data_item
  if the_asset.save
  
    # This association may be saved more than once within the same request / response 
    # cycle, which leads to needless DB calls. Now we'll clear out the data attribute
    # once the record is successfully saved any subsequent calls will be ignored.
    data_item = nil
    Attaching.find_or_create_by_asset_id_and_attachable_type_and_attachable_id(:asset_id => the_asset.id, :attachable_type => self.class.to_s, :attachable_id => self.id)
    assets(true) # implicit reloading
  end
end

#override_default_styles?(filename) ⇒ Boolean

Returns:

  • (Boolean)


126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/sga/acts_as_polymorphic_paperclip.rb', line 126

def override_default_styles?(filename)
  if !acts_as_polymorphic_paperclip_options[:styles].nil?
    normalised_styles = {}
    acts_as_polymorphic_paperclip_options[:styles].each do |name, args|
      dimensions, format = [args, nil].flatten[0..1]
      format = nil if format.blank?
      if filename.match(/\.pdf$/) # remove crop commands if file is a PDF (this fails with Imagemagick)
        args.gsub!(/#/ , "")
        format = "png"
      end
      normalised_styles[name] = { :processors => [:thumbnail], :geometry => dimensions, :format => format }
    end
    return true, normalised_styles
  else
    return false
  end
end