engine/app/models/asset_collection.rb

82 lines
1.9 KiB
Ruby
Raw Normal View History

class AssetCollection
include Locomotive::Mongoid::Document
2010-05-12 00:16:39 +00:00
## fields ##
field :name
field :slug
2010-09-15 00:19:34 +00:00
field :internal, :type => Boolean, :default => false
2010-05-12 00:16:39 +00:00
## associations ##
referenced_in :site
embeds_many :assets
2010-05-17 22:51:53 +00:00
## behaviours ##
custom_fields_for :assets
liquid_methods :name, :ordered_assets
2010-05-12 00:16:39 +00:00
## callbacks ##
before_validation :normalize_slug
2010-05-12 00:16:39 +00:00
before_save :store_asset_positions!
2010-10-29 14:19:41 +00:00
after_destroy :remove_uploaded_files
2010-05-12 00:16:39 +00:00
## validations ##
validates_presence_of :site, :name, :slug
validates_uniqueness_of :slug, :scope => :site_id
2010-09-15 00:19:34 +00:00
## named scopes ##
scope :internal, :where => { :internal => true }
scope :not_internal, :where => { :internal => false }
2010-09-15 00:19:34 +00:00
2010-05-12 00:16:39 +00:00
## methods ##
2010-05-12 00:16:39 +00:00
def ordered_assets
self.assets.sort { |a, b| (a.position || 0) <=> (b.position || 0) }
end
2010-05-12 00:16:39 +00:00
def assets_order
self.ordered_assets.collect(&:id).join(',')
end
2010-05-12 00:16:39 +00:00
def assets_order=(order)
@assets_order = order
end
2010-09-15 00:19:34 +00:00
def self.find_or_create_internal(site)
site.asset_collections.internal.first || site.asset_collections.create(:name => 'system', :slug => 'system', :internal => true)
2010-09-15 00:19:34 +00:00
end
2010-05-12 00:16:39 +00:00
protected
2010-05-12 00:16:39 +00:00
def normalize_slug
self.slug = self.name.clone if self.slug.blank? && self.name.present?
2010-05-12 00:16:39 +00:00
self.slug.slugify! if self.slug.present?
end
2010-05-12 00:16:39 +00:00
def store_asset_positions!
return if @assets_order.nil?
ids = @assets_order.split(',').collect { |id| BSON::ObjectId(id) }
ids.each_with_index do |asset_id, index|
2010-05-12 00:16:39 +00:00
self.assets.find(asset_id).position = index
end
2010-06-24 09:14:08 +00:00
self.assets.clone.each do |asset|
if !ids.include?(asset._id)
self.assets.delete(asset)
2010-05-12 00:16:39 +00:00
asset.send(:delete)
end
end
end
2010-10-29 14:19:41 +00:00
def remove_uploaded_files # callbacks are not called on each asset so we do it manually
self.assets.each do |asset|
self.asset_custom_fields.each do |field|
asset.send(:"remove_#{field._name}!") if field.kind == 'file'
end
end
end
end