Cleaning whitespace on all .rb files so commit diffs from now on will be a bit more readable

This commit is contained in:
Jacques Crocker 2010-07-23 13:09:54 -07:00
parent baf5b87a7d
commit a09329c030
146 changed files with 1385 additions and 1385 deletions

View File

@ -20,11 +20,11 @@ begin
gem.description = "a brand new CMS system with super sexy UI and cool features (alpha version for now)"
gem.homepage = %q{http://www.locomotiveapp.org}
gem.files = Dir[
"Gemfile",
"{app}/**/*",
"Gemfile",
"{app}/**/*",
"{config}/**/*",
"{lib}/**/*",
"{public}/stylesheets/admin/**/*", "{public}/javascripts/admin/**/*", "{public}/images/admin/**/*",
"{public}/stylesheets/admin/**/*", "{public}/javascripts/admin/**/*", "{public}/images/admin/**/*",
"{vendor}/**/*"]
# other fields that would normally go in your gemspec
# like authors, email and has_rdoc can also be included here
@ -33,7 +33,7 @@ begin
if dep.groups.include?(:default)
gem.add_dependency(dep.name, dep.requirement.to_s)
end
end
end
end
Jeweler::GemcutterTasks.new
rescue Exception => e

View File

@ -1,18 +1,18 @@
module Admin
class AccountsController < BaseController
sections 'settings'
def new
@account = Account.new(:email => params[:email])
end
def create
@account = Account.create(params[:account])
current_site.memberships.create(:account => @account) if @account.errors.empty?
respond_with @account, :location => edit_admin_current_site_url
end
end
end
end

View File

@ -1,12 +1,12 @@
module Admin
class ApiContentsController < ActionController::Base
include Locomotive::Routing::SiteDispatcher
before_filter :require_site
before_filter :set_content_type
def create
@content = @content_type.contents.build(params[:content])
@ -18,13 +18,13 @@ module Admin
end
end
end
protected
def set_content_type
@content_type = current_site.content_types.where(:slug => params[:slug]).first
@content_type = current_site.content_types.where(:slug => params[:slug]).first
render :json => { :error => 'Api not enabled'} and return false unless @content_type.api_enabled
end
end
end
end

View File

@ -1,23 +1,23 @@
module Admin
class AssetCollectionsController < BaseController
sections 'assets'
sections 'assets'
before_filter :set_collections
def index
if not @asset_collections.empty?
redirect_to(edit_admin_asset_collection_url(@asset_collections.first)) and return
end
end
def show
@asset_collection = current_site.asset_collections.find(params[:id])
render :action => 'edit'
end
protected
protected
def set_collections
@asset_collections = current_site.asset_collections.order_by([[:name, :asc]])
end

View File

@ -1,30 +1,30 @@
module Admin
class AssetsController < BaseController
sections 'assets'
sections 'assets'
before_filter :set_collections_and_current_collection
respond_to :json, :only => :update
def create
create! { edit_admin_asset_collection_url(@asset_collection) }
end
def update
update! { edit_admin_asset_collection_url(@asset_collection) }
end
protected
protected
def begin_of_association_chain
@asset_collection
end
def set_collections_and_current_collection
@asset_collections = current_site.asset_collections
@asset_collection = @asset_collections.find(params[:collection_id])
end
end
end

View File

@ -1,37 +1,37 @@
module Admin
class BaseController < InheritedResources::Base
include Locomotive::Routing::SiteDispatcher
layout 'admin/application'
before_filter :authenticate_admin!
before_filter :require_site
before_filter :validate_site_membership
before_filter :set_locale
helper_method :sections
# https://rails.lighthouseapp.com/projects/8994/tickets/1905-apphelpers-within-plugin-not-being-mixed-in
Dir[File.dirname(__FILE__) + "/../../helpers/**/*_helper.rb"].each do |file|
helper "admin/#{File.basename(file, '.rb').gsub(/_helper$/, '')}"
end
self.responder = Locomotive::AdminResponder # custom responder
defaults :route_prefix => 'admin'
respond_to :html
protected
def begin_of_association_chain
current_site
end
end
def self.sections(main, sub = nil)
before_filter do |c|
sub = sub.call(c) if sub.respond_to?(:call)
@ -39,18 +39,18 @@ module Admin
c.instance_variable_set(:@admin_sections, sections)
end
end
def sections(key = nil)
if !key.nil? && key.to_sym == :sub
@admin_sections[:sub] || self.controller_name.dasherize
else
else
@admin_sections[:main]
end
end
end
def set_locale
I18n.locale = current_admin.locale
end
end
end
end

View File

@ -1,7 +1,7 @@
module Admin
class ContentTypesController < BaseController
sections 'contents'
end
end
end

View File

@ -1,45 +1,45 @@
module Admin
class ContentsController < BaseController
sections 'contents'
before_filter :set_content_type
respond_to :json, :only => :update
def index
@contents = @content_type.list_or_group_contents
end
def create
create! do |success, failure|
success.html { redirect_to edit_admin_content_url(@content_type.slug, @content) }
end
end
def update
update! { edit_admin_content_url(@content_type.slug, @content) }
end
def sort
@content_type.sort_contents!(params[:order])
respond_with(@content_type, :location => admin_contents_url(@content_type.slug))
end
end
def destroy
destroy! { admin_contents_url(@content_type.slug) }
end
protected
def set_content_type
@content_type ||= current_site.content_types.where(:slug => params[:slug]).first
end
def begin_of_association_chain
set_content_type
end
end
end
end
end

View File

@ -1,24 +1,24 @@
module Admin
class CurrentSitesController < BaseController
sections 'settings', 'site'
actions :edit, :update
respond_to :json, :only => :update
def update
update! do |success, failure|
success.html { redirect_to edit_admin_current_site_url(new_host_if_subdomain_changed) }
end
end
protected
def resource
@site = current_site
end
def new_host_if_subdomain_changed
if @site.domains.include?(request.host)
{}
@ -26,6 +26,6 @@ module Admin
{ :host => "#{@site.subdomain}.#{Locomotive.config.default_domain}:#{request.port}" }
end
end
end
end
end

View File

@ -1,39 +1,39 @@
module Admin
class CustomFieldsController < BaseController
layout false
before_filter :set_parent_and_fields
def edit
@field = @fields.find(params[:id])
render :action => "edit_#{@field.kind.downcase}"
end
def update
@field = @fields.find(params[:id])
@field.updated_at = Time.now # forces mongoid to save the object
params[:custom_field][:category_items_attributes].delete('-1')
if @field.update_attributes(params[:custom_field])
render :json => @field.attributes
else
render :json => { :error => t('flash.admin.custom_fields.update.alert') }
end
end
protected
def set_parent_and_fields
if params[:parent] == 'asset_collection'
@parent = current_site.asset_collections.where(:slug => params[:slug]).first
@fields = @parent.asset_custom_fields
@fields = @parent.asset_custom_fields
else
@parent = current_site.content_types.where(:slug => params[:slug]).first
@fields = @parent.content_custom_fields
end
end
end
end
end

View File

@ -1,13 +1,13 @@
module Admin
class LayoutsController < BaseController
sections 'settings'
respond_to :json, :only => :update
def index
@layouts = current_site.layouts.order_by([[:name, :asc]])
end
end
end
end

View File

@ -1,8 +1,8 @@
module Admin
class MembershipsController < BaseController
sections 'settings'
def create
@membership = current_site.memberships.build(params[:membership])
@ -21,6 +21,6 @@ module Admin
def destroy
destroy! { edit_admin_current_site_url }
end
end
end
end

View File

@ -1,23 +1,23 @@
module Admin
class MyAccountsController < BaseController
sections 'settings', 'account'
actions :edit, :update
respond_to :json, :only => :update
def update
update! { edit_admin_my_account_url }
end
protected
def resource
@account = current_admin
end
def begin_of_association_chain; nil; end # not related directly to current_site
end
end
end

View File

@ -12,4 +12,4 @@ module Admin
end
end
end
end

View File

@ -28,4 +28,4 @@ module Admin
end
end
end
end

View File

@ -1,13 +1,13 @@
module Admin
class PasswordsController < Devise::PasswordsController
include Locomotive::Routing::SiteDispatcher
layout 'admin/login'
before_filter :require_site
helper 'admin/base', 'admin/login'
end
end
end

View File

@ -1,15 +1,15 @@
module Admin
class RenderingController < ActionController::Base
include Locomotive::Routing::SiteDispatcher
include Locomotive::Render
before_filter :require_site
def show
render_locomotive_page
end
end
end
end

View File

@ -1,19 +1,19 @@
module Admin
class SessionsController < Devise::SessionsController
include Locomotive::Routing::SiteDispatcher
layout 'admin/login'
before_filter :require_site
helper 'admin/base', 'admin/login'
protected
def after_sign_in_path_for(resource)
admin_pages_url
end
end
end
end

View File

@ -1,16 +1,16 @@
module Admin
class SitemapsController < ActionController::Base
include Locomotive::Routing::SiteDispatcher
before_filter :require_site
respond_to :xml
def show
@pages = current_site.pages.published
@host = request.host
end
end
end
end

View File

@ -1,15 +1,15 @@
module Admin
class SitesController < BaseController
sections 'settings'
def create
@site = Site.new(params[:site])
@site.memberships.build :account => @current_admin, :admin => true
create! { edit_admin_my_account_url }
end
def destroy
@site = current_admin.sites.detect { |s| s._id == params[:id] }
@ -18,13 +18,13 @@ module Admin
else
@site.errors.add(:base, 'Can not destroy the site you are logging in now')
end
respond_with @site, :location => edit_admin_my_account_url
end
protected
def begin_of_association_chain; nil; end # not related directly to current_site
end
end
end

View File

@ -1,13 +1,13 @@
module Admin
class SnippetsController < BaseController
sections 'settings'
respond_to :json, :only => :update
def index
@snippets = current_site.snippets.order_by([[:name, :asc]])
end
end
end
end

View File

@ -40,4 +40,4 @@ module Admin
end
end
end

View File

@ -1,3 +1,3 @@
class ApplicationController < ActionController::Base
class ApplicationController < ActionController::Base
protect_from_forgery
end

View File

@ -1,7 +1,7 @@
class HomeController < ApplicationController
def show; end
def unknown; end
end
end

View File

@ -1,8 +1,8 @@
module Admin::AccountsHelper
def admin_on?(site = current_site)
site.memberships.detect { |a| a.admin? && a.account == current_admin }
end
end

View File

@ -1,21 +1,21 @@
module Admin::AssetsHelper
def vignette_tag(asset)
image_tag(asset.vignette_url)
end
def image_dimensions_and_size(asset)
content_tag(:small, "#{asset.width}px x #{asset.height}px | #{number_to_human_size(asset.size)}")
end
def allow_plain_text_editing?(asset)
asset.new_record? || asset.stylesheet? || asset.javascript?
end
def image_picker_include_tags
html = javascript_include_tag 'admin/plugins/json2', 'admin/plugins/scrollTo', 'admin/plugins/codemirror/codemirror', 'admin/plugins/fancybox', 'admin/plugins/plupload/plupload.full', 'admin/plugins/imagepicker'
html += stylesheet_link_tag 'admin/plugins/fancybox', 'admin/box'
html
end
end
end

View File

@ -1,5 +1,5 @@
module Admin::BaseHelper
def title(title = nil)
if title.nil?
@content_for_title
@ -8,25 +8,25 @@ module Admin::BaseHelper
''
end
end
def admin_menu_item(name, url)
label = content_tag(:em) + escape_once('&nbsp;') + t("admin.shared.menu.#{name}")
content_tag(:li, link_to(label, url), :class => name.dasherize)
end
def admin_button_tag(text, url, options = {})
text = text.is_a?(Symbol) ? t(".#{text}") : text
link_to(url, options) do
content_tag(:em, escape_once('&nbsp;')) + text
end
end
def admin_submenu_item(name, url, options = {}, &block)
default_options = { :i18n => true, :css => name.dasherize.downcase }
default_options.merge!(options)
css = "#{'on' if name == sections(:sub)} #{'links' if block_given?} #{options[:css]}"
label_link = default_options[:i18n] ? t("admin.shared.menu.#{name}") : name
if block_given?
popup = content_tag(:div, capture(&block), :class => 'popup', :style => 'display: none')
@ -36,7 +36,7 @@ module Admin::BaseHelper
content_tag(:li, link_to(content_tag(:span, label_link), url), :class => css)
end
end
def growl_message
if not flash.empty?
%{
@ -50,5 +50,5 @@ module Admin::BaseHelper
def nocoffee_tag
link_to 'noCoffee', 'http://www.nocoffee.fr', :id => 'nocoffee'
end
end
end

View File

@ -1,36 +1,36 @@
module Admin::CustomFieldsHelper
def options_for_field_kind(selected = nil)
options = %w{String Text Category Boolean Date File}.map do |kind|
[t("admin.custom_fields.kind.#{kind.downcase}"), kind]
end
end
end
def options_for_order_by(content_type, collection_name)
options = %w{updated_at _position_in_list}.map do |type|
[t("admin.content_types.form.order_by.#{type.gsub(/^_/, '')}"), type]
end
options + options_for_highlighted_field(content_type, collection_name)
end
def options_for_highlighted_field(content_type, collection_name)
custom_fields_collection_name = "ordered_#{collection_name.singularize}_custom_fields".to_sym
collection = content_type.send(custom_fields_collection_name)
collection.delete_if { |f| f.label == 'field name' }
collection.map { |field| [field.label, field._name] }
end
def options_for_group_by_field(content_type, collection_name)
custom_fields_collection_name = "ordered_#{collection_name.singularize}_custom_fields".to_sym
collection = content_type.send(custom_fields_collection_name)
collection.delete_if { |f| not f.category? }
collection.map { |field| [field.label, field._name] }
end
def options_for_text_formatting
options = %w{none html}.map do |option|
[t("admin.custom_fields.text_formatting.#{option}"), option]
end
end
end
end

View File

@ -1,17 +1,17 @@
module Admin::LoginHelper
def login_flash_message
if not flash.empty?
content_tag :div, flash.values.first,
:id => "flash-#{flash.keys.first}",
content_tag :div, flash.values.first,
:id => "flash-#{flash.keys.first}",
:class => 'application-message'
else
''
end
end
end
def login_button_tag(label)
content_tag(:button, content_tag(:span, label), :type => 'submit', :class => 'button')
end
end
end

View File

@ -1,45 +1,45 @@
module Admin::PagesHelper
def page_main_url(page, content = nil)
url = ''
if page.site.domains.empty?
url = ''
if page.site.domains.empty?
url = main_site_url(page.site)
else
url = "http://#{current_site.domains.first}"
url += ":#{request.port}" if request.port != 80
end
if content.nil?
File.join(url, page.fullpath)
else
File.join(url, page.fullpath.gsub('/content_type_template', ''), content._slug)
File.join(url, page.fullpath.gsub('/content_type_template', ''), content._slug)
end
end
end
def parent_pages_options
roots = current_site.pages.roots.where(:slug.ne => '404').and(:_id.ne => @page.id)
returning [] do |list|
roots.each do |page|
list = add_children_to_options(page, list)
end
end
end
def add_children_to_options(page, list)
return list if page.path.include?(@page.id) || page == @page
offset = '- ' * (page.depth || 0) * 2
list << ["#{offset}#{page.title}", page.id]
page.children.each { |child| add_children_to_options(child, list) }
list
end
def options_for_page_cache_strategy
[
[t('.cache_strategy.none'), 'none'],
[t('.cache_strategy.none'), 'none'],
[t('.cache_strategy.simple'), 'simple'],
[t('.cache_strategy.hour'), 1.hour.to_s],
[t('.cache_strategy.day'), 1.day.to_s],
@ -47,5 +47,5 @@ module Admin::PagesHelper
[t('.cache_strategy.month'), 1.month.to_s]
]
end
end
end

View File

@ -1,18 +1,18 @@
module Admin::SitesHelper
def application_domain
domain = Locomotive.config.default_domain
domain += ":#{request.port}" if request.port != 80
domain
end
def main_site_url(site = current_site, options = {})
url = "http://#{site.subdomain}.#{Locomotive.config.default_domain}"
url += ":#{request.port}" if request.port != 80
url = File.join(url, controller.request.fullpath) if options.has_key?(:uri) && options[:uri]
url
end
def error_on_domain(site, name)
if (error = (site.errors[:domains] || []).detect { |n| n.include?(name) })
content_tag(:span, error, :class => 'inline-errors')
@ -20,5 +20,5 @@ module Admin::SitesHelper
''
end
end
end
end

View File

@ -1,46 +1,46 @@
class Account
include Locomotive::Mongoid::Document
# devise modules
devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable
# attr_accessible :email, :password, :password_confirmation # TODO
## attributes ##
field :name
field :locale, :default => 'en'
## validations ##
validates_presence_of :name
## associations ##
## callbacks ##
## callbacks ##
before_destroy :remove_memberships!
## methods ##
def sites
Site.where({ 'memberships.account_id' => self._id })
end
protected
def password_required?
!persisted? || !password.blank? || !password_confirmation.blank?
end
def remove_memberships!
self.sites.each do |site|
site.memberships.delete_if { |m| m.account_id == self._id }
if site.admin_memberships.empty?
raise I18n.t('errors.messages.needs_admin_account')
raise I18n.t('errors.messages.needs_admin_account')
else
site.save
end
end
end
end

View File

@ -1,12 +1,12 @@
class Asset
class Asset
include Mongoid::Document
include Mongoid::Timestamps
## Extensions ##
include Mongoid::Timestamps
## Extensions ##
include Models::Extensions::Asset::Vignette
include CustomFields::ProxyClassEnabler
## fields ##
field :name, :type => String
field :content_type, :type => String
@ -15,25 +15,25 @@ class Asset
field :size, :type => Integer
field :position, :type => Integer, :default => 0
mount_uploader :source, AssetUploader
## associations ##
embedded_in :collection, :class_name => 'AssetCollection', :inverse_of => :assets
## validations ##
validates_presence_of :name, :source
## behaviours ##
## methods ##
%w{image stylesheet javascript pdf video audio}.each do |type|
define_method("#{type}?") do
self.content_type == type
end
end
end
def to_liquid
{ :url => self.source.url }.merge(self.attributes)
end
end
end

View File

@ -1,60 +1,60 @@
class AssetCollection
include Locomotive::Mongoid::Document
## fields ##
field :name
field :slug
## associations ##
belongs_to_related :site
embeds_many :assets
## behaviours ##
custom_fields_for :assets
liquid_methods :name, :ordered_assets
## callbacks ##
before_validation :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
protected
def normalize_slug
self.slug = self.name.clone if self.slug.blank? && self.name.present?
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.clone.each do |asset|
if !@assets_order.split(',').include?(asset._id)
self.assets.delete(asset)
self.assets.delete(asset)
asset.send(:delete)
end
end
end
end
end

View File

@ -2,71 +2,71 @@ class ContentInstance
include Mongoid::Document
include Mongoid::Timestamps
## extensions ##
include CustomFields::ProxyClassEnabler
## fields (dynamic fields) ##
field :_slug
field :_position_in_list, :type => Integer, :default => 0
field :_visible, :type => Boolean, :default => true
## validations ##
validate :require_highlighted_field
## associations ##
embedded_in :content_type, :inverse_of => :contents
## callbacks ##
before_save :set_slug
before_save :set_visibility
before_create :add_to_list_bottom
## named scopes ##
named_scope :latest_updated, :order_by => [[:updated_at, :desc]], :limit => Locomotive.config.lastest_items_nb
## methods ##
alias :visible? :_visible?
def visible?
self._visible || self._visible.nil?
end
def to_liquid
Locomotive::Liquid::Drops::Content.new(self)
end
protected
def set_slug
_alias = self.highlighted_field_alias
self._slug = self.send(_alias).parameterize('_')
end
def set_visibility
field = self.content_type.content_custom_fields.detect { |f| %w{visible active}.include?(f._alias) }
self._visible = self.send(field._name) rescue true
end
def add_to_list_bottom
Rails.logger.debug "add_to_list_bottom"
self._position_in_list = self.content_type.contents.size
end
def require_highlighted_field
_alias = self.highlighted_field_alias
if self.send(_alias).blank?
self.errors.add(_alias, :blank)
end
end
def highlighted_field_value
self.send(self.content_type.highlighted_field._name)
end
def highlighted_field_alias
self.content_type.highlighted_field._alias.to_sym
end
end
end

View File

@ -1,7 +1,7 @@
class ContentType
include Locomotive::Mongoid::Document
## fields ##
field :name
field :description
@ -10,7 +10,7 @@ class ContentType
field :highlighted_field_name
field :group_by_field_name
field :api_enabled, :type => Boolean, :default => false
## associations ##
belongs_to_related :site
embeds_many :contents, :class_name => 'ContentInstance' do
@ -22,21 +22,21 @@ class ContentType
## callbacks ##
before_validation :normalize_slug
before_save :set_default_values
## validations ##
validates_presence_of :site, :name, :slug
validates_uniqueness_of :slug, :scope => :site_id
validates_size_of :content_custom_fields, :minimum => 1, :message => :array_too_short
## behaviours ##
custom_fields_for :contents
## methods ##
def groupable?
self.group_by_field && group_by_field.category?
end
def list_or_group_contents
if self.groupable?
groups = self.contents.klass.send(:"group_by_#{self.group_by_field._alias}", :ordered_contents)
@ -52,42 +52,42 @@ class ContentType
self.ordered_contents
end
end
def ordered_contents(conditions = {})
column = self.order_by.to_sym
(if conditions.nil? || conditions.empty?
self.contents
else
self.contents.where(conditions)
end).sort { |a, b| (a.send(column) || 0) <=> (b.send(column) || 0) }
end
def sort_contents!(order)
order.split(',').each_with_index do |id, position|
self.contents.find(id)._position_in_list = position
end
self.save
end
def highlighted_field
self.content_custom_fields.detect { |f| f._name == self.highlighted_field_name }
end
def group_by_field
@group_by_field ||= self.content_custom_fields.detect { |f| f._name == self.group_by_field_name }
end
protected
def set_default_values
self.order_by ||= 'updated_at'
self.highlighted_field_name ||= self.content_custom_fields.first._name
end
def normalize_slug
self.slug = self.name.clone if self.slug.blank? && self.name.present?
self.slug = self.name.clone if self.slug.blank? && self.name.present?
self.slug.slugify! if self.slug.present?
end
end
end

View File

@ -1,8 +1,8 @@
module Models
module Extensions
module Asset
module Models
module Extensions
module Asset
module Vignette
def vignette_url
if self.image?
if self.width < 80 && self.height < 80
@ -16,9 +16,9 @@ module Models
mime_type_to_url(:medium)
end
end
protected
def mime_type_to_url(size)
mime_type = File.mime_type?(self.source_filename)
filename = "unknown"
@ -35,8 +35,8 @@ module Models
File.join("admin", "icons", "filetype", size.to_s, filename + ".png")
end
end
end
end
end
end
end
end
end

View File

@ -1,28 +1,28 @@
module Models
module Extensions
module Page
module Parts
module Models
module Extensions
module Page
module Parts
extend ActiveSupport::Concern
included do
before_create { |p| p.parts << PagePart.build_body_part if p.parts.empty? }
end
end
module InstanceMethods
def parts_attributes=(attributes)
def parts_attributes=(attributes)
self.update_parts(attributes.values.map { |attrs| PagePart.new(attrs) })
end
def joined_parts
self.parts.enabled.map(&:template).join('')
end
protected
def update_parts(parts)
performed = []
@ -46,9 +46,9 @@ module Models
self.update_parts(new_parts)
self.save
end
end
end
end
end
end
end
end
end
end
end

View File

@ -1,6 +1,6 @@
module Models
module Extensions
module Page
module Models
module Extensions
module Page
module Render
def render(context)
@ -12,8 +12,8 @@ module Models
::Liquid::Template.parse("{{ content_for_layout }}").render(context)
end
end
end
end
end
end
end
end
end
end

View File

@ -1,32 +1,32 @@
module Models
module Extensions
module Page
module Templatized
module Models
module Extensions
module Page
module Templatized
extend ActiveSupport::Concern
included do
belongs_to_related :content_type
field :templatized, :type => Boolean, :default => false
field :content_type_visible_column
before_validation :set_slug_if_templatized
end
module InstanceMethods
def set_slug_if_templatized
self.slug = 'content_type_template' if self.templatized?
end
end
end
end
end
end

View File

@ -1,19 +1,19 @@
module Models
module Extensions
module Page
module Tree
module Models
module Extensions
module Page
module Tree
extend ActiveSupport::Concern
included do
include Mongoid::Acts::Tree
## fields ##
field :position, :type => Integer
## behaviours ##
acts_as_tree :order => ['position', 'asc']
## callbacks ##
before_validation :reset_parent
before_save { |p| p.send(:write_attribute, :parent_id, nil) if p.parent_id.blank? }
@ -24,10 +24,10 @@ module Models
# Fixme (Didier L.): Instances methods are defined before the include itself
alias :fix_position :hacked_fix_position
end
end
module InstanceMethods
def sort_children!(ids)
ids.each_with_index do |id, position|
child = self.children.detect { |p| p._id == id }
@ -35,15 +35,15 @@ module Models
child.save
end
end
def parent=(owner) # missing in acts_as_tree
@_parent = owner
self.fix_position(false)
self.instance_variable_set :@_will_move, true
end
protected
def change_parent
if self.parent_id_changed?
self.fix_position(false)
@ -63,15 +63,15 @@ module Models
self[depth_field] = parent[depth_field] + 1
self.save if perform_save
end
end
end
def reset_parent
if self.parent_id_changed?
@_parent = nil
end
end
def add_to_list_bottom
def add_to_list_bottom
self.position = (::Page.where(:_id.ne => self._id).and(:parent_id => self.parent_id).max(:position) || 0) + 1
end
@ -83,9 +83,9 @@ module Models
p.save
end
end
end
end
end
end
end
end
end
end
end
end

View File

@ -3,46 +3,46 @@ class Layout < LiquidTemplate
## associations ##
has_many_related :pages
embeds_many :parts, :class_name => 'PagePart'
## callbacks ##
before_save :build_parts_from_value
after_save :update_parts_in_pages
## validations ##
validates_format_of :value, :with => Locomotive::Regexps::CONTENT_FOR_LAYOUT, :message => :missing_content_for_layout
## methods ##
protected
def build_parts_from_value
if self.value_changed? || self.new_record?
self.parts.each { |p| p.disabled = true }
self.value.scan(Locomotive::Regexps::CONTENT_FOR).each do |attributes|
slug = attributes[0].strip.downcase
name = slug.humanize
name = I18n.t('attributes.defaults.page_parts.name') if slug == 'layout'
if part = self.parts.detect { |p| p.slug == slug }
part.name = name if name.present?
part.disabled = false
else
self.parts.build :slug => slug, :name => name || slug
end
end
end
# body always first
body = self.parts.detect { |p| p.slug == 'layout' }
self.parts.delete(body)
self.parts.insert(0, body)
@_update_pages = true if self.value_changed?
end
end
def update_parts_in_pages
self.pages.each { |p| p.send(:update_parts!, self.parts) } if @_update_pages
end
end
end
end

View File

@ -1,32 +1,32 @@
class LiquidTemplate
include Locomotive::Mongoid::Document
## fields ##
field :name
field :slug
field :value
## associations ##
belongs_to_related :site
## callbacks ##
before_validation :normalize_slug
## validations ##
validates_presence_of :site, :name, :slug, :value
validates_uniqueness_of :slug, :scope => :site_id
## behaviours ##
liquify_template :value
## methods ##
protected
def normalize_slug
self.slug = self.name.clone if self.slug.blank? && self.name.present?
self.slug.slugify!(:without_extension => true, :downcase => true) if self.slug.present?
end
end
end

View File

@ -1,26 +1,26 @@
class Membership
include Locomotive::Mongoid::Document
## fields ##
field :admin, :type => Boolean, :default => false
## associations ##
belongs_to_related :account
embedded_in :site, :inverse_of => :memberships
## validations ##
validates_presence_of :account
## methods ##
def email; @email; end
def email=(email)
@email = email
self.account = Account.where(:email => email).first
end
def process!
if @email.blank?
self.errors.add_on_blank(:email)
@ -35,5 +35,5 @@ class Membership
:save_it
end
end
end
end

View File

@ -96,4 +96,4 @@ class Page
self.slug.slugify!(:without_extension => true) if self.slug.present?
end
end
end

View File

@ -1,5 +1,5 @@
class PagePart
include Mongoid::Document
## fields ##
@ -8,28 +8,28 @@ class PagePart
field :value
field :disabled, :type => Boolean, :default => false
field :value
## associations ##
embedded_in :page, :inverse_of => :parts
## validations ##
validates_presence_of :name, :slug
## named scopes ##
named_scope :enabled, where(:disabled => false)
## methods ##
def template
"{% capture content_for_#{self.slug} %}#{self.value}{% endcapture %}"
end
def self.build_body_part
self.new({
:name => I18n.t('attributes.defaults.page_parts.name'),
:value => I18n.t('attributes.defaults.pages.other.body'),
:name => I18n.t('attributes.defaults.page_parts.name'),
:value => I18n.t('attributes.defaults.pages.other.body'),
:slug => 'layout'
})
end
end
end

View File

@ -93,4 +93,4 @@ class Site
end
end
end
end

View File

@ -1,3 +1,3 @@
class Snippet < LiquidTemplate
end
end

View File

@ -117,4 +117,4 @@ class ThemeAsset
self.errors.add(:source, :extname_changed)
end
end
end
end

View File

@ -7,16 +7,16 @@ class AssetUploader < CarrierWave::Uploader::Base
def store_dir
"sites/#{model.collection.site_id}/assets/#{model.id}"
end
def cache_dir
"#{Rails.root}/tmp/uploads"
end
version :thumb do
process :resize_to_fill => [50, 50]
process :convert => 'png'
end
version :medium do
process :resize_to_fill => [80, 80]
process :convert => 'png'
@ -24,18 +24,18 @@ class AssetUploader < CarrierWave::Uploader::Base
version :preview do
process :resize_to_fit => [880, 1100]
process :convert => 'png'
process :convert => 'png'
end
process :set_content_type
process :set_content_type
process :set_size
process :set_width_and_height
def set_content_type
value = :other
content_type = file.content_type == 'application/octet-stream' ? File.mime_type?(original_filename) : file.content_type
self.class.content_types.each_pair do |type, rules|
rules.each do |rule|
case rule
@ -44,20 +44,20 @@ class AssetUploader < CarrierWave::Uploader::Base
end
end
end
model.content_type = value
end
def set_size
model.size = file.size
end
def set_width_and_height
if model.image?
model.width, model.height = `identify -format "%wx%h" #{file.path}`.split(/x/).collect(&:to_i)
end
end
def self.content_types
{
:image => ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png', 'image/jpg'],
@ -67,7 +67,7 @@ class AssetUploader < CarrierWave::Uploader::Base
:stylesheet => ['text/css'],
:javascript => ['text/javascript', 'text/js', 'application/x-javascript', 'application/javascript'],
:font => ['application/x-font-ttf', 'application/vnd.ms-fontobject']
}
}
end
end

View File

@ -1,16 +1,16 @@
# encoding: utf-8
class ThemeAssetUploader < AssetUploader
process :set_content_type
process :set_content_type
process :set_size
process :set_width_and_height
version :thumb do
process :resize_to_fill => [50, 50]
process :convert => 'png'
end
version :medium do
process :resize_to_fill => [80, 80]
process :convert => 'png'
@ -18,15 +18,15 @@ class ThemeAssetUploader < AssetUploader
version :preview do
process :resize_to_fit => [880, 1100]
process :convert => 'png'
process :convert => 'png'
end
def store_dir
"sites/#{model.site_id}/themes/#{model.id}"
end
def extension_white_list
%w(jpg jpeg gif png css js swf flv)
end
end
end

View File

@ -40,7 +40,7 @@ module Locomotive
# g.template_engine :erb
# g.test_framework :test_unit, :fixture => true
# end
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"

View File

@ -31,4 +31,4 @@ end
CarrierWave.configure do |config|
config.storage = :file
config.root = File.join(Rails.root, 'public')
end
end

View File

@ -30,4 +30,4 @@ Locomotive::Application.configure do
# Enable threaded mode
# config.threadsafe!
end
end

View File

@ -30,4 +30,4 @@ end
CarrierWave.configure do |config|
config.storage = :file
end
end

View File

@ -143,4 +143,4 @@ Devise.setup do |config|
# end
# manager.default_strategies(:scope => :user).unshift :twitter_oauth
# end
end
end

View File

@ -1,6 +1,6 @@
# Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format
# Add new inflection rules using the following format
# (all these examples are active by default):
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'

View File

@ -6,24 +6,24 @@ Locomotive.configure do |config|
# Ex:
# config.default_domain = Rails.env.production? ? 'mydomain.com' : 'example.com'
config.default_domain = 'example.com'
# configure how many items we display in sub menu in the "Contents" section.
# configure how many items we display in sub menu in the "Contents" section.
config.lastest_items_nb = 5
# tell if logs are enabled. Useful for debug purpose.
config.enable_logs = true
# tell if the application is hosted on Heroku.
# Locomotive uses heroku api to add / remove domains.
# there are 2 ways of passing heroku credentials to Locomotive
# - from ENV variables: HEROKU_LOGIN & HEROKU_PASSWORD
# - from this file
#
# Notes:
# - IMPORTANT: behaviours related to this option will only be applied in production
# Notes:
# - IMPORTANT: behaviours related to this option will only be applied in production
# - credentials coming from this file take precedence over ENV variables
#
#
# Ex:
# config.heroku = { :name => '<my heroku app name>', :login => 'john@doe.net', :password => 'easy' }
config.heroku = false
end
end

View File

@ -5,4 +5,4 @@ if Rails.env.test?
g.test_framework :rspec
end
end
end
end

View File

@ -2,6 +2,6 @@
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
Rails.application.config.secret_token = 'aa84844b97e90edda8e005a686d82c3bef1f8e20a1255301f1d0886fc592a45ef2393d64b0c3d3ea858b1f6406ad6f15305666264716a79fcfa17de93ad0d69d'

View File

@ -6,4 +6,4 @@ site.save!
puts "Your first website has been created !"
puts "Admin url: http://test.example.com:3000/admin"
puts "Crendetials: admin@example.com / locomotive"
puts "Crendetials: admin@example.com / locomotive"

View File

@ -41,7 +41,7 @@ end
## Common
def create_site_and_admin_account
@site = Factory(:site, :name => 'Locomotive test website', :subdomain => 'test')
@site = Factory(:site, :name => 'Locomotive test website', :subdomain => 'test')
@admin = Factory(:account, { :name => 'Admin', :email => 'admin@locomotiveapp.org' })
@site.memberships.build :account => @admin, :admin => true
@site.save
@ -56,5 +56,5 @@ def create_layout_samples
<div id="main">\{\{ content_for_layout \}\}</div>
</body>
</html>})
Factory(:layout, :site => @site)
end
Factory(:layout, :site => @site)
end

