2010-05-12 00:16:39 +00:00
|
|
|
class AssetCollection
|
|
|
|
include Mongoid::Document
|
|
|
|
include Mongoid::Timestamps
|
2010-05-19 23:42:19 +00:00
|
|
|
include Mongoid::CustomFields
|
2010-05-12 00:16:39 +00:00
|
|
|
|
|
|
|
## fields ##
|
|
|
|
field :name, :type => String
|
|
|
|
field :slug, :type => String
|
2010-05-21 00:34:32 +00:00
|
|
|
# field :asset_fields_counter, :type => Integer, :default => 0 # FIXME (custom fields)
|
2010-05-17 20:46:41 +00:00
|
|
|
|
2010-05-12 00:16:39 +00:00
|
|
|
|
|
|
|
## associations ##
|
|
|
|
belongs_to_related :site
|
2010-05-21 00:34:32 +00:00
|
|
|
embeds_many :assets #, :custom_fields => true # FIXME (custom fields)
|
2010-05-17 20:46:41 +00:00
|
|
|
|
2010-05-21 00:34:32 +00:00
|
|
|
# embeds_many :asset_fields # FIXME (custom fields)
|
2010-05-17 22:51:53 +00:00
|
|
|
|
|
|
|
## behaviours ##
|
2010-05-19 23:42:19 +00:00
|
|
|
custom_fields_for :assets
|
|
|
|
|
2010-05-21 00:34:32 +00:00
|
|
|
# accepts_nested_attributes_for :asset_fields, :allow_destroy => true # FIXME (custom fields)
|
2010-05-12 00:16:39 +00:00
|
|
|
|
|
|
|
## callbacks ##
|
|
|
|
before_validate :normalize_slug
|
|
|
|
before_save :store_asset_positions!
|
|
|
|
|
|
|
|
## validations ##
|
|
|
|
validates_presence_of :site, :name, :slug
|
|
|
|
validates_uniqueness_of :slug, :scope => :site_id
|
|
|
|
|
|
|
|
## methods ##
|
|
|
|
|
|
|
|
def ordered_assets
|
|
|
|
self.assets.sort { |a, b| (a.position || 0) <=> (b.position || 0) }
|
|
|
|
end
|
|
|
|
|
|
|
|
def assets_order
|
|
|
|
self.ordered_assets.collect(&:id).join(',')
|
|
|
|
end
|
|
|
|
|
|
|
|
def assets_order=(order)
|
|
|
|
@assets_order = order
|
|
|
|
end
|
2010-05-19 16:17:45 +00:00
|
|
|
|
|
|
|
def ordered_asset_fields # FIXME (custom fields)
|
|
|
|
self.asset_fields.sort { |a, b| (a.position || 0) <=> (b.position || 0) }
|
|
|
|
end
|
2010-05-12 00:16:39 +00:00
|
|
|
|
|
|
|
protected
|
|
|
|
|
|
|
|
def normalize_slug
|
|
|
|
self.slug = self.name.clone if self.slug.blank? && self.name.present?
|
|
|
|
self.slug.slugify! if self.slug.present?
|
|
|
|
end
|
|
|
|
|
|
|
|
def store_asset_positions!
|
|
|
|
return if @assets_order.nil?
|
|
|
|
|
|
|
|
@assets_order.split(',').each_with_index do |asset_id, index|
|
|
|
|
self.assets.find(asset_id).position = index
|
|
|
|
end
|
|
|
|
|
|
|
|
self.assets.each do |asset|
|
|
|
|
if !@assets_order.split(',').include?(asset._id)
|
|
|
|
self.assets.delete(asset)
|
|
|
|
asset.send(:delete)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|