engine/app/models/asset_collection.rb

61 lines
1.2 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-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-05-12 00:16:39 +00:00
## validations ##
validates_presence_of :site, :name, :slug
validates_uniqueness_of :slug, :scope => :site_id
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-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?
2010-05-12 00:16:39 +00:00
@assets_order.split(',').each_with_index do |asset_id, index|
self.assets.find(asset_id).position = index
end
2010-06-24 09:14:08 +00:00
self.assets.clone.each do |asset|
2010-05-12 00:16:39 +00:00
if !@assets_order.split(',').include?(asset._id)
self.assets.delete(asset)
2010-05-12 00:16:39 +00:00
asset.send(:delete)
end
end
end
end