View File

@ -1,6 +1,6 @@
# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril.
# It is recommended to regenerate this file in the future when you upgrade to a
# newer version of cucumber-rails. Consider adding your own code to a new file
# It is recommended to regenerate this file in the future when you upgrade to a
# newer version of cucumber-rails. Consider adding your own code to a new file
# instead of editing this one. Cucumber will automatically load all features/**/*.rb
# files.
@ -191,7 +191,7 @@ Then /^the "([^\"]*)" checkbox(?: within "([^\"]*)")? should not be checked$/ do
end
end
end
Then /^(?:|I )should be on (.+)$/ do |page_name|
current_path = URI.parse(current_url).path
if current_path.respond_to? :should
@ -205,8 +205,8 @@ Then /^(?:|I )should have the following query string:$/ do |expected_pairs|
query = URI.parse(current_url).query
actual_params = query ? CGI.parse(query) : {}
expected_params = {}
expected_pairs.rows_hash.each_pair{|k,v| expected_params[k] = v.split(',')}
expected_pairs.rows_hash.each_pair{|k,v| expected_params[k] = v.split(',')}
if actual_params.respond_to? :should
actual_params.should == expected_params
else

View File

@ -1,6 +1,6 @@
# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril.
# It is recommended to regenerate this file in the future when you upgrade to a
# newer version of cucumber-rails. Consider adding your own code to a new file
# It is recommended to regenerate this file in the future when you upgrade to a
# newer version of cucumber-rails. Consider adding your own code to a new file
# instead of editing this one. Cucumber will automatically load all features/**/*.rb
# files.
@ -22,7 +22,7 @@ require 'cucumber/rails/capybara_javascript_emulation' # Lets you click links wi
# steps to use the XPath syntax.
Capybara.default_selector = :css
# If you set this to false, any error raised from within your app will bubble
# If you set this to false, any error raised from within your app will bubble
# up to your step definition and out to cucumber unless you catch it somewhere
# on the way. You can make Rails rescue errors and render error pages on a
# per-scenario basis by tagging a scenario or feature with the @allow-rescue tag.
@ -43,4 +43,4 @@ Locomotive.configure do |config|
config.default_domain = 'example.com'
end
Capybara.default_host = 'test.example.com'
Capybara.default_host = 'test.example.com'

