2011-11-10 21:41:20 +00:00
|
|
|
module Locomotive
|
2011-10-30 23:02:41 +00:00
|
|
|
class Snippet
|
|
|
|
|
|
|
|
include Locomotive::Mongoid::Document
|
|
|
|
|
|
|
|
## fields ##
|
|
|
|
field :name
|
|
|
|
field :slug
|
|
|
|
field :template
|
|
|
|
|
|
|
|
## associations ##
|
2011-11-03 13:01:08 +00:00
|
|
|
referenced_in :site, :class_name => 'Locomotive::Site'
|
2011-10-30 23:02:41 +00:00
|
|
|
|
|
|
|
## callbacks ##
|
|
|
|
before_validation :normalize_slug
|
2011-11-03 13:01:08 +00:00
|
|
|
after_save :update_templates
|
|
|
|
after_destroy :update_templates
|
2011-10-30 23:02:41 +00:00
|
|
|
|
|
|
|
## validations ##
|
|
|
|
validates_presence_of :site, :name, :slug, :template
|
|
|
|
validates_uniqueness_of :slug, :scope => :site_id
|
|
|
|
|
2011-12-05 12:29:58 +00:00
|
|
|
## behaviours ##
|
|
|
|
attr_protected :id
|
|
|
|
attr_accessible :name, :slug, :template
|
|
|
|
|
2011-10-30 23:02:41 +00:00
|
|
|
## methods ##
|
|
|
|
|
2011-12-08 15:47:17 +00:00
|
|
|
def to_presenter
|
|
|
|
Locomotive::SnippetPresenter.new(self)
|
|
|
|
end
|
|
|
|
|
2011-12-05 12:29:58 +00:00
|
|
|
def as_json(options = {})
|
2011-12-08 15:47:17 +00:00
|
|
|
self.to_presenter.as_json
|
2011-12-05 12:29:58 +00:00
|
|
|
end
|
|
|
|
|
2011-10-30 23:02:41 +00:00
|
|
|
protected
|
|
|
|
|
|
|
|
def normalize_slug
|
|
|
|
# TODO: refactor it
|
|
|
|
self.slug = self.name.clone if self.slug.blank? && self.name.present?
|
|
|
|
self.slug.permalink! if self.slug.present?
|
|
|
|
end
|
|
|
|
|
|
|
|
def update_templates
|
|
|
|
return unless (self.site rescue false) # not run if the site is being destroyed
|
|
|
|
|
|
|
|
pages = self.site.pages.any_in(:snippet_dependencies => [self.slug]).to_a
|
|
|
|
|
|
|
|
pages.each do |page|
|
|
|
|
self._change_snippet_inside_template(page.template.root)
|
|
|
|
|
|
|
|
page.send(:_serialize_template)
|
|
|
|
|
|
|
|
Page.without_callback(:save, :after, :update_template_descendants) do
|
|
|
|
page.save(:validate => false)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def _change_snippet_inside_template(node)
|
|
|
|
case node
|
|
|
|
when Locomotive::Liquid::Tags::Snippet
|
|
|
|
node.refresh(self) if node.slug == self.slug
|
|
|
|
when Locomotive::Liquid::Tags::InheritedBlock
|
|
|
|
_change_snippet_inside_template(node.parent) if node.parent
|
|
|
|
end
|
|
|
|
# Walk the children of this entry if they're available.
|
|
|
|
if node.respond_to?(:nodelist)
|
|
|
|
(node.nodelist || []).each do |child|
|
|
|
|
self._change_snippet_inside_template(child)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
end
|