2010-07-23 20:09:54 +00:00
|
|
|
module Models
|
|
|
|
module Extensions
|
|
|
|
module Page
|
|
|
|
module Parts
|
2010-06-01 00:06:46 +00:00
|
|
|
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
included do
|
2010-08-08 13:16:32 +00:00
|
|
|
embeds_many :parts, :class_name => 'PagePart'
|
|
|
|
|
2010-08-01 07:00:06 +00:00
|
|
|
before_validation do |p|
|
|
|
|
if p.parts.empty?
|
2010-08-01 07:50:29 +00:00
|
|
|
p.parts << PagePart.build_body_part(p.respond_to?(:body) ? p.body : nil)
|
2010-08-01 07:00:06 +00:00
|
|
|
end
|
|
|
|
end
|
2010-07-23 20:09:54 +00:00
|
|
|
end
|
|
|
|
|
2010-06-01 00:06:46 +00:00
|
|
|
module InstanceMethods
|
2010-07-23 20:09:54 +00:00
|
|
|
|
|
|
|
def parts_attributes=(attributes)
|
2010-06-01 00:06:46 +00:00
|
|
|
self.update_parts(attributes.values.map { |attrs| PagePart.new(attrs) })
|
|
|
|
end
|
2010-07-23 20:09:54 +00:00
|
|
|
|
2010-06-01 00:06:46 +00:00
|
|
|
def joined_parts
|
|
|
|
self.parts.enabled.map(&:template).join('')
|
|
|
|
end
|
2010-07-23 20:09:54 +00:00
|
|
|
|
2010-06-01 00:06:46 +00:00
|
|
|
protected
|
2010-07-23 20:09:54 +00:00
|
|
|
|
2010-06-01 00:06:46 +00:00
|
|
|
def update_parts(parts)
|
|
|
|
performed = []
|
|
|
|
|
|
|
|
# add / update
|
|
|
|
parts.each do |part|
|
|
|
|
if (existing = self.parts.detect { |p| p.id == part.id || p.slug == part.slug })
|
|
|
|
existing.attributes = part.attributes.delete_if { |k, v| %w{_id slug}.include?(k) }
|
|
|
|
else
|
|
|
|
self.parts << (existing = part)
|
|
|
|
end
|
|
|
|
performed << existing unless existing.disabled?
|
|
|
|
end
|
|
|
|
|
|
|
|
# disable missing parts
|
|
|
|
(self.parts.map(&:slug) - performed.map(&:slug)).each do |slug|
|
|
|
|
self.parts.detect { |p| p.slug == slug }.disabled = true
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def update_parts!(new_parts)
|
|
|
|
self.update_parts(new_parts)
|
|
|
|
self.save
|
|
|
|
end
|
2010-07-23 20:09:54 +00:00
|
|
|
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|