View File

@ -3,7 +3,7 @@ class String
# def perma_string(sep = '_')
# ActiveSupport::Inflector.parameterize(self, sep).to_s
# end
def slugify(options = {})
options = { :sep => '_', :without_extension => false, :downcase => false, :underscore => false }.merge(options)
# replace accented chars with ther ascii equivalents
@ -24,21 +24,21 @@ class String
s.gsub!(/[\-]/i, '_') if options[:underscore]
s
end
def slugify!(options = {})
replace(self.slugify(options))
end
end
## Hash
class Hash
def underscore_keys
new_hash = {}
self.each_pair do |key, value|
self.each_pair do |key, value|
if value.respond_to?(:collect!) # Array
value.collect do |item|
if item.respond_to?(:each_pair) # Hash item within
@ -50,13 +50,13 @@ class Hash
elsif value.respond_to?(:each_pair) # Hash
value = value.underscore_keys
end
new_key = key.is_a?(String) ? key.underscore : key # only String keys
new_hash[new_key] = value
end
self.replace(new_hash)
end
end
end

View File

@ -1,14 +1,14 @@
module Locomotive
class CopyAssetsGenerator < Rails::Generators::Base
def self.source_root
def self.source_root
@_locomotive_source_root ||= File.expand_path('../../../../../', __FILE__)
@_locomotive_source_root
end
def copy_public_files
directory 'public', 'public', :recursive => true
end
end
end
end

