refactoring (wip)

This commit is contained in:
Didier Lafforgue 2012-04-06 12:23:11 +02:00
parent 260f9ae4ef
commit e26febdaf6
39 changed files with 225 additions and 457 deletions

View File

@ -16,12 +16,9 @@ class Locomotive.Models.Page extends Backbone.Model
toJSON: -> toJSON: ->
_.tap super, (hash) => _.tap super, (hash) =>
_.each ['content_type_id_text', 'edit_url', 'parent_id_text', 'response_type_text'], (key) => delete hash[key] _.each ['edit_url', 'parent_id_text', 'response_type_text'], (key) => delete hash[key]
delete hash['editable_elements'] delete hash['editable_elements']
hash.editable_elements = @get('editable_elements').toJSONForSave() if @get('editable_elements')? && @get('editable_elements').length > 0 hash.editable_elements = @get('editable_elements').toJSONForSave() if @get('editable_elements')? && @get('editable_elements').length > 0
delete hash['target_klass_name']
hash.target_klass_name = @get('target_klass_name') if @get('templatized') == true
class Locomotive.Models.PagesCollection extends Backbone.Collection class Locomotive.Models.PagesCollection extends Backbone.Collection

View File

@ -41,7 +41,7 @@ class Locomotive.Views.Pages.FormView extends Locomotive.Views.Shared.FormView
@enable_response_type_select() @enable_response_type_select()
# enable check boxes # enable check boxes
@enable_templatized_checkbox() @enable_wildcard_checkbox()
@enable_redirect_checkbox() @enable_redirect_checkbox()
@ -112,11 +112,6 @@ class Locomotive.Views.Pages.FormView extends Locomotive.Views.Shared.FormView
data: { parent_id: @$('#page_parent_id').val(), slug: @$('#page_slug').val() } data: { parent_id: @$('#page_parent_id').val(), slug: @$('#page_slug').val() }
success: (data) => success: (data) =>
@$('#page_slug_input .inline-hints').html(data.url).effect('highlight') @$('#page_slug_input .inline-hints').html(data.url).effect('highlight')
if data.templatized_parent
@$('li#page_slug_input').show()
@$('li#page_templatized_input, li#page_target_klass_name_input').hide()
else
@$('li#page_templatized_input, li#page_target_klass_name_input').show()
enable_response_type_select: -> enable_response_type_select: ->
@$('li#page_response_type_input').change (event) => @$('li#page_response_type_input').change (event) =>
@ -126,19 +121,13 @@ class Locomotive.Views.Pages.FormView extends Locomotive.Views.Shared.FormView
@model.set redirect: false @model.set redirect: false
@$('li#page_redirect_input, li#page_redirect_url_input').hide() @$('li#page_redirect_input, li#page_redirect_url_input').hide()
enable_templatized_checkbox: -> enable_wildcard_checkbox: ->
@_enable_checkbox 'templatized', @_enable_checkbox 'wildcard',
features: ['slug', 'redirect', 'listed'] features: ['redirect', 'listed']
on_callback: =>
@$('li#page_target_klass_name_input').show()
off_callback: =>
@$('li#page_target_klass_name_input').hide()
@$('li#page_templatized_input').hide() if @model.get('templatized_from_parent') == true
enable_redirect_checkbox: -> enable_redirect_checkbox: ->
@_enable_checkbox 'redirect', @_enable_checkbox 'redirect',
features: ['templatized', 'cache_strategy'] features: ['wildcard', 'cache_strategy']
on_callback: => on_callback: =>
@$('li#page_redirect_url_input').show() @$('li#page_redirect_url_input').show()
off_callback: => off_callback: =>

View File

@ -289,7 +289,7 @@ ul.list {
cursor: move; cursor: move;
} }
&.templatized > .inner > a { &.wildcard > .inner > a {
padding-right: 24px; padding-right: 24px;
background: transparent image-url("locomotive/list/icons/template.png") no-repeat right 2px; background: transparent image-url("locomotive/list/icons/template.png") no-repeat right 2px;
} }

View File

@ -53,10 +53,10 @@ module Locomotive
end end
def get_path def get_path
page = current_site.pages.build(:parent => current_site.pages.find(params[:parent_id]), :slug => params[:slug].permalink).tap do |p| page = current_site.pages.build(:parent => current_site.pages.find(params[:parent_id]), :slug => params[:slug].permalink, :wildcard => params[:wildcard]).tap do |p|
p.valid?; p.send(:build_fullpath) p.valid?; p.send(:build_fullpath)
end end
render :json => { :url => public_page_url(page), :slug => page.slug, :templatized_parent => page.templatized_from_parent? } render :json => { :url => public_page_url(page), :slug => page.slug }
end end
end end

View File

