app/models/locomotive/theme_asset.rb in locomotive_cms-2.0.3 vs app/models/locomotive/theme_asset.rb in locomotive_cms-2.1.0
- old
+ new
@@ -11,24 +11,27 @@
field :content_type
field :width, type: Integer
field :height, type: Integer
field :size, type: Integer
field :folder, default: nil
+ field :checksum
+
mount_uploader :source, ThemeAssetUploader, mount_on: :source_filename, validate_integrity: true
## associations ##
- belongs_to :site, class_name: 'Locomotive::Site'
+ belongs_to :site, class_name: 'Locomotive::Site', autosave: false
## indexes ##
- index :site_id
- index [[:site_id, Mongo::ASCENDING], [:local_path, Mongo::ASCENDING]]
+ index site_id: 1
+ index site_id: 1, local_path: 1
## callbacks ##
before_validation :check_for_folder_changes
before_validation :store_plain_text
before_validation :sanitize_folder
before_validation :build_local_path
+ before_save :calculate_checksum
## validations ##
validates_presence_of :site
validates_presence_of :source, on: :create
validates_presence_of :plain_text_name, if: Proc.new { |a| a.performing_plain_text? }
@@ -102,11 +105,11 @@
@plain_text = sanitized_source # no need to reset the plain_text instance variable to have the last version
end
def self.all_grouped_by_folder(site)
- assets = site.theme_assets.order_by([[:slug, :asc]])
+ assets = site.theme_assets.order_by(:slug.asc)
assets.group_by { |a| a.folder.split('/').first.to_sym }
end
def to_liquid
{ url: self.source.url }.merge(self.attributes).stringify_keys
@@ -139,11 +142,11 @@
end
def escape_shortcut_urls(text)
return if text.blank?
- text.gsub(/[("'](\/(stylesheets|javascripts|images|media|others)\/(([^;.]+)\/)*([a-zA-Z_\-0-9]+)\.[a-z]{2,3})[)"']/) do |path|
+ text.gsub(/[("'](\/(stylesheets|javascripts|images|media|others)\/(([^;.]+)\/)*([a-zA-Z_\-0-9]+)\.[a-z]{2,3})(\?[0-9]+)?[)"']/) do |path|
sanitized_path = path.gsub(/[("')]/, '').gsub(/^\//, '')
if asset = self.site.theme_assets.where(local_path: sanitized_path).first
"#{path.first}#{asset.source.url}#{path.last}"
@@ -154,11 +157,11 @@
end
def check_for_folder_changes
# https://github.com/jnicklas/carrierwave/issues/330
# https://github.com/jnicklas/carrierwave-mongoid/issues/23
- if self.persisted? && self.folder_changed? && !self.source_filename_changed?
+ if self.persisted? && self.folder_changed? && !self.changed_attributes.key?('source_filename')
# a simple way to rename a file
old_asset = self.class.where(_id: self._id).first # bypass memoization by mongoid
file = old_asset.source.file
file.content_type = File.mime_type?(file.path) if file.content_type.nil?
self.source = file
@@ -166,9 +169,17 @@
end
end
def content_type_can_not_change
self.errors.add(:source, :extname_changed) if self.persisted? && self.content_type_changed?
+ end
+
+ def calculate_checksum
+ begin
+ self.checksum = Digest::MD5.hexdigest(self.source.read)
+ rescue Errno::ENOENT => e
+ # no file
+ end
end
end
end