View File

@ -8,7 +8,7 @@ module Locomotive
def copy_initializer
template 'locomotive.rb', 'config/initializers/locomotive.rb'
end
def seed_db
append_file 'db/seeds.rb', %{
# Uncomment the following lines if you want to create the first website / account
@ -17,10 +17,10 @@ module Locomotive
#site.memberships.build :account => account, :admin => true
#site.save!}
end
def show_readme
readme 'README'
end
end
end
end

View File

@ -3,24 +3,24 @@ Locomotive.configure do |config|
# Ex:
# config.default_domain = Rails.env.production? ? 'mydomain.com' : 'example.com'
config.default_domain = 'mydomain.com'
# configure how many items we display in sub menu in the "Contents" section.
# configure how many items we display in sub menu in the "Contents" section.
config.lastest_items_nb = 5
# tell if logs are enabled. Useful for debug purpose.
config.enable_logs = true
# tell if the application is hosted on Heroku.
# Locomotive uses heroku api to add / remove domains.
# there are 2 ways of passing heroku credentials to Locomotive
# - from ENV variables: HEROKU_LOGIN & HEROKU_PASSWORD
# - from this file
#
# Notes:
# - IMPORTANT: behaviours related to this option will only be applied in production
# Notes:
# - IMPORTANT: behaviours related to this option will only be applied in production
# - credentials coming from this file take precedence over ENV variables
#
#
# Ex:
# config.heroku = { :name => '<my heroku app name>', :login => 'john@doe.net', :password => 'easy' }
config.heroku = false
end
end

View File

@ -13,43 +13,43 @@ require 'locomotive/admin_responder'
require 'mongo_session_store/mongoid'
module Locomotive
include Locomotive::Heroku
class << self
attr_accessor :config
def config
self.config = Configuration.new unless @config
@config
end
end
def self.configure
self.config ||= Configuration.new
yield(self.config)
after_configure
end
def self.after_configure
raise '[Error] Locomotive needs a default domain name' if Locomotive.config.default_domain.blank?
ActionMailer::Base.default_url_options[:host] = self.config.default_domain + (Rails.env.development? ? ':3000' : '')
# cookies stored in mongodb (mongoid_store)
Rails.application.config.session_store :mongoid_store, {
:key => Locomotive.config.cookie_key
}
# Heroku support
self.enable_heroku if self.heroku?
end
def self.logger(message)
if Locomotive.config.enable_logs == true
Rails.logger.info(message)
end
end
end
end

View File

@ -2,9 +2,9 @@ require 'responders'
module Locomotive
class AdminResponder < ::ActionController::Responder
include ::Responders::FlashResponder
def api_behavior(error)
raise error unless resourceful?
@ -20,9 +20,9 @@ module Locomotive
else
display({ :notice => controller.flash[:notice] })
end
controller.flash.discard # reset flash messages !
end
end
end
end

View File

@ -1,7 +1,7 @@
module CarrierWave
module Uploader
class Base
def to_liquid
{
:url => self.url,
@ -9,7 +9,7 @@ module CarrierWave
:size => self.size
}.stringify_keys
end
end
end
end
end

View File

@ -1,26 +1,26 @@
require 'carrierwave'
module CarrierWave
class SanitizedFile
def original_filename=(filename)
@original_filename = filename
end
def content_type=(content_type)
@content_type = content_type
end
# http://github.com/jnicklas/carrierwave/issuesearch?state=closed&q=content+type#issue/48
def copy_to_with_content_type(new_path, permissions=nil)
new_file = self.copy_to_without_content_type(new_path, permissions)
new_file.content_type = self.content_type
new_file
end
alias_method_chain :copy_to, :content_type
# FIXME (Did) CarrierWave speaks mime type now
def content_type
return @content_type if @content_type
@ -30,9 +30,9 @@ module CarrierWave
File.mime_type?(@file) if @file.is_a?(String)
end
end
end
end
module CarrierWave
@ -44,7 +44,7 @@ module CarrierWave
record.errors.add attr, options[:message] if record.send("#{attr}_integrity_error")
end
end
def validates_processing_of(*attrs)
options = attrs.last.is_a?(Hash) ? attrs.last : {}
options[:message] ||= I18n.t('carrierwave.errors.processing', :default => 'failed to be processed.')

View File

@ -1,4 +1,4 @@
module Locomotive
module Locomotive
class Configuration
@@defaults = {
@ -18,7 +18,7 @@ module Locomotive
def initialize
@@settings = self.class.get_from_hash(@@defaults)
end
def self.settings
@@settings
end
@ -43,7 +43,7 @@ module Locomotive
# specialized hash for storing configuration settings
class ConfigurationHash < Hash
# ensure that default entries always produce
# ensure that default entries always produce
# instances of the ConfigurationHash class
def default(key=nil)
include?(key) ? self[key] : self[key] = self.class.new
@ -59,11 +59,11 @@ module Locomotive
# i.e. params.id === params[:id]
# note: all keys are converted to symbols
def method_missing(name, *args, &block)
if name.to_s.ends_with? '='
if name.to_s.ends_with? '='
send :[]=, name.to_s.chomp('=').to_sym, *args
else
send(:[], name.to_sym, &block)
end
end
end
end
end
end
end

View File

@ -3,7 +3,7 @@ module CustomFields
module Types
module File
class FileUploader < ::CarrierWave::Uploader::Base
def store_dir
"sites/#{model.content_type.site_id}/contents/#{model.id}/files"
end
@ -11,8 +11,8 @@ module CustomFields
def cache_dir
"#{Rails.root}/tmp/uploads"
end
end
end
end
end
end
end

View File

@ -18,4 +18,4 @@ module Locomotive
class Engine < Rails::Engine
end
end
end

View File

@ -2,58 +2,58 @@ require 'heroku'
module Locomotive
module Heroku
extend ActiveSupport::Concern
included do
class << self
attr_accessor :heroku_connection
attr_accessor :heroku_domains
end
end
module ClassMethods
def heroku?
!self.config.heroku.nil? && self.config.heroku.respond_to?(:[])
end
def enable_heroku
raise 'Heroku application name is mandatory' if self.config.heroku[:name].blank?
self.open_heroku_connection
self.enhance_site_model
# "cache" domains for better performance
self.heroku_domains = self.heroku_connection.list_domains(self.config.heroku[:name]).collect { |h| h[:domain] }
end
def open_heroku_connection
login = self.config.heroku[:login] || ENV['HEROKU_LOGIN']
password = self.config.heroku[:password] || ENV['HEROKU_PASSWORD']
self.heroku_connection = ::Heroku::Client.new(login, password)
end
def enhance_site_model
Site.send :include, Locomotive::Heroku::CustomDomain
end
# manage domains
def add_heroku_domain(name)
Locomotive.logger "[add heroku domain] #{name}"
self.heroku_connection.add_domain(self.config.heroku[:name], name)
self.heroku_domains << name
end
def remove_heroku_domain(name)
Locomotive.logger "[remove heroku domain] #{name}"
self.heroku_connection.remove_domain(self.config.heroku[:name], name)
self.heroku_domains.delete(name)
end
end
end
end
end

View File

@ -1,21 +1,21 @@
module Locomotive
module Heroku
module CustomDomain
extend ActiveSupport::Concern
included do
after_save :add_heroku_domains
after_destroy :remove_heroku_domains
alias_method_chain :add_subdomain_to_domains, :heroku
end
module InstanceMethods
protected
def add_subdomain_to_domains_with_heroku
unless self.domains_change.nil?
full_subdomain = "#{self.subdomain}.#{Locomotive.config.default_domain}"
@ -24,13 +24,13 @@ module Locomotive
:removed => self.domains_change.first - self.domains_change.last - [full_subdomain]
}
end
add_subdomain_to_domains_without_heroku
end
def add_heroku_domains
return if @heroku_domains_change.nil?
@heroku_domains_change[:added].each do |name|
Locomotive.add_heroku_domain(name)
end
@ -38,15 +38,15 @@ module Locomotive
Locomotive.remove_heroku_domain(name)
end
end
def remove_heroku_domains
self.domains_without_subdomain.each do |name|
Locomotive.remove_heroku_domain(name)
end
end
end
end
end
end
end

View File

@ -1,2 +1,2 @@
require 'locomotive/httparty/webservice'
require 'locomotive/httparty/patches'
require 'locomotive/httparty/patches'

View File

@ -2,17 +2,17 @@ require 'crack/json'
module Crack
class JSON
def self.parse_with_tumblr(json)
cleaned_json = json.gsub(/^var\s+.+\s+=\s+/, '').gsub(/;$/, '')
parse_without_tumblr(cleaned_json)
rescue ArgumentError => e
raise ParseError, "Invalid JSON string #{e.inspect}"
end
class << self
alias_method_chain :parse, :tumblr
end
end
end
end

View File

@ -1,7 +1,7 @@
module Locomotive
module Httparty
class Webservice
include ::HTTParty
def self.consume(url, options = {})
@ -19,7 +19,7 @@ module Locomotive
self.get(path, options).try(:underscore_keys)
end
end
end
end
end

View File

@ -35,12 +35,12 @@ module InheritedResources
options[:location] ||= collection_url rescue nil
destroy_resource(object)
options[:alert] = object.errors.full_messages.first # display the first error if present
respond_with_dual_blocks(object, options, &block)
end
alias :destroy! :destroy
end
end
end

View File

@ -2,4 +2,4 @@
Dir[File.join(File.dirname(__FILE__), 'liquid', dir, '*.rb')].each { |lib| require lib }
end
::Liquid::Template.file_system = Locomotive::Liquid::DbFileSystem.new # enable snippets
::Liquid::Template.file_system = Locomotive::Liquid::DbFileSystem.new # enable snippets

View File

@ -1,18 +1,18 @@
module Locomotive
module Liquid
class DbFileSystem
# Works only with snippets
module Locomotive
module Liquid
class DbFileSystem
# Works only with snippets
def read_template_file(site, template_path)
raise FileSystemError, "Illegal snippet name '#{template_path}'" unless template_path =~ /^[^.\/][a-zA-Z0-9_\/]+$/
snippet = site.snippets.where(:slug => template_path).first
raise FileSystemError, "No such snippet '#{template_path}'" if snippet.nil?
snippet.template
end
end
end
end
end
end
end
end

View File

@ -1,19 +1,19 @@
module Locomotive
module Liquid
module Locomotive
module Liquid
module Drops
class AssetCollections < ::Liquid::Drop
class AssetCollections < ::Liquid::Drop
def initialize(site)
@site = site
end
def before_method(meth)
@site.asset_collections.where(:slug => meth.to_s)
end
end
end
end
end
end

View File

@ -1,27 +1,27 @@
# Code taken from Mephisto sources (http://mephistoblog.com/)
module Locomotive
module Liquid
module Drops
module Liquid
module Drops
class Base < ::Liquid::Drop
@@forbidden_attributes = %w{_id _version _index}
class_inheritable_reader :liquid_attributes
write_inheritable_attribute :liquid_attributes, []
attr_reader :source
delegate :hash, :to => :source
def initialize(source)
unless source.nil?
@source = source
@liquid = liquid_attributes.flatten.inject({}) { |h, k| h.update k.to_s => @source.send(k) }
end
end
def id
(@source.respond_to?(:id) ? @source.id : nil) || 'new'
end
def before_method(method)
@liquid[method.to_s]
end
@ -29,7 +29,7 @@ module Locomotive
# converts an array of records to an array of liquid drops
def self.liquify(*records, &block)
i = -1
records =
records =
records.inject [] do |all, r|
i+=1
attrs = (block && block.arity == 1) ? [r] : [r, i]
@ -41,12 +41,12 @@ module Locomotive
end
protected
def liquify(*records, &block)
self.class.liquify(*records, &block)
end
end
end
end
end
end
end

View File

@ -1,21 +1,21 @@
module Locomotive
module Liquid
module Drops
module Locomotive
module Liquid
module Drops
class Content < Base
def before_method(meth)
return '' if @source.nil?
if not @@forbidden_attributes.include?(meth.to_s)
value = @source.send(meth)
end
end
def highlighted_field_value
@source.highlighted_field_value
end
end
end
end
end
end
end
end

View File

@ -2,39 +2,39 @@ module Locomotive
module Liquid
module Drops
class Contents < ::Liquid::Drop
def initialize(site)
@site = site
end
def before_method(meth)
type = @site.content_types.where(:slug => meth.to_s).first
ProxyCollection.new(@site, type)
end
end
class ProxyCollection < ::Liquid::Drop
def initialize(site, content_type)
@site = site
@content_type = content_type
@collection = nil
end
def first
content = @content_type.ordered_contents(@context['with_scope']).first
end
def last
content = @content_type.ordered_contents(@context['with_scope']).last
end
def each(&block)
@collection ||= @content_type.ordered_contents(@context['with_scope'])
@collection.each(&block)
end
def paginate(options = {})
@collection ||= @content_type.ordered_contents(@context['with_scope']).paginate(options)
{
@ -47,11 +47,11 @@ module Locomotive
:per_page => @collection.per_page
}
end
def api
{ 'create' => @context.registers[:controller].send('admin_api_contents_url', @content_type.slug) }
end
def before_method(meth)
klass = @content_type.contents.klass # delegate to the proxy class
if (meth.to_s =~ /^group_by_.+$/) == 0
@ -61,6 +61,6 @@ module Locomotive
end
end
end
end
end
end
end
end

View File

@ -1,18 +1,18 @@
module Locomotive
module Liquid
module Drops
module Locomotive
module Liquid
module Drops
class Javascripts < ::Liquid::Drop
def initialize(site)
@site = site
end
def before_method(meth)
asset = @site.theme_assets.where(:content_type => 'javascript', :slug => meth.to_s).first
!asset.nil? ? asset.source.url : nil
end
end
end
end
end
end

View File

@ -22,4 +22,4 @@ module Locomotive
end
end
end
end
end

View File

@ -12,4 +12,4 @@ module Locomotive
end
end
end
end
end

View File

@ -1,19 +1,19 @@
module Locomotive
module Liquid
module Drops
class Stylesheets < ::Liquid::Drop
module Locomotive
module Liquid
module Drops
class Stylesheets < ::Liquid::Drop
def initialize(site)
@site = site
end
def before_method(meth)
def before_method(meth)
asset = @site.theme_assets.where(:content_type => 'stylesheet', :slug => meth.to_s).first
!asset.nil? ? asset.source.url : nil
end
end
end
end
end
end
end

View File

@ -16,4 +16,4 @@ module Locomotive
end
end
end
end

View File

@ -1,19 +1,19 @@
module Locomotive
module Liquid
module Filters
module Locomotive
module Liquid
module Filters
module Date
def localized_date(input, *args)
format, locale = args[0], args[1] rescue 'en'
date = input.is_a?(String) ? Time.parse(input) : input
if format.to_s.empty?
return input.to_s
end
date = input.is_a?(String) ? Time.parse(input) : input
if date.respond_to?(:strftime)
I18n.locale = locale
I18n.l date, :format => format
@ -21,10 +21,10 @@ module Locomotive
input
end
end
end
::Liquid::Template.register_filter(Date)
end
end
end
::Liquid::Template.register_filter(Date)
end
end
end

View File

@ -1,8 +1,8 @@
module Locomotive
module Liquid
module Filters
module Liquid
module Filters
module Html
# Write the link to a stylesheet resource
# input: url of the css file
def stylesheet_tag(input)
@ -10,7 +10,7 @@ module Locomotive
input = "#{input}.css" unless input.ends_with?('.css')
%{<link href="#{input}" media="screen" rel="stylesheet" type="text/css" />}
end
# Write the link to javascript resource
# input: url of the javascript file
def javascript_tag(input)
@ -18,15 +18,15 @@ module Locomotive
input = "#{input}.js" unless input.ends_with?('.js')
%{<script src="#{input}" type="text/javascript"></script>}
end
# Write an image tag
# input: url of the image OR asset drop
def image_tag(input, *args)
image_options = inline_options(args_to_options(args))
"<img src=\"#{File.join('/', get_path_from_asset(input))}\" #{image_options}/>"
end
# Embed a flash movie into a page
# input: url of the flash movie OR asset drop
# width: width (in pixel or in %) of the embedded movie
@ -46,15 +46,15 @@ module Locomotive
# Render the navigation for a paginated collection
def default_pagination(paginate, *args)
return '' if paginate['parts'].empty?
options = args_to_options(args)
previous_link = (if paginate['previous'].blank?
"<span class=\"disabled prev_page\">#{I18n.t('pagination.previous')}</span>"
else
"<a href=\"#{paginate['previous']['url']}\" class=\"prev_page\">#{I18n.t('pagination.previous')}</a>"
end)
links = ""
paginate['parts'].each do |part|
links << (if part['is_link']
@ -65,22 +65,22 @@ module Locomotive
"<span class=\"current\">#{part['title']}</span>"
end)
end
next_link = (if paginate['next'].blank?
"<span class=\"disabled next_page\">#{I18n.t('pagination.next')}</span>"
else
"<a href=\"#{paginate['next']['url']}\" class=\"next_page\">#{I18n.t('pagination.next')}</a>"
end)
%{<div class="pagination #{options[:css]}">
#{previous_link}
#{links}
#{next_link}
</div>}
end
protected
# Convert an array of properties ('key:value') into a hash
# Ex: ['width:50', 'height:100'] => { :width => '50', :height => '100' }
def args_to_options(*args)
@ -92,23 +92,23 @@ module Locomotive
end
options
end
# Write options (Hash) into a string according to the following pattern:
# <key1>="<value1>", <key2>="<value2", ...etc
def inline_options(options = {})
return '' if options.empty?
(options.stringify_keys.to_a.collect { |a, b| "#{a}=\"#{b}\"" }).join(' ') << ' '
end
# Get the path to be used in html tags such as image_tag, flash_tag, ...etc
# input: url (String) OR asset drop
def get_path_from_asset(input)
input.respond_to?(:url) ? input.url : input
end
end
::Liquid::Template.register_filter(Html)
end
end
end
end
end

View File

@ -1,30 +1,30 @@
module Locomotive
module Liquid
module Filters
module Filters
module Misc
def underscore(input)
input.to_s.gsub(' ', '_').gsub('/', '_').underscore
end
def dasherize(input)
input.to_s.gsub(' ', '-').gsub('/', '-').dasherize
end
def concat(input, *args)
result = input.to_s
args.flatten.each { |a| result << a.to_s }
result
end
def modulo(word, index, modulo)
(index.to_i + 1) % modulo == 0 ? word : ''
(index.to_i + 1) % modulo == 0 ? word : ''
end
end
::Liquid::Template.register_filter(Misc)
end
end
end
end
end

View File

@ -1,16 +1,16 @@
module Locomotive
module Liquid
module Filters
module Filters
module Text
def textile(input)
::RedCloth.new(input).to_html
end
end
::Liquid::Template.register_filter(Text)
end
end
end
end
end

View File

@ -1,13 +1,13 @@
module Locomotive
module Liquid
module Locomotive
module Liquid
module LiquifyTemplate
def self.included(base)
base.extend(ClassMethods)
end
# Store the parsed version of a liquid template into a column in order to increase performance
# See http://cjohansen.no/en/rails/liquid_email_templates_in_rails
# See http://cjohansen.no/en/rails/liquid_email_templates_in_rails
#
# class Page
# liquify_template :body
@ -15,33 +15,33 @@ module Locomotive
#
# page = Page.new :body => '...some liquid tags'
# page.template # Liquid::Template
#
#
#
module ClassMethods
def liquify_template(source = :value)
field :serialized_template, :type => Binary
before_validation :store_template
class_eval <<-EOV
def liquify_template_source
self.send(:#{source.to_s})
end
EOV
include InstanceMethods
end
end
module InstanceMethods
def template
Marshal.load(read_attribute(:serialized_template).to_s) rescue nil
end
protected
def store_template
begin
template = ::Liquid::Template.parse(self.liquify_template_source)
@ -50,8 +50,8 @@ module Locomotive
self.errors.add :template, :liquid_syntax_error
end
end
end
end
end
end
end
end
end
end

View File

@ -1,21 +1,21 @@
module Locomotive
module Liquid
module Tags
module Liquid
module Tags
class Blueprint < ::Liquid::Tag
def render(context)
%{
<link href="/stylesheets/admin/blueprint/screen.css" media="screen, projection" rel="stylesheet" type="text/css" />
<link href="/stylesheets/admin/blueprint/print.css" media="print" rel="stylesheet" type="text/css" />
<!--[if IE]>
<link href="/stylesheets/admin/blueprint/ie.css" media="screen, projection" rel="stylesheet" type="text/css" />
<![endif]-->
<link href="/stylesheets/admin/blueprint/print.css" media="print" rel="stylesheet" type="text/css" />
<!--[if IE]>
<link href="/stylesheets/admin/blueprint/ie.css" media="screen, projection" rel="stylesheet" type="text/css" />
<![endif]-->
}
end
end
::Liquid::Template.register_tag('blueprint_stylesheets', Blueprint)
end
end
end
::Liquid::Template.register_tag('blueprint_stylesheets', Blueprint)
end
end
end

View File

@ -1,4 +1,4 @@
module Locomotive
module Locomotive
module Liquid
module Tags
# Consume web services as easy as pie directly in liquid !
@ -12,7 +12,7 @@ module Locomotive
# {% endconsume %}
#
class Consume < ::Liquid::Block
Syntax = /(#{::Liquid::VariableSignature}+)\s*from\s*(#{::Liquid::QuotedString}+)/
def initialize(tag_name, markup, tokens)
@ -27,20 +27,20 @@ module Locomotive
raise ::Liquid::SyntaxError.new("Syntax Error in 'consume' - Valid syntax: consume <var> from \"<url>\" [username: value, password: value]")
end
super
super
end
def render(context)
context.stack do
context.scopes.last[@target.to_s] = Locomotive::Httparty::Webservice.consume(@url, @options.symbolize_keys)
render_all(@nodelist, context)
end
end
end
end
::Liquid::Template.register_tag('consume', Consume)
end
end
end
end

View File

@ -1,6 +1,6 @@
module Liquid
module Locomotive
module Tags
module Liquid
module Locomotive
module Tags
class Jquery < ::Liquid::Tag
def render(context)
@ -10,8 +10,8 @@ module Liquid
}
end
end
::Liquid::Template.register_tag('jQuery', Jquery)
end
end
end
::Liquid::Template.register_tag('jQuery', Jquery)
end
end
end

Some files were not shown because too many files have changed in this diff Show More