@ -2,7 +2,7 @@ module Locomotive
module PagesHelper module PagesHelper
def css_for_page(page) def css_for_page(page)
%w(index not_found templatized redirect).inject([]) do |memo, state| %w(index not_found wildcard redirect).inject([]) do |memo, state|
memo << state.dasherize if page.send(:"#{state}?") memo << state.dasherize if page.send(:"#{state}?")
memo memo
end.join(' ') end.join(' ')
@ -32,13 +32,6 @@ module Locomotive
list list
end end
def options_for_target_klass_name
base_models = current_site.content_types.map do |type|
[type.name.humanize, type.klass_with_custom_fields(:entries)]
end
base_models + Locomotive.config.models_for_templatization.map { |name| [name.underscore.humanize, name] }
end
def options_for_page_cache_strategy def options_for_page_cache_strategy
[ [
[t('.cache_strategy.none'), 'none'], [t('.cache_strategy.none'), 'none'],

View File

@ -20,11 +20,13 @@ module Locomotive
# before_rearrange :foo #propagate_fullpath_changes # before_rearrange :foo #propagate_fullpath_changes
# after_save :propagate_fullpath_changes # after_save :propagate_fullpath_changes
# after_save { |p| puts "[after_save] #{p.fullpath} / #{p.wildcards.inspect} / #{p.wildcard?}" }
## scopes ## ## scopes ##
# scope :fullpath, lambda { |fullpath| { :where => { :fullpath => fullpath } } } # used ? # scope :fullpath, lambda { |fullpath| { :where => { :fullpath => fullpath } } } # used ?
## virtual attributes ## ## virtual attributes ##
attr_accessor :wildcards_map attr_accessor :wildcards_hash
end end
@ -60,6 +62,47 @@ module Locomotive
end.join('/') end.join('/')
end end
# It returns the fullpath with wildcard segments replaced by the values
# specified in the first argument.
#
# @param [ Hash ] values The map assigning to a wildcard name its value
# @return [ String ] The compiled fullpath
#
def compiled_fullpath(values)
return self.fullpath unless self.has_wildcards?
index = 0
self.fullpath.split('/').map do |segment|
if segment == '*'
"#{values[self.wildcards[index]]}".tap { index += 1 }
else
segment
end
end.join('/')
end
# It builds the map associating the name of a wildcard
# with its value within the path.
# The map is also stored in the wildcards_hash attribute
# of the page.
#
# @param [ String ] path the path from the HTTP request
# @return [ Hash ] The map
#
def match_wildcards(path)
self.wildcards_hash, wildcard_index, segments = {}, 0, self.fullpath.split('/')
path.split('/').each_with_index do |segment, index|
if segments[index] == '*'
self.wildcards_hash[self.wildcards[wildcard_index].underscore] = segment
wildcard_index += 1
end
end
self.wildcards_hash
end
protected protected
# def set_children_autosave # def set_children_autosave
@ -71,17 +114,16 @@ module Locomotive
return true if self.parent.nil? return true if self.parent.nil?
if self.parent.has_wildcards? if self.parent.has_wildcards?
puts "[get_wildcards_from_parent] #{self.slug} - #{self.parent.wildcards.inspect}" # puts "[get_wildcards_from_parent] #{self.slug} - #{self.parent.wildcards.inspect}"
self.wildcards = self.parent.wildcards self.wildcards = self.parent.wildcards.clone
elsif !self.wildcard? else
self.wildcards = nil # puts "[get_wildcards_from_parent] #{self.slug} - reset wildcards"
self.wildcards = []
end end
true
end end
def add_slug_to_wildcards def add_slug_to_wildcards
puts "[add_slug_to_wildcards] #{self.slug} / #{self.wildcard?}" # puts "[add_slug_to_wildcards] #{self.slug} / #{self.wildcard?}"
(self.wildcards ||= []) << self.slug if self.wildcard? (self.wildcards ||= []) << self.slug if self.wildcard?
end end
@ -89,56 +131,56 @@ module Locomotive
if self.index? || self.not_found? if self.index? || self.not_found?
self.fullpath = self.slug self.fullpath = self.slug
else else
slugs = self.ancestors_and_self.map { |page| page.wildcard? ? '*' : page.slug } segments = (self.parent.fullpath.try(:split, '/') || [nil]) + [self.wildcard? ? '*' : self.slug]
slugs.shift unless slugs.size == 1 segments.shift if segments.first == 'index'
self.fullpath = File.join slugs.compact self.fullpath = File.join segments.compact
end end
end end
def must_propagate_fullpath_changes? # def must_propagate_fullpath_changes?
self.wildcard_changed? || self.slug_changed? # self.wildcard_changed? || self.slug_changed?
end # end
#
def propagate_fullpath_changes # def propagate_fullpath_changes
return true unless must_propagate_fullpath_changes? # return true unless must_propagate_fullpath_changes?
#
parent_identities = { self._id => self } # parent_identities = { self._id => self }
#
Rails.logger.debug "[propagate_fullpath_changes] BEGIN page #{self.slug} #{self.fullpath} / #{self.wildcards.inspect} / #{self._parent.try(:has_wildcards?).inspect}" # Rails.logger.debug "[propagate_fullpath_changes] BEGIN page #{self.slug} #{self.fullpath} / #{self.wildcards.inspect} / #{self._parent.try(:has_wildcards?).inspect}"
puts "[propagate_fullpath_changes] BEGIN page #{self.slug} #{self.fullpath} / #{self.wildcards.inspect} / #{self._parent.try(:has_wildcards?).inspect}" # puts "[propagate_fullpath_changes] BEGIN page #{self.slug} #{self.fullpath} / #{self.wildcards.inspect} / #{self._parent.try(:has_wildcards?).inspect}"
#
self.descendants.order_by([[:depth, :asc]]).each do |page| # self.descendants.order_by([[:depth, :asc]]).each do |page|
_parent = parent_identities[page.parent_id] # _parent = parent_identities[page.parent_id]
_fullpath = {} # _fullpath = {}
_wildcards = nil # _wildcards = nil
#
puts "[propagate_fullpath_changes] #{page.fullpath} / #{page.wildcards.inspect} / #{page._parent.try(:has_wildcards?).inspect}" # puts "[propagate_fullpath_changes] #{page.fullpath} / #{page.wildcards.inspect} / #{page._parent.try(:has_wildcards?).inspect}"
#
if _parent.has_wildcards? # if _parent.has_wildcards?
_wildcards = _parent.wildcards + (page.wildcard? ? [page.slug] : []) # _wildcards = _parent.wildcards + (page.wildcard? ? [page.slug] : [])
end # end
#
self.site.locales.each do |locale| # self.site.locales.each do |locale|
base_fullpath = _parent.fullpath_translations[locale] # base_fullpath = _parent.fullpath_translations[locale]
slug = page.wildcard? ? '*' : page.slug_translations[locale] # slug = page.wildcard? ? '*' : page.slug_translations[locale]
#
next if base_fullpath.blank? # next if base_fullpath.blank?
#
_fullpath[locale] = File.join(base_fullpath, slug) # _fullpath[locale] = File.join(base_fullpath, slug)
end # end
#
selector = { 'id' => page._id } # selector = { 'id' => page._id }
operations = { # operations = {
'$set' => { # '$set' => {
'wildcards' => _wildcards, # 'wildcards' => _wildcards,
'fullpath' => _fullpath # 'fullpath' => _fullpath
} # }
} # }
self.collection.update selector, operations # self.collection.update selector, operations
#
parent_identities[page._id] = page # parent_identities[page._id] = page
end # end
end # end
end end
end end

View File

@ -11,11 +11,10 @@ module Locomotive
module ClassMethods module ClassMethods
# Given both a site and a path, this method tries # Given both a site and a path, this method retrieves
# to get the matching page. # the matching page if it exists.
# If the page is templatized, the related content entry is # If the found page owns wildcards in its fullpath, then
# associated to the page (page.content_entry stores the entry). # assigns the value for each wildcard and store the result within the page.
# If no page is found, then it returns the 404 one instead.
# #
# @param [ Site ] site The site where to find the page # @param [ Site ] site The site where to find the page
# @param [ String ] path The fullpath got from the request # @param [ String ] path The fullpath got from the request
@ -33,17 +32,7 @@ module Locomotive
if !_page.published? && !logged_in if !_page.published? && !logged_in
next next
else else
if _page.templatized? _page.match_wildcards(path)
%r(^#{_page.fullpath.gsub('content_type_template', '([^\/]+)')}$) =~ path
permalink = $1
_page.content_entry = _page.fetch_target_entry(permalink)
if _page.content_entry.nil? || (!_page.content_entry.visible? && !logged_in) # content instance not found or not visible
next
end
end
end end
page = _page page = _page

View File

@ -1,213 +0,0 @@
# module Locomotive
# module Extensions
# module Page
# module Templatized
#
# extend ActiveSupport::Concern
#
# included do
#
# ## fields ##
# field :wildcards, :type => Array
# field :with_wildcards, :type => Boolean, :default => false
# field :fullpath_with_wildcards, :default => false, :localize => true
#
# ## callbacks ##
# before_validation :get_wildcards_from_parent
# before_validation :add_slug_to_wildcards
# before_save :build_fullpath_with_wildcards
# after_save :propagate_wildcards
#
# ## scopes ##
#
# ## virtual attributes ##
# attr_accessor :wildcards_map
#
# end
#
# protected
#
# def get_wildcards_from_parent
# return if self.parent.nil?
#
# if self.parent.with_wildcards?
# self.wildcards = self.parent.wildcards
# self.with_wildcards = true
# elsif !self.with_wildcards?
# self.wildcards = []
# self.with_wildcards = false
# end
# end
#
# def add_slug_to_wildcards
# (self.wildcards ||= []) << self.slug if self.will_wildcards?
# end
#
# def build_fullpath_with_wildcards
# if self.index? || self.not_found?
# self.fullpath_with_wildcards = self.slug
# else
# slugs = self.ancestors_and_self.map { |page| page.with_wildcards? ? '*' : page.slug }
# slugs.shift unless slugs.size == 1
# self.fullpath_with_wildcards = File.join slugs.compact
# end
# end
#
# def propagate_wildcards
# return unless self.with_wildcards_changed? || (self.with_wildcards? && self.slug_changed?)
#
# parent_identities = { self._id => self }
#
# self.descendants.order_by([[:depth, :asc]]).each do |page|
# _parent = parent_identities[page._id]
# _wildcards = _parent.wildcards + (page.wildcards? ? [page.slug] : [])
# _fullpath_with_wildcards = File.join(_parent.fullpath_with_wildcards, page.wildcards? ? '*' : page.slug)
#
# # TODO: fullpath_with_wildcards is localized !!!!
#
# selector = { 'id' => page._id }
# operations = {
# '$set' => {
# 'wildcards' => _wildcards,
# 'with_wildcards' => true,
# 'fullpath_with_wildcards' => _fullpath_with_wildcards
# }
# }
# self.collection.update selector, operations
#
# parent_identities[page._id] = page
# end
# end
#
# end
# end
# end
# end
#
#
#
# # field :templatized_from_parent, :type => Boolean, :default => false
# # field :target_klass_name
# #
# # ## validations ##
# # validates_presence_of :target_klass_name, :if => :templatized?
# # validate :ensure_target_klass_name_security
# #
# # ## callbacks ##
# # before_validation :get_templatized_from_parent
# # before_validation :set_slug_if_templatized
# # before_validation :ensure_target_klass_name_security
# # after_save :propagate_templatized
# #
# # ## scopes ##
# # scope :templatized, :where => { :templatized => true }
# #
# # ## virtual attributes ##
# # attr_accessor :content_entry
# # end
# #
# # # Returns the class specified by the target_klass_name property
# # #
# # # @example
# # #
# # # page.target_klass_name = 'Locomotive::Entry12345'
# # # page.target_klass = Locomotive::Entry12345
# # #
# # # @return [ Class ] The target class
# # #
# # def target_klass
# # target_klass_name.constantize
# # end
# #
# # # Gives the name which can be used in a liquid template in order
# # # to reference an entry. It uses the slug property if the target klass
# # # is a Locomotive content type or the class name itself for the other classes.
# # #
# # # @example
# # #
# # # page.target_klass_name = 'Locomotive::Entry12345' # related to the content type Articles
# # # page.target_entry_name = 'article'
# # #
# # # page.target_klass_name = 'OurProduct'
# # # page.target_entry_name = 'our_product'
# # #
# # # @return [ String ] The name in lowercase and underscored
# # #
# # def target_entry_name
# # if self.target_klass_name =~ /^Locomotive::Entry([a-z0-9]+)$/
# # @content_type ||= self.site.content_types.find($1)
# # @content_type.slug.singularize
# # else
# # self.target_klass_name.underscore
# # end
# # end
# #
# # # Finds the entry both specified by the target klass and identified by the permalink
# # #
# # # @param [ String ] permalink The permalink of the entry
# # #
# # # @return [ Object ] The document
# # #
# # def fetch_target_entry(permalink)
# # target_klass.find_by_permalink(permalink)
# # end
# #
# # protected
# #
# # def get_templatized_from_parent
# # return if self.parent.nil?
# #
# # if self.parent.templatized?
# # self.templatized = self.templatized_from_parent = true
# # self.target_klass_name = self.parent.target_klass_name
# # elsif !self.templatized?
# # self.templatized = self.templatized_from_parent = false
# # self.target_klass_name = nil
# # end
# # end
# #
# # def set_slug_if_templatized
# # self.slug = 'content_type_template' if self.templatized? && !self.templatized_from_parent?
# # end
# #
# # # Makes sure the target_klass is owned by the site OR
# # # if it belongs to the models allowed by the application
# # # thanks to the models_for_templatization option.
# # #
# # def ensure_target_klass_name_security
# # return if !self.templatized? || self.target_klass_name.blank?
# #
# # if self.target_klass_name =~ /^Locomotive::Entry([a-z0-9]+)$/
# # content_type = Locomotive::ContentType.find($1)
# #
# # if content_type.site_id != self.site_id
# # self.errors.add :target_klass_name, :security
# # end
# # elsif !Locomotive.config.models_for_templatization.include?(self.target_klass_name)
# # self.errors.add :target_klass_name, :security
# # end
# # end
# #
# # # Sets the templatized, templatized_from_parent properties of
# # # the children of the current page ONLY IF the templatized
# # # attribute got changed.
# # #
# # def propagate_templatized
# # return unless self.templatized_changed?
# #
# # selector = { 'parent_ids' => { '$in' => [self._id] } }
# # operations = {
# # '$set' => {
# # 'templatized' => self.templatized,
# # 'templatized_from_parent' => self.templatized,
# # 'target_klass_name' => self.target_klass_name
# # }
# # }
# #
# # self.collection.update selector, operations, :multi => true
# # end
# #
# # end
# # end
# # end
# # end

View File

@ -1,7 +1,7 @@
module Locomotive module Locomotive
class PagePresenter < BasePresenter class PagePresenter < BasePresenter
delegate :title, :slug, :fullpath, :handle, :raw_template, :published, :listed, :templatized, :templatized_from_parent, :redirect, :redirect_url, :template_changed, :cache_strategy, :response_type, :to => :source delegate :title, :slug, :fullpath, :handle, :raw_template, :published, :listed, :wildcard, :wildcards, :redirect, :redirect_url, :template_changed, :cache_strategy, :response_type, :to => :source
def escaped_raw_template def escaped_raw_template
h(self.source.raw_template) h(self.source.raw_template)
@ -12,7 +12,7 @@ module Locomotive
end end
def included_methods def included_methods
super + %w(title slug fullpath handle raw_template published listed templatized templatized_from_parent redirect redirect_url cache_strategy response_type template_changed editable_elements localized_fullpaths) super + %w(title slug fullpath handle raw_template published listed wildcard wildcards redirect redirect_url cache_strategy response_type template_changed editable_elements localized_fullpaths)
end end
def localized_fullpaths def localized_fullpaths

View File

@ -16,7 +16,7 @@
- if not @page.index? and not @page.not_found? - if not @page.index? and not @page.not_found?
= f.input :parent_id, :as => :select, :collection => parent_pages_options, :include_blank => false = f.input :parent_id, :as => :select, :collection => parent_pages_options, :include_blank => false
= f.input :slug, :required => false, :hint => @page.slug.blank? ? t('.empty_slug') : public_page_url(@page), :input_html => { :'data-url' => get_path_pages_url, :disabled => @page.index? || @page.not_found? }, :wrapper_html => { :style => "#{'display: none' if @page.templatized? && !@page.templatized_from_parent?};", :class => 'em-inline-hints' } = f.input :slug, :required => false, :hint => @page.slug.blank? ? t('.empty_slug') : public_page_url(@page), :input_html => { :'data-url' => get_path_pages_url, :disabled => @page.index? || @page.not_found? }, :class => 'em-inline-hints' }
= f.inputs :name => :seo, :class => "inputs foldable #{'folded' if inputs_folded?(@page)}" do = f.inputs :name => :seo, :class => "inputs foldable #{'folded' if inputs_folded?(@page)}" do
@ -34,15 +34,13 @@
= f.input :response_type, :as => :select, :collection => options_for_page_response_type, :include_blank => false = f.input :response_type, :as => :select, :collection => options_for_page_response_type, :include_blank => false
= f.input :templatized, :as => :'Locomotive::Toggle', :style => "#{'display: none' if @page.redirect? || @page.templatized_from_parent?}" = f.input :wildcard, :as => :'Locomotive::Toggle', :style => "#{'display: none' if @page.redirect?}"
= f.input :target_klass_name, :as => :select, :collection => options_for_target_klass_name, :include_blank => false, :wrapper_html => { :style => "#{'display: none' unless @page.templatized? && !@page.templatized_from_parent?}" }
= f.input :published, :as => :'Locomotive::Toggle' = f.input :published, :as => :'Locomotive::Toggle'
= f.input :listed, :as => :'Locomotive::Toggle' = f.input :listed, :as => :'Locomotive::Toggle'
= f.input :redirect, :as => :'Locomotive::Toggle', :wrapper_html => { :style => "#{'display: none' if @page.templatized? || !@page.default_response_type?}" } = f.input :redirect, :as => :'Locomotive::Toggle', :wrapper_html => { :style => "#{'display: none' if !@page.default_response_type?}" }
= f.input :cache_strategy, :as => :select, :collection => options_for_page_cache_strategy, :include_blank => false, :wrapper_html => { :style => "#{'display: none' if @page.redirect?}" } = f.input :cache_strategy, :as => :select, :collection => options_for_page_cache_strategy, :include_blank => false, :wrapper_html => { :style => "#{'display: none' if @page.redirect?}" }

View File

@ -3,7 +3,7 @@
%li{ :id => "item-#{page.id}", :class => "page #{css_for_page(page)}" } %li{ :id => "item-#{page.id}", :class => "page #{css_for_page(page)}" }
- children = can?(:manage, page) ? page.children : page.children.find_all { |p| !p.templatized? } - children = page.children
- with_children = !children.empty? - with_children = !children.empty?

View File

@ -8,14 +8,8 @@ xml.urlset "xmlns" => "http://www.sitemaps.org/schemas/sitemap/0.9" do
@pages.each do |page| @pages.each do |page|
if not page.index_or_not_found? if not page.index_or_not_found?
if page.templatized? if page.wildcard?
page.content_type.entries.visible.each do |c| # FIXME (Didier L.) unable for now to generate all the pages
xml.url do
xml.loc page_url(page, { :content => c, :host => true })
xml.lastmod c.updated_at.to_date.to_s('%Y-%m-%d')
xml.priority 0.9
end
end
else else
xml.url do xml.url do
xml.loc page_url(page, { :host => true }) xml.loc page_url(page, { :host => true })

View File

@ -57,7 +57,7 @@ de:
title: Titel title: Titel
parent: Parent parent: Parent
slug: Slug slug: Slug
templatized: Templatized wildcard: Wildcard
published: Veröffentlicht published: Veröffentlicht
listed: Im Menü listed: Im Menü
redirect: Umleitung redirect: Umleitung

View File

@ -58,7 +58,7 @@ es:
parent_id: Padre parent_id: Padre
slug: Enlace slug: Enlace
listed: Menu listed: Menu
templatized: Templatizada wildcard: Wildcard
published: Publicada published: Publicada
redirect: Redirección redirect: Redirección
redirect_url: Url de redirección redirect_url: Url de redirección

View File

@ -58,7 +58,7 @@ fr:
parent_id: Dossier parent parent_id: Dossier parent
slug: Raccourci slug: Raccourci
listed: Menu listed: Menu
templatized: Templatisée wildcard: Wildcard
published: Publiée published: Publiée
redirect: Redirection redirect: Redirection
redirect_url: Url de redirection redirect_url: Url de redirection

View File

@ -64,7 +64,7 @@ it:
parent_id: Pagina superiore parent_id: Pagina superiore
slug: Slug slug: Slug
listed: In menù listed: In menù
templatized: Templatized wildcard: Wildcard
published: Pubblicata published: Pubblicata
redirect: Redirezione redirect: Redirezione
redirect_url: Url di redirezione redirect_url: Url di redirezione

View File

@ -221,7 +221,7 @@
parent: Tilhører parent: Tilhører
parent_id: Tilhører parent_id: Tilhører
slug: Slug slug: Slug
templatized: Templatized wildcard: Wildcard
published: Publisert published: Publisert
listed: I meny listed: I meny
redirect: Videresending redirect: Videresending

View File

@ -60,7 +60,7 @@ pt-BR:
title: Título title: Título
parent: Pai parent: Pai
slug: Slug slug: Slug
templatized: Template wildcard: Wildcard
published: Publicado published: Publicado
cache_strategy: Cache cache_strategy: Cache
content_type: content_type:

View File

@ -37,7 +37,7 @@ ru:
title: Имя title: Имя
parent: Родитель parent: Родитель
slug: Ссылка slug: Ссылка
templatized: Шаблонизирована wildcard: Wildcard
published: Опубликована published: Опубликована
listed: Меню listed: Меню
redirect: Перенаправлена redirect: Перенаправлена

View File

@ -55,9 +55,7 @@ de:
page: page:
published: "Nur authentifizierte Accounts können nicht publizierte Seiten ansehen." published: "Nur authentifizierte Accounts können nicht publizierte Seiten ansehen."
cache_strategy: "Cache die Seiten, um eine bessere Geschwindigkeit zu erzielen. Die 'Einfach' Option ist ein guter Kompromiss." cache_strategy: "Cache die Seiten, um eine bessere Geschwindigkeit zu erzielen. Die 'Einfach' Option ist ein guter Kompromiss."
templatized: "Nutze diese Seite als Vorlage für einen Baustein, den du erstellt hast."
listed: "Regele, ob die Seite in den generierten Menüs angezeigt werden soll." listed: "Regele, ob die Seite in den generierten Menüs angezeigt werden soll."
content_type_id: "Der Baustein für den diese Seite als Vorlage dienen soll."
seo_title: "Wähle einen Titel für den 'title' Tag im Seiten Header. Lass es leer, wenn der Seitentitel verwendet werden soll." seo_title: "Wähle einen Titel für den 'title' Tag im Seiten Header. Lass es leer, wenn der Seitentitel verwendet werden soll."
meta_keywords: "Meta-Schlagworte, die im HEAD-Bereich der Webseite genutzt werden. Die einzelnen Wörter werden durch eine Leertaste getrennt. Diese werden für die Suchmaschinen benötigt." meta_keywords: "Meta-Schlagworte, die im HEAD-Bereich der Webseite genutzt werden. Die einzelnen Wörter werden durch eine Leertaste getrennt. Diese werden für die Suchmaschinen benötigt."
meta_description: "Meta-Beschreibung, die im HEAD-Bereich der Webseite genutzt wird. Diese wird für die Suchmaschinen benötigt." meta_description: "Meta-Beschreibung, die im HEAD-Bereich der Webseite genutzt wird. Diese wird für die Suchmaschinen benötigt."

View File

@ -57,9 +57,8 @@ en:
handle: "Unique identifier to retrieve this page within an external controller instance" handle: "Unique identifier to retrieve this page within an external controller instance"
published: "Only authenticated accounts can view unpublished pages." published: "Only authenticated accounts can view unpublished pages."
cache_strategy: "Cache the page for better performance. The 'Simple' choice is a good compromise." cache_strategy: "Cache the page for better performance. The 'Simple' choice is a good compromise."
templatized: "Use the page as a template for a model you defined." wildcard: "Make the page have a wildcard segment in its path. Then the slug will be used as the name of the wildcard in the template"
listed: "Control whether to show the page from generated menus." listed: "Control whether to show the page from generated menus."
target_klass_name: "The type of content this page will be a template for."
seo_title: "Define a page title which should be used as the value for the title tag in the head section. Leave it empty if you want to use the default value from the site settings." seo_title: "Define a page title which should be used as the value for the title tag in the head section. Leave it empty if you want to use the default value from the site settings."
meta_keywords: "Overrides the site's meta keywords used within the head tag of the page. They are separated by a comma." meta_keywords: "Overrides the site's meta keywords used within the head tag of the page. They are separated by a comma."
meta_description: "Overrides the site's meta description used within the head tag of the page." meta_description: "Overrides the site's meta description used within the head tag of the page."
@ -84,7 +83,7 @@ en:
source: "The current file is available here %{url}" source: "The current file is available here %{url}"
content_entry: content_entry:
_slug: "Property used to generate the url of a page working as a template for this content type (ex: \"template_page/{{ your_object._permalink }})\"." _slug: "Property used to generate the url of a page working as a template for this content type (ex: \"template_page/{{ your_object._permalink }})\"."
seo_title: "The value you fill in will replace the SEO title of the templatized page related to your model." seo_title: "The value you fill in can be used to replace the SEO title in any pages."
meta_keywords: "Overrides the site's meta keywords used within the head tag of the page. They are separated by a comma." meta_keywords: "Overrides the site's meta keywords used within the head tag of the page. They are separated by a comma."
meta_description: "Overrides the site's meta description used within the head tag of the page." meta_description: "Overrides the site's meta description used within the head tag of the page."
import: import:

View File

@ -49,9 +49,7 @@ es:
page: page:
published: "Las páginas no publicadas son únicamente visibles tras iniciar sesión." published: "Las páginas no publicadas son únicamente visibles tras iniciar sesión."
cache_strategy: "Utilizar una caché de página para un mejor rendimiento. La opción 'Simple' es un buen compromiso." cache_strategy: "Utilizar una caché de página para un mejor rendimiento. La opción 'Simple' es un buen compromiso."
templatized: "Usar la página como plantilla de un modelo."
listed: "Controla si la página se enseña o no en los menús." listed: "Controla si la página se enseña o no en los menús."
content_type_id: "El modelo del cual será una plantilla esta página."
meta_keywords: "Reescribir las palabras clave SEO utilizadas en la cabecera de la página. Deben estar separadas por comas." meta_keywords: "Reescribir las palabras clave SEO utilizadas en la cabecera de la página. Deben estar separadas por comas."
meta_description: "Reescribir la metadescripción que se utiliza en la cabecera de la página." meta_description: "Reescribir la metadescripción que se utiliza en la cabecera de la página."
snippet: snippet:

View File

@ -53,9 +53,8 @@ fr:
page: page:
published: "Seuls les administrateurs authentifiés peuvent voir une page non publiée." published: "Seuls les administrateurs authentifiés peuvent voir une page non publiée."
cache_strategy: "Cache la page pour de meilleure performance. L'option 'Simple' est le meilleur compromis." cache_strategy: "Cache la page pour de meilleure performance. L'option 'Simple' est le meilleur compromis."
templatized: "Utilise la page comme un template pour un modèle défini." wildcard: "Détermine si la page aura la dernière partie de son URL dynamique. Si oui, le slug sera utilisé comme nom du segment dans le template."
listed: "Controle si la page doit être visible depuis les menus automatiquement générés." listed: "Controle si la page doit être visible depuis les menus automatiquement générés."
target_klass_name: "Le type du contenu pour lequel cette page est un template."
seo_title: "Définit un titre de page à mettre dans la balise TITLE de la page. Laissez le blanc pour utiliser la valeur par défaut (voir configuration du site)." seo_title: "Définit un titre de page à mettre dans la balise TITLE de la page. Laissez le blanc pour utiliser la valeur par défaut (voir configuration du site)."
meta_keywords: "Redéfinit les mots-clés du site. Utilisés à l'intérieur de la balise HEAD. Ils sont séparés par une virgule." meta_keywords: "Redéfinit les mots-clés du site. Utilisés à l'intérieur de la balise HEAD. Ils sont séparés par une virgule."
meta_description: "Redéfinit la description du site. Utilisée à l'intérieur de la balise HEAD." meta_description: "Redéfinit la description du site. Utilisée à l'intérieur de la balise HEAD."

View File

@ -55,9 +55,7 @@ it:
page: page:
published: "Solo gli account autenticati possono visualizzare le pagine non pubblicate." published: "Solo gli account autenticati possono visualizzare le pagine non pubblicate."
cache_strategy: "Attiva il cache della pagina per miglirare le prestazioni. L'opzione 'Semplice' è un buon compromesso." cache_strategy: "Attiva il cache della pagina per miglirare le prestazioni. L'opzione 'Semplice' è un buon compromesso."
templatized: "Utilizzare la pagina come template per un modello che hai definito."
listed: "Determina se la pagina deve essere mostrata nei menù generati." listed: "Determina se la pagina deve essere mostrata nei menù generati."
content_type_id: "Il tipo di contenuto di cui questa pagina sarà il template."
seo_title: "Definisce il titolo della pagina inserito nel tag title della sezione head. Lascia vuoto se vuoi che venga utilizzato il titolo definito per il sito." seo_title: "Definisce il titolo della pagina inserito nel tag title della sezione head. Lascia vuoto se vuoi che venga utilizzato il titolo definito per il sito."
meta_keywords: "Sovrascrive per questa pagina le meta keywords definite per il sito all'interno del tag head della pagina. Sono separate da virgola." meta_keywords: "Sovrascrive per questa pagina le meta keywords definite per il sito all'interno del tag head della pagina. Sono separate da virgola."
meta_description: "Sovrascrive per questa pagina la meta description definita per il sito." meta_description: "Sovrascrive per questa pagina la meta description definita per il sito."

View File

@ -49,9 +49,7 @@ nl:
page: page:
published: "Alleen geauthenticeerde accounts kunnen niet gepubliceerde pagina's zien." published: "Alleen geauthenticeerde accounts kunnen niet gepubliceerde pagina's zien."
cache_strategy: "Cache de pagina voor betere prestaties. De 'Simpele' keus is een goed compromis." cache_strategy: "Cache de pagina voor betere prestaties. De 'Simpele' keus is een goed compromis."
templatized: "Gebruik de pagina als template voor een door u gedefinieerd model."
listed: "Controleer of de pagina getoond wordt van de gegenereerde menu's." listed: "Controleer of de pagina getoond wordt van de gegenereerde menu's."
content_type_id: "Het type inhoud waar deze pagina als template voor dient"
meta_keywords: "Overschrijft de meta keywords van de website in de head tag van deze pagina. Gescheiden door een komma" meta_keywords: "Overschrijft de meta keywords van de website in de head tag van deze pagina. Gescheiden door een komma"
meta_description: "Overschrijft de meta description van de website in de head tag van deze pagina." meta_description: "Overschrijft de meta description van de website in de head tag van deze pagina."
snippet: snippet:

View File

@ -55,9 +55,7 @@
page: page:
published: "Kun autoriserte kontoer kan se ikke-publiserte sider" published: "Kun autoriserte kontoer kan se ikke-publiserte sider"
cache_strategy: "Buffre siden for å bedre ytelsen. \"Enkel\" er et bra kompromiss." cache_strategy: "Buffre siden for å bedre ytelsen. \"Enkel\" er et bra kompromiss."
templatized: "Bruk denne siden som mal for en modell."
listed: "Styr om siden skal vises i de genererte menyene." listed: "Styr om siden skal vises i de genererte menyene."
content_type_id: "Innholdstypen denne siden skal være mal for."
seo_title: "Definer en egen tittel for siden. Denne blir benyttet av nettleseren. Hvis denne står tom blir standardverdien fra sideinnstillingene benyttet." seo_title: "Definer en egen tittel for siden. Denne blir benyttet av nettleseren. Hvis denne står tom blir standardverdien fra sideinnstillingene benyttet."
meta_keywords: "Overstyr søkemotor-metadata for denne siden. Separer med komma." meta_keywords: "Overstyr søkemotor-metadata for denne siden. Separer med komma."
meta_description: "Overstyr søkemotorbeskrivelsen for denne siden." meta_description: "Overstyr søkemotorbeskrivelsen for denne siden."

View File

@ -46,7 +46,6 @@ pt-BR:
page: page:
published: "Apenas contas autenticadas podem ver páginas não publicadas." published: "Apenas contas autenticadas podem ver páginas não publicadas."
cache_strategy: 'Faça o Cache da página para obter melhor desempenho. A escolha do "Simples" é um bom compromisso' cache_strategy: 'Faça o Cache da página para obter melhor desempenho. A escolha do "Simples" é um bom compromisso'
templatized: "Utilize a página como template para o modelo definido."
snippet: snippet:
slug: "Você precisa saber a ordem para inserir fragmentos dentro da página." slug: "Você precisa saber a ordem para inserir fragmentos dentro da página."
site: site:

View File

@ -55,9 +55,7 @@ ru:
page: page:
published: "Только аутентифицированным пользователям разрешается просматривать неопубликованные страницы." published: "Только аутентифицированным пользователям разрешается просматривать неопубликованные страницы."
cache_strategy: "Кэшировать страницу для лучшей производительности. Вариант 'Простое' является хорошим компромиссом." cache_strategy: "Кэшировать страницу для лучшей производительности. Вариант 'Простое' является хорошим компромиссом."
templatized: "Используйте страницу в качестве шаблона для определенной вами модели."
listed: "Контролируйте возможность показа страницы из сгенерированных меню." listed: "Контролируйте возможность показа страницы из сгенерированных меню."
content_type_id: "Тип содержимого, для которого эта страница будет выступать в качестве шаблона."
seo_title: "Определите заголовок страницы, который будет использоваться как значение тэга title в секции head. Оставьте пустым, если вы хотите использовать значение по умолчанию из настроек сайта." seo_title: "Определите заголовок страницы, который будет использоваться как значение тэга title в секции head. Оставьте пустым, если вы хотите использовать значение по умолчанию из настроек сайта."
meta_keywords: "Переопределяет meta keywords сайта, используемые внутри тэга head страницы. Они разделены запятыми." meta_keywords: "Переопределяет meta keywords сайта, используемые внутри тэга head страницы. Они разделены запятыми."
meta_description: "Переопределяет meta description сайта, используемые внутри тэга head страницы." meta_description: "Переопределяет meta description сайта, используемые внутри тэга head страницы."

View File

@ -45,9 +45,6 @@ Locomotive.configure do |config|
# follow the Dependency Injection pattern # follow the Dependency Injection pattern
# config.context_assign_extensions = {} # config.context_assign_extensions = {}
# add extra classes other than the defined content types among a site which will potentially used by the templatized pages.
# config.models_for_templatization = %w(Product)
# Rack-cache settings, mainly used for the inline resizing image module. Default options: # Rack-cache settings, mainly used for the inline resizing image module. Default options:
# config.rack_cache = { # config.rack_cache = {
# :verbose => true, # :verbose => true,

View File

@ -3,14 +3,18 @@ module Locomotive
module Drops module Drops
class Page < Base class Page < Base
delegate :seo_title, :meta_keywords, :meta_description, :to => '_source' delegate :title, :seo_title, :meta_keywords, :meta_description, :to => '_source'
def title def title
self._source.templatized? ? @context['entry']._label : self._source.title # TODO
# self._source.templatized? ? @context['entry']._label : self._source.title
self._source.title
end end
def slug def slug
self._source.templatized? ? self._source.content_type.slug.singularize : self._source.slug # TODO
# self._source.templatized? ? self._source.content_type.slug.singularize : self._source.slug
self._source.slug
end end
def parent def parent

View File

@ -42,11 +42,14 @@ module Locomotive
output += @site.locales.collect do |locale| output += @site.locales.collect do |locale|
::Mongoid::Fields::I18n.with_locale(locale) do ::Mongoid::Fields::I18n.with_locale(locale) do
fullpath = @site.localized_page_fullpath(@page, locale) # fullpath = @site.localized_page_fullpath(@page, locale)
if @page.templatized? # if @page.templatized?
fullpath.gsub!('content_type_template', context['entry']._permalink) # fullpath.gsub!('content_type_template', context['entry']._permalink)
end # end
# TODO: TO BE TESTED
fullpath = @page.compiled_fullpath(@page.wildcards_hash)
%(<a href="/#{fullpath}" class="#{locale} #{'current' if locale == context['current_locale']}">#{link_label(locale)}</a>) %(<a href="/#{fullpath}" class="#{locale} #{'current' if locale == context['current_locale']}">#{link_label(locale)}</a>)
end end

View File

@ -134,7 +134,7 @@ module Locomotive
# Determines whether or not a page should be a part of the menu # Determines whether or not a page should be a part of the menu
def include_page?(page) def include_page?(page)
if !page.listed? || page.templatized? || !page.published? if !page.listed? || page.has_wildcards? || !page.published?
false false
elsif @options[:exclude] elsif @options[:exclude]
(page.fullpath =~ @options[:exclude]).nil? (page.fullpath =~ @options[:exclude]).nil?

View File

@ -12,28 +12,6 @@ module Mongoid#:nodoc:
end end
end end
# module Relations #:nodoc:
# module AutoSave
# module ClassMethods #:nodoc:
# def autosave(metadata)
# if metadata.autosave?
# set_callback :save, :after do |document|
# relation = document.send(metadata.name)
#
# return true if document.try(:"autosave_for_#{metadata.name}?") == false # FIXME (Didier L.) add more control on the document side
#
# if relation
# (relation.do_or_do_not(:in_memory) || Array.wrap(relation)).each do |doc|
# doc.save
# end
# end
# end
# end
# end
# end
# end
# end
module Fields #:nodoc: module Fields #:nodoc:
module Internal #:nodoc: module Internal #:nodoc:
class RawArray < Mongoid::Fields::Internal::Array class RawArray < Mongoid::Fields::Internal::Array

View File

@ -62,10 +62,7 @@ module Locomotive
assigns.merge!(flash.to_hash.stringify_keys) # data from public submissions assigns.merge!(flash.to_hash.stringify_keys) # data from public submissions
if @page.templatized? # add instance from content type assigns.merge!(@page.wildcards_hash.stringify_keys) if @page.has_wildcards?
assigns['entry'] = @page.content_entry
assigns[@page.target_entry_name] = @page.content_entry # just here to help to write readable liquid code
end
registers = { registers = {
:controller => self, :controller => self,

View File

@ -56,9 +56,6 @@ Locomotive.configure do |config|
# follow the Dependency Injection pattern # follow the Dependency Injection pattern
# config.context_assign_extensions = {} # config.context_assign_extensions = {}
# add extra classes other than the defined content types among a site which will potentially used by the templatized pages.
config.models_for_templatization = %w(Foo)
# Rack-cache settings, mainly used for the inline resizing image module. Default options: # Rack-cache settings, mainly used for the inline resizing image module. Default options:
# config.rack_cache = { # config.rack_cache = {
# :verbose => true, # :verbose => true,

View File

@ -71,13 +71,14 @@ describe Locomotive::Liquid::Drops::Page do
render_template('{{ home.title }}').should == 'Home page' render_template('{{ home.title }}').should == 'Home page'
end end
it 'renders the content instance highlighted field instead for a templatized page' do # TODO
templatized = FactoryGirl.build(:page, :title => 'Lorem ipsum template', :templatized => true) # it 'renders the content instance highlighted field instead for a templatized page' do
# templatized = FactoryGirl.build(:page, :title => 'Lorem ipsum template', :templatized => true)
entry = Locomotive::Liquid::Drops::ContentEntry.new(mock('entry', :_label => 'Locomotive rocks !')) #
# entry = Locomotive::Liquid::Drops::ContentEntry.new(mock('entry', :_label => 'Locomotive rocks !'))
render_template('{{ page.title }}', 'page' => templatized, 'entry' => entry).should == 'Locomotive rocks !' #
end # render_template('{{ page.title }}', 'page' => templatized, 'entry' => entry).should == 'Locomotive rocks !'
# end
end end

View File

@ -15,7 +15,7 @@ describe Locomotive::Liquid::Tags::Nav do
Locomotive::Page.new(:title => 'Child #2.1', :fullpath => 'child_2/sub_child_1', :slug => 'sub_child_1', :published => true), Locomotive::Page.new(:title => 'Child #2.1', :fullpath => 'child_2/sub_child_1', :slug => 'sub_child_1', :published => true),
Locomotive::Page.new(:title => 'Child #2.2', :fullpath => 'child_2/sub_child_2', :slug => 'sub_child_2', :published => true), Locomotive::Page.new(:title => 'Child #2.2', :fullpath => 'child_2/sub_child_2', :slug => 'sub_child_2', :published => true),
Locomotive::Page.new(:title => 'Unpublished #2.2', :fullpath => 'child_2/sub_child_unpublishd_2', :slug => 'sub_child_unpublished_2', :published => false), Locomotive::Page.new(:title => 'Unpublished #2.2', :fullpath => 'child_2/sub_child_unpublishd_2', :slug => 'sub_child_unpublished_2', :published => false),
Locomotive::Page.new(:title => 'Templatized #2.3', :fullpath => 'child_2/sub_child_template_3', :slug => 'sub_child_template_3', :published => true, :templatized => true), Locomotive::Page.new(:title => 'Templatized #2.3', :fullpath => 'child_2/sub_child_template_3', :slug => 'sub_child_template_3', :published => true, :wildcard => true),
Locomotive::Page.new(:title => 'Unlisted #2.4', :fullpath => 'child_2/sub_child_unlisted_4', :slug => 'sub_child_unlisted_4', :published => true, :listed => false) Locomotive::Page.new(:title => 'Unlisted #2.4', :fullpath => 'child_2/sub_child_unlisted_4', :slug => 'sub_child_unlisted_4', :published => true, :listed => false)
] ]
@home.children.last.stubs(:children_with_minimal_attributes).returns(other_children) @home.children.last.stubs(:children_with_minimal_attributes).returns(other_children)
@ -55,7 +55,7 @@ describe Locomotive::Liquid::Tags::Nav do
output.should match /<\/a><\/li><\/ul><\/li><\/ul>/ output.should match /<\/a><\/li><\/ul><\/li><\/ul>/
end end
it 'does not render templatized pages' do it 'does not render pages with wildcards' do
output = render_nav('site', {}, 'depth: 2') output = render_nav('site', {}, 'depth: 2')
output.should_not match /sub-child-template-3/ output.should_not match /sub-child-template-3/

View File

@ -128,37 +128,22 @@ describe 'Locomotive rendering system' do
end end
context 'templatized page' do context 'wildcards page' do
before(:each) do before(:each) do
@content_type = FactoryGirl.build(:content_type, :site => nil) @page.attributes = { 'wildcards' => %w(permalink), 'fullpath' => 'projects/*', 'wildcard' => true }
@content_entry = @content_type.entries.build(:_visible => true)
@page.templatized = true
@page.stubs(:fetch_target_entry).returns(@content_entry)
@page.stubs(:fullpath).returns('/projects/content_type_template')
@controller.request.fullpath = '/projects/edeneo.html' @controller.request.fullpath = '/projects/edeneo.html'
@controller.current_site.pages.expects(:where).with(:depth => 2, :fullpath.in => %w{projects/edeneo projects/content_type_template content_type_template/edeneo}).returns([@page]) @controller.current_site.pages.expects(:where).with(:depth => 2, :fullpath.in => %w{projects/edeneo projects/* */edeneo */*}).returns([@page])
end end
it 'sets the content_entry variable' do it 'finds the page' do
page = @controller.send(:locomotive_page) page = @controller.send(:locomotive_page)
page.should_not be_nil page.should_not be_nil
page.content_entry.should == @content_entry
end end
it 'returns the 404 page if the instance does not exist' do it 'assigns values to wildcards' do
@page.stubs(:fetch_target_entry).returns(nil) page = @controller.send(:locomotive_page)
(klass = Locomotive::Page).expects(:published).returns([true]) page.wildcards_hash.should == { 'permalink' => 'edeneo' }
@controller.current_site.pages.expects(:not_found).returns(klass)
@controller.send(:locomotive_page).should be_true
end
it 'returns the 404 page if the instance is not visible' do
@content_entry._visible = false
@page.stubs(:fetch_target_entry).returns(@content_entry)
(klass = Locomotive::Page).expects(:published).returns([true])
@controller.current_site.pages.expects(:not_found).returns(klass)
@controller.send(:locomotive_page).should be_true
end end
end end

View File

@ -25,6 +25,12 @@ describe Locomotive::Page do
@page.pretty_fullpath.should == 'archives/:month/projects/:permalink' @page.pretty_fullpath.should == 'archives/:month/projects/:permalink'
end end
it 'compiles a fullpath with wildcards' do
@page.fullpath = 'archives/*/projects/*'
@page.wildcards = %w(month permalink)
@page.compiled_fullpath('month' => 'june', 'permalink' => 'hello-world').should == 'archives/june/projects/hello-world'
end
describe 'building the fullpath' do describe 'building the fullpath' do
it 'returns "index" for the root page' do it 'returns "index" for the root page' do
@ -45,16 +51,13 @@ describe Locomotive::Page do
end end
it 'includes a single "*" if the page enables wildcards and if there are a lot of ancestors' do it 'includes a single "*" if the page enables wildcards and if there are a lot of ancestors' do
@page.stubs(:ancestors_and_self).returns([FactoryGirl.build(:page), FactoryGirl.build(:page, :slug => 'archives'), FactoryGirl.build(:page, :slug => 'projects'), @page]) @page.stubs(:parent).returns(FactoryGirl.build(:page, :fullpath => 'archives/projects'))
@page.send(:build_fullpath) @page.send(:build_fullpath)
@page.fullpath.should == 'archives/projects/*' @page.fullpath.should == 'archives/projects/*'
end end
it 'includes many "*" when there are ancestors enabling wildcards' do it 'includes many "*" when there are ancestors enabling wildcards' do
@page.stubs(:ancestors_and_self).returns([FactoryGirl.build(:page), @page.stubs(:parent).returns(FactoryGirl.build(:page, :fullpath => 'archives/*/projects'))
FactoryGirl.build(:page, :slug => 'archives'),
FactoryGirl.build(:page, :slug => 'month', :wildcard => true),
FactoryGirl.build(:page, :slug => 'projects'), @page])
@page.send(:build_fullpath) @page.send(:build_fullpath)
@page.fullpath.should == 'archives/*/projects/*' @page.fullpath.should == 'archives/*/projects/*'
end end
@ -101,9 +104,7 @@ describe Locomotive::Page do
end end
it 'turns a page into a wildcards one' do it 'turns a page into a wildcards one' do
Rails.logger.debug "=========== START ============"
@month_page.update_attributes :wildcard => true @month_page.update_attributes :wildcard => true
Rails.logger.debug "=========== END ============"
@project_page.reload @project_page.reload
@project_page.fullpath.should == 'archives/*/projects/*' @project_page.fullpath.should == 'archives/*/projects/*'
@posts_page.reload @posts_page.reload
@ -111,21 +112,52 @@ describe Locomotive::Page do
end end
it 'turns off the wildcard property of page' do it 'turns off the wildcard property of page' do
puts "==== 1 ==="
Rails.logger.debug "==== 1 ==="
puts "@month_page = #{@month_page.fullpath.inspect} / #{@month_page.wildcards.inspect}"
@month_page.update_attributes :wildcard => true @month_page.update_attributes :wildcard => true
puts "==== 2 === "
Rails.logger.debug "==== 2 ==="
@month_page.update_attributes :wildcard => false @month_page.update_attributes :wildcard => false
puts "---- DONE ----"
Rails.logger.debug "==== DONE ==="
@project_page.reload @project_page.reload
@project_page.fullpath.should == 'archives/month/projects/*' @project_page.fullpath.should == 'archives/month/projects/*'
@project_page.wildcards.should == %w(project) @project_page.wildcards.should == %w(project)
@posts_page.reload @posts_page.reload
@posts_page.fullpath.should == 'archives/month/posts' @posts_page.fullpath.should == 'archives/month/posts'
@posts_page.wildcards.should == nil @posts_page.wildcards.should == []
end
end
describe 'building the hash map asssociating a wildcard name with its value from a path' do
it 'returns an empty map for non wildcards fullpath' do
@page.fullpath = 'index'
@page.wildcards = nil
@page.match_wildcards('index').should be_empty
end
it 'underscores the wildcard name in the returned hash map' do
@page.fullpath = 'projects/*'
@page.wildcards = %w(my-permalink)
@page.match_wildcards('projects/hello-world').should == { 'my_permalink' => 'hello-world' }
end
it 'returns a map with one element if the fullpath contains a single wildcard' do
@page.fullpath = 'projects/*'
@page.wildcards = %w(permalink)
@page.match_wildcards('projects/hello-world').should == { 'permalink' => 'hello-world' }
end
it 'returns a map with as many elements as there are wildcards in the fullpath' do
@page.fullpath = 'archives/*/projects/*'
@page.wildcards = %w(month permalink)
@page.match_wildcards('archives/june/projects/hello-world').should == {
'month' => 'june',
'permalink' => 'hello-world'
}
end
it 'stores the map inside a virtual attribute' do
@page.fullpath = 'projects/*'
@page.wildcards = %w(permalink)
@page.match_wildcards('projects/hello-world')
@page.wildcards_hash.should == { 'permalink' => 'hello-world' }
end end
end end