All Files (82.89% covered at 14.68 hits/line)
51 files in total.
1368 relevant lines.
1134 lines covered and
234 lines missed
- 1
class Admin::ConfigurationController < ApplicationController
# Admin::ConfigurationController handles the batch-updating of TrustyCms::Config entries.
# It accepts any set of config name-value pairs but is accessible only to administrators.
# Note that configuration is routed as a singular resource so we only deal with show/edit/update
# and the show and edit views determine what set of config values is shown and made editable.
- 1
before_action :initialize_config
- 1
only_allow_access_to :edit, :update,
:when => [:admin],
:denied_url => { :controller => 'admin/configuration', :action => 'show' },
:denied_message => 'You must have admin privileges to edit site configuration.'
- 1
def show
- 5
@user = current_user
- 5
render
end
- 1
def edit
- 1
render
end
- 1
def update
- 1
if params[:trusty_config]
- 1
begin
- 1
TrustyCms.config.transaction do
- 1
params[:trusty_config].each_pair do |key, value|
- 10
@trusty_config[key] = TrustyCms::Config.find_or_initialize_by(key: key)
- 10
@trusty_config[key].value = value # validation sets errors on @trusty_config['key'] that the helper methods will pick up
end
- 1
redirect_to :action => :show
end
rescue ActiveRecord::RecordInvalid => e
flash[:error] = "Configuration error: please check the form"
render :action => :edit
rescue TrustyCms::Config::ConfigError => e
flash[:error] = "Configuration error: #{e}"
render :action => :edit
end
end
end
- 1
protected
- 1
def initialize_config
- 7
@trusty_config = {}
end
end
- 1
class Admin::ExtensionsController < ApplicationController
- 1
only_allow_access_to :index,
:when => :admin,
:denied_url => { :controller => 'pages', :action => 'index' },
:denied_message => 'You must have administrative privileges to perform this action.'
- 1
def index
@template_name = 'index' # for Admin::RegionsHelper
@extensions = TrustyCms::Extension.descendants.sort_by { |e| e.extension_name }
end
end
- 1
class Admin::LayoutsController < Admin::ResourceController
- 1
paginate_models
- 1
only_allow_access_to :index, :show, :new, :create, :edit, :update, :remove, :destroy,
:when => [:designer, :admin],
:denied_url => { :controller => 'admin/pages', :action => 'index' },
:denied_message => 'You must have designer privileges to perform this action.'
end
- 1
class Admin::PagesController < Admin::ResourceController
- 1
before_action :initialize_meta_rows_and_buttons, :only => [:new, :edit, :create, :update]
- 1
before_action :count_deleted_pages, :only => [:destroy]
- 1
rescue_from ActiveRecord::RecordInvalid, :with => :validation_error
- 1
class PreviewStop < ActiveRecord::Rollback
- 1
def message
'Changes not saved!'
end
end
- 1
create_responses do |r|
- 1
r.plural.js do
@level = params[:level].to_i
@index = params[:index].to_i
@rendered_html = ""
@template_name = 'index'
self.models = Page.find(params[:page_id]).children.all
response.headers['Content-Type'] = 'text/html;charset=utf-8'
render :action => 'children.html.haml', :layout => false
end
end
- 1
def index
- 22
@homepage = Page.find_by_parent_id(nil)
- 22
response_for :plural
end
- 1
def new
- 2
@page = self.model = model_class.new_with_defaults(trusty_config)
- 2
assign_page_attributes
- 2
response_for :new
end
- 1
def preview
render_preview
rescue PreviewStop => exception
render :text => exception.message unless @performed_render
end
- 1
def save_table_position
new_position = params[:new_position]
Page.save_order(new_position)
head :ok
end
- 1
private
- 1
def validation_error(e)
flash[:error] = e.message
render :new
end
- 1
def assign_page_attributes
- 2
if params[:page_id].blank?
- 2
self.model.slug = '/'
end
- 2
self.model.parent_id = params[:page_id]
end
- 1
def model_class
- 148
if Page.descendants.any? { |d| d.to_s == params[:page_class] }
verify_page_class(params[:page_class])
- 74
elsif params[:page_id]
Page.find(params[:page_id]).children
else
- 74
Page
end
end
- 1
def render_preview
Page.transaction do
page_class = Page.descendants.include?(model_class) ? model_class : Page
if request.referer =~ %r{/admin/pages/(\d+)/edit}
page = Page.find($1).becomes(page_class)
page.update_attributes(params[:page])
page.published_at ||= Time.now
else
page = page_class.new(params[:page])
page.published_at = page.updated_at = page.created_at = Time.now
page.parent = Page.find($1) if request.referer =~ %r{/admin/pages/(\d+)/children/new}
end
page.pagination_parameters = pagination_parameters
process_with_exception(page)
end
end
- 1
def process_with_exception(page)
page.process(request, response)
@performed_render = true
render template: 'site/show_page', layout: false
raise PreviewStop
end
- 1
def count_deleted_pages
- 1
@count = model.children.count + 1
end
- 1
def initialize_meta_rows_and_buttons
- 4
@buttons_partials ||= []
- 4
@meta ||= []
- 4
@meta << {:field => "slug", :type => "text_field", :args => [{:class => 'textbox', :maxlength => 100}]}
- 4
@meta << {:field => "breadcrumb", :type => "text_field", :args => [{:class => 'textbox', :maxlength => 160}]}
end
- 1
def verify_page_class(page_class)
if page_class.constantize.ancestors.include?(Page)
page_class.constantize
else
raise "I'm not allowed to constantize #{page_class}!"
end
end
end
- 1
class Admin::PreferencesController < ApplicationController
- 1
before_action :initialize_variables
- 1
def show
- 1
set_standard_body_style
- 1
render :edit
end
- 1
def edit
render
end
- 1
def update
- 1
if @user.update_attributes(preferences_params)
- 1
redirect_to admin_configuration_path
else
flash[:error] = t('preferences_controller.error_updating')
render :edit
end
end
- 1
private
- 1
def initialize_variables
- 2
@user = current_user
- 2
@controller_name = 'user'
- 2
@template_name = 'preferences'
end
- 1
def preferences_params
- 1
params.require(:user).permit(:name, :email, :login, :password, :password_confirmation, :locale)
end
end
- 1
require 'trusty_cms/resource_responses'
- 1
class Admin::ResourceController < ApplicationController
- 1
extend TrustyCms::ResourceResponses
- 1
helper_method :model, :current_object, :models, :current_objects, :model_symbol, :plural_model_symbol, :model_class, :model_name, :plural_model_name
- 1
before_action :populate_format
- 1
before_action :never_cache
- 1
before_action :load_models, :only => :index
- 1
before_action :load_model, :only => [:new, :create, :edit, :update, :remove, :destroy]
- 1
after_action :clear_model_cache, :only => [:create, :update, :destroy]
- 1
cattr_reader :paginated
- 1
cattr_accessor :default_per_page, :will_paginate_options
- 1
create_responses do |r|
# Equivalent respond_to block for :plural responses:
# respond_to do |wants|
# wants.xml { render :xml => models }
# wants.json { render :json => models }
# wants.any
# end
- 1
r.plural.publish(:xml, :json) { render format_symbol => models }
- 1
r.singular.publish(:xml, :json) { render format_symbol => model }
- 6
r.singular.default { redirect_to edit_model_path if action_name == "show" }
- 1
r.not_found.publish(:xml, :json) { head :not_found }
- 1
r.not_found.default { announce_not_found; redirect_to :action => "index" }
- 1
r.invalid.publish(:xml, :json) { render format_symbol => model.errors, :status => :unprocessable_entity }
- 1
r.invalid.default { announce_validation_errors; render :action => template_name }
- 1
r.stale.publish(:xml, :json) { head :conflict }
- 1
r.stale.default { announce_update_conflict; render :action => template_name }
- 1
r.create.publish(:xml, :json) { render format_symbol => model, :status => :created, :location => url_for(:format => format_symbol, :id => model) }
- 3
r.create.default { redirect_to continue_url(params) }
- 1
r.update.publish(:xml, :json) { head :ok }
- 1
r.update.default { redirect_to continue_url(params) }
- 1
r.destroy.publish(:xml, :json) { head :deleted }
- 3
r.destroy.default { redirect_to continue_url(params) }
end
- 1
def index
- 8
response_for :plural
end
- 1
[:show, :new, :edit, :remove].each do |action|
- 4
class_eval %{
def #{action} # def show
response_for :singular # response_for :singular
end # end
}, __FILE__, __LINE__
- 1
end
- 1
[:create, :update].each do |action|
- 2
class_eval %{
def #{action} # def create
model.update_attributes!(permitted_params[model_symbol]) # model.update_attributes!(params[model_symbol])
response_for :#{action} # response_for :create
end # end
}, __FILE__, __LINE__
- 1
end
- 1
def destroy
- 2
model.destroy
- 2
response_for :destroy
end
- 1
def self.model_class(model_class = nil)
- 35
@model_class ||= (model_class || self.controller_name).to_s.singularize.camelize.constantize
end
# call paginate_models to declare that will_paginate should be used in the index view
# options specified here are accessible in the view by calling will_paginate_options
# eg.
#
# Class MyController < Admin::ResourceController
# paginate_models :per_page => 100
- 1
def self.paginate_models(options={})
- 2
@@paginated = true
- 2
@@will_paginate_options = options.slice(:class, :previous_label, :next_label, :inner_window, :outer_window, :separator, :container).merge(:param_name => :p)
- 2
@@default_per_page = options[:per_page]
end
# returns a hash of options that can be passed to will_paginate
# the @pagination_for@ helper method calls @will_paginate_options@ unless other options are supplied.
#
# pagination_for(@events)
- 1
def will_paginate_options
- 8
self.class.will_paginate_options || {}
end
- 1
helper_method :will_paginate_options
# a convenience method that returns true if paginate_models has been called on this controller class
# and can be used to make display decisions in controller and view
- 1
def paginated?
- 34
self.class.paginated == true && params[:pp] != 'all'
end
- 1
helper_method :paginated?
# return a hash of page and per_page that can be used to build a will_paginate collection
# the per_page figure can be set in several ways:
# request parameter > declared by paginate_models > default set in config entry @admin.pagination.per_page@ > overall default of 50
- 1
def pagination_parameters
- 32
pp = params[:pp] || TrustyCms.config['admin.pagination.per_page']
- 32
pp = (self.class.default_per_page || 50) if pp.blank?
{
- 32
:page => (params[:p] || 1).to_i,
:per_page => pp.to_i
- 32
}
end
- 1
protected
- 1
def rescue_action(exception)
case exception
when ActiveRecord::RecordInvalid
response_for :invalid
when ActiveRecord::StaleObjectError
response_for :stale
when ActiveRecord::RecordNotFound
response_for :not_found
else
super
end
end
- 1
def model_class
- 35
self.class.model_class
end
- 1
def model
- 17
instance_variable_get("@#{model_symbol}") || load_model
end
- 1
alias :current_object :model
- 1
def model=(object)
- 13
instance_variable_set("@#{model_symbol}", object)
end
- 1
def load_model
- 11
self.model = if params[:id]
- 6
model_class.find(params[:id])
else
- 5
model_class.new()
end
end
- 1
def models
instance_variable_get("@#{plural_model_symbol}") || load_models
end
- 1
alias :current_objects :models
- 1
def models=(objects)
- 30
instance_variable_set("@#{plural_model_symbol}", objects)
end
- 1
def load_models
- 30
self.models = paginated? ? model_class.paginate(pagination_parameters) : model_class.all
end
- 1
def model_name
- 62
model_class.name
end
- 1
def plural_model_name
model_name.pluralize
end
- 1
alias :models_name :plural_model_name
- 1
def model_symbol
- 32
model_name.underscore.intern
end
- 1
def plural_model_symbol
- 30
model_name.pluralize.underscore.intern
end
- 1
alias :models_symbol :plural_model_symbol
- 1
def humanized_model_name
t(model_name.underscore.downcase)
end
- 1
def continue_url(options)
- 4
options[:redirect_to] || (params[:continue] ? {:action => 'edit', :id => model.id} : index_page_for_model)
end
- 1
def index_page_for_model
- 4
parts = {:action => "index"}
- 4
if paginated? && model && i = model_class.all.index(model)
- 2
p = (i / pagination_parameters[:per_page].to_i) + 1
- 2
parts[:p] = p if p && p > 1
end
- 4
parts
end
- 1
def edit_model_path
method = "edit_admin_#{model_name.underscore}_path"
send method.to_sym, params[:id]
end
- 1
def announce_validation_errors
flash.now[:error] = t("resource_controller.validation_errors")
end
- 1
def announce_removed
ActiveSupport::Deprecation.warn("announce_removed is no longer encouraged in TrustyCms 0.9.x.", caller)
flash[:notice] = t("resource_controller.removed", :humanized_model_name => humanized_model_name)
end
- 1
def announce_not_found
flash[:notice] = t("resource_controller.not_found", :humanized_model_name => humanized_model_name)
end
- 1
def announce_update_conflict
flash.now[:error] = t("resource_controller.update_conflict", :humanized_model_name => humanized_model_name)
end
- 1
def clear_model_cache
- 4
Rails.cache.clear
end
- 1
def format_symbol
format.to_sym
end
- 1
def format
params[:format] || 'html'
end
# I would like to set this to expires_in(1.minute, :private => true) to allow for more fluid navigation
# but the annoyance for concurrent authors would be too great.
- 1
def never_cache
- 41
expires_now
end
# Assist with user agents that cause improper content-negotiation
# warn "Remove default HTML format, Accept header no longer used. (#{__FILE__}: #{__LINE__})" if Rails.version !~ /^2\.1/
- 1
def populate_format
- 41
params[:format] ||= 'html' unless request.xhr?
end
- 1
def permitted_params
- 18
model_symbols = ActiveRecord::Base.descendants.map{|a| a.name.underscore.to_sym}
- 14
keys = params.keys.map{|k| k.underscore.to_sym}
- 2
valid_symbols = model_symbols & keys
- 2
valid_symbols.each do |symbol|
- 2
params[symbol].permit!
end
- 2
params
end
end
- 1
class Admin::UsersController < Admin::ResourceController
- 1
paginate_models
- 1
only_allow_access_to :index, :show, :new, :create, :edit, :update, :remove, :destroy,
:when => :admin,
:denied_url => { :controller => 'pages', :action => 'index' },
:denied_message => 'You must have administrative privileges to perform this action.'
- 1
before_action :ensure_deletable, :only => [:remove, :destroy]
- 1
def show
redirect_to edit_admin_user_path(params[:id])
end
- 1
def update
user_params = params[model_symbol]
if user_params && user_params['admin'] == false && model == current_user
user_params.delete('admin')
annouce_cannot_remove_self_from_admin_role
end
model.update_attributes!(user_params)
response_for :update
end
- 1
def ensure_deletable
if current_user.id.to_s == params[:id].to_s
announce_cannot_delete_self
redirect_to admin_users_path
end
end
- 1
private
- 1
def announce_cannot_delete_self
flash[:error] = t('users_controller.cannot_delete_self')
end
- 1
def annouce_cannot_remove_self_from_admin_role
flash[:error] = 'You cannot remove yourself from the admin role.'
end
end
- 1
class Admin::WelcomeController < ApplicationController
- 1
no_login_required
- 1
before_action :never_cache
- 1
skip_before_action :verify_authenticity_token
- 1
def index
- 21
redirect_to admin_pages_path
end
- 1
def login
- 43
if request.post?
- 20
@username_or_email = params[:username_or_email]
- 20
password = params[:password]
- 20
announce_invalid_user unless self.current_user = User.authenticate(@username_or_email, password)
end
- 43
if current_user
- 18
if params[:remember_me]
current_user.remember_me
set_session_cookie
end
- 18
redirect_to(session[:return_to] || welcome_path)
- 18
session[:return_to] = nil
end
end
- 1
def logout
- 1
request.cookies[:session_token] = { :expires => 1.day.ago.utc }
- 1
self.current_user.forget_me if self.current_user
- 1
self.current_user = nil
- 1
announce_logged_out
- 1
redirect_to login_path
end
- 1
private
- 1
def never_cache
- 65
expires_now
end
- 1
def announce_logged_out
- 1
flash[:notice] = t('welcome_controller.logged_out')
end
- 1
def announce_invalid_user
- 2
flash.now[:error] = t('welcome_controller.invalid_user')
end
end
#require_dependency 'trusty_cms'
- 1
require 'login_system'
- 1
class ApplicationController < ActionController::Base
- 1
include LoginSystem
# TODO: Add an ActionView::PathSet.new([paths]) for all extension view paths
- 1
prepend_view_path("#{TRUSTY_CMS_ROOT}/app/views")
- 1
protect_from_forgery
- 1
before_action :set_current_user
- 1
before_action :set_timezone
- 1
before_action :set_user_locale
- 1
before_action :set_javascripts_and_stylesheets
- 1
before_action :force_utf8_params if RUBY_VERSION =~ /1\.9/
- 1
before_action :set_standard_body_style, :only => [:new, :edit, :update, :create]
- 1
before_action :set_mailer
- 1
attr_accessor :trusty_config, :cache
- 1
attr_reader :pagination_parameters
- 1
helper_method :pagination_parameters
- 1
def initialize
- 330
super
- 330
@trusty_config = TrustyCms::Config
end
- 1
def template_name
- 52
case self.action_name
when 'index'
- 31
'index'
when 'new','create'
- 5
'new'
when 'show'
- 6
'show'
when 'edit', 'update'
- 5
'edit'
when 'remove', 'destroy'
- 4
'remove'
else
- 1
self.action_name
end
end
- 1
private
- 1
def set_mailer
- 136
ActionMailer::Base.default_url_options[:host] = request.host_with_port
end
- 1
def set_current_user
- 136
UserActionObserver.instance.current_user = current_user
end
- 1
def set_user_locale
- 136
I18n.locale = current_user && !current_user.locale.blank? ? current_user.locale : TrustyCms::Config['default_locale']
end
- 1
def set_timezone
- 138
Time.zone = TrustyCms::Config['local.timezone'] != nil && TrustyCms::Config['local.timezone'].empty? ? Time.zone_default : TrustyCms::Config['local.timezone']
end
- 1
def set_javascripts_and_stylesheets
- 137
@stylesheets ||= []
- 137
@stylesheets.concat %w(admin/main)
- 137
@javascripts ||= []
end
- 1
def set_standard_body_style
- 11
@body_classes ||= []
- 11
@body_classes.concat(%w(reversed))
end
# When using TrustyCms with Ruby 1.9, the strings that come in from forms are ASCII-8BIT encoded.
# That causes problems, especially when using special chars and with certain DBs, like DB2
# That's why we force the encoding of the params to UTF-8
# That's what's happening in Rails 3, too: https://github.com/rails/rails/commit/25215d7285db10e2c04d903f251b791342e4dd6a
#
# See http://stackoverflow.com/questions/8268778/rails-2-3-9-encoding-of-query-parameters
# See https://rails.lighthouseapp.com/projects/8994/tickets/4807
# See http://jasoncodes.com/posts/ruby19-rails2-encodings (thanks for the following code, Jason!)
- 1
def force_utf8_params
traverse = lambda do |object, block|
if object.kind_of?(Hash)
object.each_value { |o| traverse.call(o, block) }
elsif object.kind_of?(Array)
object.each { |o| traverse.call(o, block) }
else
block.call(object)
end
object
end
force_encoding = lambda do |o|
o.force_encoding(Encoding::UTF_8) if o.respond_to?(:force_encoding)
end
traverse.call(params, force_encoding)
end
end
- 1
require 'trusty_cms/pagination/controller'
- 1
class SiteController < ApplicationController
- 1
include TrustyCms::Pagination::Controller
- 1
skip_before_action :verify_authenticity_token
- 1
no_login_required
- 1
def self.cache_timeout=(val)
TrustyCms::PageResponseCacheDirector.cache_timeout=(val)
end
- 1
def self.cache_timeout
TrustyCms::PageResponseCacheDirector.cache_timeout
end
- 1
def show_page
- 21
url = params[:url]
- 21
if Array === url
url = url.join('/')
else
- 21
url = url.to_s
end
- 21
if @page = find_page(url)
batch_page_status_refresh if (url == "/" || url == "")
# This is a bit of a hack to get Vanity URL pages working in another extension
# In Rails 2, redirect_to halted execution, so process_page could be aliased and
# a redirect could be used. This no longer works. There's a better fix for this,
# but for now, anything that aliases process_page can return false if it's rendering
# or redirecting on its own.
return unless process_page(@page)
set_cache_control
@performed_render ||= true
render layout: false
else
render :template => 'site/not_found', :status => 404, layout: false
end
rescue Page::MissingRootPageError
- 21
redirect_to welcome_path
end
- 1
def cacheable_request?
(request.head? || request.get?) && live?
end
# hide_action :cacheable_request?
- 1
def set_expiry(time, options={})
expires_in time, options
end
# hide_action :set_expiry
- 1
def set_etag(val)
headers['ETag'] = val
end
# hide_action :set_expiry
- 1
private
- 1
def batch_page_status_refresh
@changed_pages = []
@pages = Page.where({:status_id => Status[:scheduled].id})
@pages.each do |page|
if page.published_at <= Time.now
page.status_id = Status[:published].id
page.save
@changed_pages << page.id
end
end
expires_in nil, :private=>true, "no-cache" => true if @changed_pages.length > 0
end
- 1
def set_cache_control
response_cache_director(@page).set_cache_control
end
- 1
def response_cache_director(page)
klass_name = "TrustyCms::#{page.class}ResponseCacheDirector"
begin
klass = klass_name.constantize
rescue NameError, LoadError
director_klass = "TrustyCms::PageResponseCacheDirector"
#Rubocop: The use of eval is a serious security risk.
#eval(%Q{class #{klass_name} < #{director_klass}; end}, TOPLEVEL_BINDING)
klass = director_klass.constantize
end
klass.new(page, self)
end
- 1
def find_page(url)
- 21
found = Page.find_by_path(url, live?)
found if found and (found.published? or dev?)
end
- 1
def process_page(page)
page.pagination_parameters = pagination_parameters
page.process(request, response)
end
- 1
def dev?
- 21
request.host == @trusty_config['dev.host'] || request.host =~ /^dev\./
end
- 1
def live?
- 21
not dev?
end
end
- 1
module Admin::ConfigurationHelper
# Defines helper methods for use in the admin interface when displaying or editing configuration.
# Renders the setting as label and value:
#
# show_config("admin.title")
# => <label for="admin_title">Admin title<label><span id="admin_title">TrustyCms CMS</span>
#
- 1
def show_config(key, options={})
- 50
setting = setting_for(key)
- 50
setting.valid?
- 50
domkey = key.gsub(/\W/, '_')
- 50
html = ""
- 50
html << content_tag(:label, t("trusty_config.#{key}").titlecase, :for => domkey)
- 50
if setting.boolean?
- 5
value = setting.checked? ? t('yes') : t('no')
- 5
html << content_tag(:span, value, :id => domkey, :class => "#{value} #{options[:class]}")
else
- 45
value = setting.selected_value || setting.value
- 45
html << content_tag(:span, value, :id => domkey, :class => options[:class])
end
- 50
html << content_tag(:span, " #{t("units.#{setting.units}")}", :class => 'units') if setting.units
- 50
html << content_tag(:span, " #{t('warning')}: #{[setting.errors[:value]].flatten.first}", :class => 'warning') if setting.errors.messages[:value].present?
- 50
Rails.logger.error(html)
- 50
html.html_safe
end
# Renders the setting as label and appropriate input field:
#
# edit_setting("admin.title")
# => <label for="admin_title">Admin title<label><input type="text" name="config['admin.title']" id="admin_title" value="TrustyCms CMS" />
#
# edit_config("defaults.page.status")
# =>
# <label for="defaults_page_status">Default page status<label>
# <select type="text" name="config['defaults.page.status']" id="defaults_page_status">
# <option value="Draft">Draft</option>
# ...
# </select>
#
# edit_setting("user.allow_password_reset?")
# => <label for="user_allow_password_reset_">Admin title<label><input type="checkbox" name="config['user.allow_password_reset?']" id="user_allow_password_reset_" value="1" checked="checked" />
#
- 1
def edit_config(key, options={})
- 10
setting = setting_for(key)
- 10
domkey = key.gsub(/\W/, '_')
- 10
name = "trusty_config[#{key}]"
- 10
title = t("trusty_config.#{key}").titlecase
- 10
title << content_tag(:span, " (#{t("units.#{setting.units}")})", :class => 'units') if setting.units
- 10
value = params[key.to_sym].nil? ? setting.value : params[key.to_sym]
- 10
html = ""
- 10
if setting.boolean?
- 1
html << hidden_field_tag(name, 0)
- 1
html << check_box_tag(name, 1, value, :class => 'setting', :id => domkey)
- 1
html << content_tag(:label, title.html_safe, :class => 'checkbox', :for => domkey)
- 9
elsif setting.selector?
- 4
html << content_tag(:label, title.html_safe, :for => domkey)
- 4
html << select_tag(name, options_for_select(setting.definition.selection, value), :class => 'setting', :id => domkey)
else
- 5
html << content_tag(:label, title.html_safe, :for => domkey)
- 5
html << text_field_tag(name, value, :class => 'textbox', :id => domkey)
end
- 10
if setting.errors[:value].present?
html << content_tag(:span, [setting.errors[:value]].flatten.first, :class => 'error')
html = content_tag(:span, html.html_safe, :class => "error-with-field")
end
- 10
html.html_safe
end
- 1
def setting_for(key)
- 60
@trusty_config ||= {} # normally initialized in Admin::ConfigurationController
- 60
@trusty_config[key] ||= TrustyCms.config.find_or_initialize_by(key: key)
end
- 1
def definition_for(key)
if setting = setting_for(key)
setting.definition
end
end
end
- 1
module Admin::ExtensionsHelper
end
- 1
module Admin::LayoutsHelper
end
- 1
module Admin::NodeHelper
- 1
def render_nodes(page, starting_index, parent_index = nil, simple = false)
- 4
@rendered_html = ""
- 4
render_node page, starting_index, parent_index, simple
- 4
@rendered_html
end
- 1
def render_node(page, index, parent_index = nil, simple = false)
- 4
@current_node = prepare_page(page)
- 4
@rendered_html += (render :partial => 'admin/pages/node',
:locals => {level: index, index: index, parent_index: parent_index,
- 4
page: page, simple: simple, branch: (page.children.count > 0) })
- 4
index
end
- 1
def prepare_page(page)
- 4
page.extend MenuRenderer
- 4
page.view = self
- 4
if page.additional_menu_features?
page.extend(*page.menu_renderer_modules)
end
- 4
page
end
- 1
def homepage
@homepage ||= Page.find_by_parent_id(nil)
end
- 1
def show_all?
controller.action_name == 'remove'
end
- 1
def expanded_rows
unless @expanded_rows
@expanded_rows = case
when rows = cookies[:expanded_rows]
rows.split(',').map { |x| Integer(x) rescue nil }.compact
else
[]
end
if homepage and !@expanded_rows.include?(homepage.id)
@expanded_rows << homepage.id
end
end
@expanded_rows
end
- 1
def expanded
show_all? || expanded_rows.include?(@current_node.id)
end
- 1
def expander(level)
unless @current_node.children.empty? or level == 0
image((expanded ? "collapse" : "expand"),
:class => "expander", :alt => 'toggle children',
:title => '')
else
""
end
end
- 1
def icon
- 4
icon_name = @current_node.virtual? ? 'virtual_page' : 'page'
- 4
image(icon_name, :class => "icon", :alt => '', :title => '')
end
- 1
def node_title
- 4
%{<span class="title">#{ h(@current_node.title) }</span>}.html_safe
end
- 1
def page_type
- 3
display_name = @current_node.class.display_name
- 3
if display_name == 'Page'
- 3
""
else
%{<span class="info">(#{ h(display_name) })</span>}.html_safe
end
end
- 1
def spinner
- 3
image('spinner.gif',
:class => 'busy', :id => "busy_#{@current_node.id}",
:alt => "", :title => "",
:style => 'display: none;')
end
end
- 1
module Admin::PagesHelper
- 1
include Admin::NodeHelper
- 1
include Admin::ReferencesHelper
- 1
def class_of_page
@page.class
end
- 1
def filter
@page.parts.first.filter if @page.parts.respond_to?(:any?) && @page.parts.any?
end
- 1
def meta_errors?
- 6
!!(@page.errors[:slug] or @page.errors[:breadcrumb])
end
- 1
def status_to_display
- 3
@page.status_id = 100 if @page.status_id == 90
- 15
@display_status = Status.selectable.map{ |s| [I18n.translate(s.name.downcase), s.id] }
end
- 1
def clean_page_description(page)
page.description.to_s.strip.gsub(/\t/,'').gsub(/\s+/,' ')
end
end
- 1
module Admin::PreferencesHelper
end
- 1
require "RedCloth"
- 1
module Admin::ReferencesHelper
- 1
def tag_reference
String.new.tap do |output|
class_of_page.tag_descriptions.sort.each do |tag_name, description|
value = t("desc.#{tag_name.gsub(':','-')}").match('desc') ? description : t("desc.#{tag_name.gsub(':','-')}")
output << render(:partial => "admin/references/tag_reference.haml",
:locals => {:tag_name => tag_name,
:description => RedCloth.new(TrustyCms::Taggable::Util.strip_leading_whitespace(value)).to_html
})
end
end
end
- 1
def filter_reference
unless filter.blank?
if filter.description.blank?
"There is no documentation on this filter."
else
filter.description
end
else
"There is no filter on the current page part."
end
end
- 1
def _display_name
case params[:type]
when 'filters'
filter ? filter.filter_name : t('select.none')
when 'tags'
class_of_page.display_name
end
end
- 1
def filter
@filter ||= begin
TextFilter.find_descendant(params[:filter_name])
end
end
- 1
def class_of_page
@page_class ||= (params[:class_name].blank? ? 'Page' : params[:class_name]).constantize
end
end
- 1
module Admin::RegionsHelper
- 1
def render_region(region, options={}, &block)
- 244
lazy_initialize_region_set
- 244
default_partials = TrustyCms::AdminUI::RegionPartials.new(self)
- 244
if block_given?
- 123
block.call(default_partials)
- 123
(options[:locals] ||= {}).merge!(:defaults => default_partials)
end
- 244
output = @region_set[region].compact.map do |partial|
- 194
begin
- 194
render options.merge(:partial => partial)
rescue ::ActionView::MissingTemplate # couldn't find template
- 194
default_partials[partial]
rescue ::ActionView::TemplateError => e # error in template
raise e
end
end.join.html_safe
- 244
Rails.logger.error(output)
- 244
block_given? ? concat(output) : output
end
- 1
def lazy_initialize_region_set
- 244
unless @region_set
- 44
@controller_name ||= @_controller.controller_name
- 44
@template_name ||= @_controller.template_name
- 44
@region_set = admin.send(@controller_name).send(@template_name)
end
end
end
- 1
module Admin::ResourceHelper
end
- 1
module Admin::UsersHelper
- 1
def roles(user)
roles = []
roles << I18n.t('admin') if user.admin?
roles << I18n.t('designer') if user.designer?
roles.join(', ')
end
end
- 1
module Admin::WelcomeHelper
end
- 1
module ApplicationHelper
- 1
include Admin::RegionsHelper
- 1
def trusty_config
- 138
TrustyCms::Config
end
- 1
def default_page_title
- 69
title + ' - ' + subtitle
end
- 1
def title
- 69
trusty_config['admin.title'] || 'Trusty CMS'
end
- 1
def subtitle
- 69
trusty_config['admin.subtitle'] || 'Publishing for Small Teams'
end
- 1
def logged_in?
- 69
!current_user.nil?
end
- 1
def onsubmit_status(model)
- 2
model.new_record? ? t('creating_status', :model => t(model.class.name.downcase)) : "#{I18n.t('saving_changes')}…"
end
- 1
def save_model_button(model, options = {})
- 6
model_name = model.class.name.underscore
- 6
human_model_name = model_name.humanize.titlecase
- 6
options[:label] ||= model.new_record? ?
t('buttons.create', :name => t(model_name, :default => human_model_name), :default => 'Create ' + human_model_name) :
t('buttons.save_changes', :default => 'Save Changes')
- 6
options[:class] ||= "button"
- 6
options[:accesskey] ||= 'S'
- 6
submit_tag options.delete(:label), options
end
- 1
def save_model_and_continue_editing_button(model)
- 5
submit_tag t('buttons.save_and_continue'), :name => 'continue', :class => 'button', :accesskey => "s"
end
- 1
def current_item?(item)
- 140
if item.tab && item.tab.many? {|i| current_url?(i.relative_url) }
# Accept only stricter URL matches if more than one matches
current_page?(item.url)
else
- 28
current_url?(item.relative_url)
end
end
- 1
def current_tab?(tab)
- 372
@current_tab ||= tab if tab.any? {|item| current_url?(item.relative_url) }
- 130
@current_tab == tab
end
- 1
def current_url?(options)
- 382
url = case options
when Hash
url_for options
else
- 382
options.to_s
end
#TODO: look for other instances of request_uri
- 382
request.original_fullpath =~ Regexp.new('^' + Regexp.quote(clean(url)))
end
- 1
def clean(url)
- 382
uri = URI.parse(url)
- 382
uri.path.gsub(%r{/+}, '/').gsub(%r{/$}, '')
end
- 1
def admin?
- 5
current_user and current_user.admin?
end
- 1
def designer?
current_user and (current_user.designer? or current_user.admin?)
end
- 1
def updated_stamp(model)
- 5
unless model.new_record?
- 2
updated_by = (model.updated_by || model.created_by)
- 2
name = updated_by ? updated_by.name : nil
- 2
time = (model.updated_at || model.created_at)
- 2
if name or time
- 2
html = %{<p class="updated_line">#{t('timestamp.last_updated')} }
- 2
html << %{#{t('timestamp.by')} <strong>#{name}</strong> } if name
- 2
html << %{#{t('timestamp.at')} #{timestamp(time)}} if time
- 2
html << %{</p>}
- 2
html.html_safe
end
end
end
- 1
def timestamp(time)
# time.strftime("%I:%M %p on %B %e, %Y").sub("AM", 'am').sub("PM", 'pm')
- 2
I18n.localize(time, :format => :timestamp)
end
- 1
def meta_errors?
- 4
false
end
- 1
def meta_label
- 5
meta_errors? ? 'Less' : 'More'
end
- 1
def image(name, options = {})
- 67
image_tag(append_image_extension("admin/#{name}"), options)
end
- 1
def admin
- 112
TrustyCms::AdminUI.instance
end
- 1
def body_classes
- 101
@body_classes ||= []
end
- 1
def nav_tabs
- 44
admin.nav
end
- 1
def translate_with_default(name)
- 158
t(name.underscore.downcase, :default => name)
end
- 1
def available_locales_select
- 1
[[t('select.default'),'']] + TrustyCms::AvailableLocales.locales
end
- 1
def stylesheet_overrides
- 69
overrides = []
- 69
if File.exist?("#{Rails.root}/public/stylesheets/admin/overrides.css") || File.exist?("#{Rails.root}/public/stylesheets/sass/admin/overrides.sass")
overrides << 'admin/overrides'
end
- 69
overrides
end
- 1
def javascript_overrides
- 69
overrides = []
- 69
if File.exist?("#{Rails.root}/public/javascripts/admin/overrides.js")
overrides << 'admin/overrides'
end
- 69
overrides
end
# Returns a Gravatar URL associated with the email parameter.
# See: http://douglasfshearer.com/blog/gravatar-for-ruby-and-ruby-on-rails
- 1
def gravatar_url(email, options={})
# Default to highest rating. Rating can be one of G, PG, R X.
- 6
options[:rating] ||= "G"
# Default size of the image.
- 6
options[:size] ||= "32px"
# Default image url to be used when no gravatar is found
# or when an image exceeds the rating parameter.
- 6
local_avatar_url = "/production/assets/admin/avatar_#{([options[:size].to_i] * 2).join('x')}.png"
- 6
default_avatar_url = "#{request.protocol}#{request.host_with_port}#{ActionController::Base.relative_url_root}#{local_avatar_url}"
- 6
options[:default] ||= default_avatar_url
- 6
unless email.blank?
# Build the Gravatar url.
url = '//gravatar.com/avatar/'
url << "#{Digest::MD5.new.update(email)}?"
url << "rating=#{options[:rating]}" if options[:rating]
url << "&size=#{options[:size]}" if options[:size]
url << "&default=#{options[:default]}" if options[:default]
# Test the Gravatar url
require 'open-uri'
begin; open "http:#{url}", :proxy => true
rescue; local_avatar_url
else; url
end
else
- 6
local_avatar_url
end
end
# returns the usual set of pagination links.
# options are passed through to will_paginate
# and a 'show all' depagination link is added if relevant.
- 1
def pagination_for(list, options={})
- 8
if list.respond_to? :total_pages
- 8
options = {
:max_per_page => @trusty_config['pagination.max_per_page'] || 500,
:depaginate => true
}.merge(options.symbolize_keys)
- 8
depaginate = options.delete(:depaginate) # supply :depaginate => false to omit the 'show all' link
- 8
depagination_limit = options.delete(:max_per_page) # supply :max_per_page => false to include the 'show all' link no matter how large the collection
- 8
html = will_paginate(list, will_paginate_options.merge(options))
- 8
if depaginate && list.total_pages > 1 && (!depagination_limit.blank? || list.total_entries <= depagination_limit.to_i)
html << content_tag(:div, link_to(t('show_all'), :pp => 'all'), :class => 'depaginate')
- 8
elsif depaginate && list.total_entries > depagination_limit.to_i
html = content_tag(:div, link_to("paginate", :p => 1), :class => 'pagination')
end
- 8
html
end
end
- 1
private
- 1
def append_image_extension(name)
- 67
unless name =~ /\.(.*?)$/
- 58
name + '.png'
else
- 9
name
end
end
end
- 1
module SiteHelper
end
- 1
class Layout < ActiveRecord::Base
# Default Order
- 26
default_scope {order("name")}
# Associations
- 1
has_many :pages
- 1
belongs_to :created_by, :class_name => 'User'
- 1
belongs_to :updated_by, :class_name => 'User'
# Validations
- 1
validates_presence_of :name
- 1
validates_uniqueness_of :name
- 1
validates_length_of :name, :maximum => 100
end
- 1
module MenuRenderer
- 1
def exclude(*type_names)
@excluded_class_names ||= []
@excluded_class_names.concat(type_names).uniq!
end
- 1
module_function :exclude
- 1
def excluded_class_names
- 9
MenuRenderer.instance_variable_get(:@excluded_class_names)
end
- 1
module_function :excluded_class_names
- 1
public :excluded_class_names
- 1
def view=(val)
- 4
@view = val
end
- 1
def view
- 39
@view
end
- 1
def additional_menu_features?
- 4
@additional_menu_features ||= (menu_renderer_module_name != 'MenuRenderer' && Object.const_defined?(menu_renderer_module_name))
end
- 1
def menu_renderer_module_name
- 4
simple_name = self.class_name.to_s.sub('Page','')
- 4
"#{simple_name}MenuRenderer"
end
- 1
def menu_renderer_modules
[Object.const_get(menu_renderer_module_name)]
end
- 1
def allowed_child_classes
- 9
(allowed_children_cache.to_s.split(',') - Array(excluded_class_names)).map do |name|
- 18
begin
- 18
name.constantize
rescue LoadError, NameError => _
nil
end
- 9
end.compact
end
- 1
def default_child_item
- 3
menu_item(default_child)
end
- 1
def separator_item
- 3
view.content_tag :li, '', :class => 'separator'
end
- 1
def child_items
- 3
(allowed_child_classes - [self.class.default_child]).map do |child|
- 3
menu_item(child)
end
end
- 1
def menu_items
- 3
[default_child_item, separator_item] + child_items
end
- 1
def menu_list
- 3
view.content_tag :ul, menu_items.join.html_safe, :class => 'menu', :id => "allowed_children_#{id}"
end
- 1
def remove_link
- 3
view.link_to view.image('minus') + ' ' + I18n.t('remove'), view.remove_admin_page_url(self), :class => "action"
end
- 1
def remove_option
- 3
remove_link
end
- 1
def add_child_disabled?
- 3
allowed_child_classes.size == 0
end
- 1
def disabled_add_child_link
view.content_tag :span, view.image('plus_disabled') + ' Add Child', :class => 'action disabled'
end
- 1
def add_child_link
view.link_to((view.image('plus') + ' Add Child'), view.new_admin_page_child_path(self, :page_class => default_child.name), :class => "action")
end
- 1
def add_child_link_with_menu_hook
- 3
view.link_to((view.image('plus') + ' Add Child'), "#allowed_children_#{id}", :class => "action dropdown")
end
- 1
def add_child_menu
- 3
menu_list
end
- 1
def add_child_link_with_menu
- 3
add_child_link_with_menu_hook + add_child_menu
end
- 1
def add_child_option
- 3
if add_child_disabled?
disabled_add_child_link
else
- 3
if allowed_child_classes.size == 1
add_child_link
else
- 3
add_child_link_with_menu
end
end
end
- 1
private
- 1
def clean_page_description(page_class)
- 6
page_class.description.to_s.strip.gsub(/\t/,'').gsub(/\s+/,' ')
end
- 1
def menu_item(child_class)
- 6
view.content_tag(:li, menu_link(child_class))
end
- 1
def menu_link(child_class)
- 6
title = clean_page_description(child_class)
- 6
path = view.new_admin_page_child_path(self, :page_class => child_class.name)
- 6
text = link_text_for_child_class(child_class.name)
- 6
view.link_to(text, path, :title => title)
end
- 1
def link_text_for_child_class(given_class_name)
- 6
translation_key = if given_class_name == 'Page' || given_class_name.blank?
- 3
'normal_page'
else
- 3
given_class_name.sub('Page','').underscore
end
- 6
fallback = given_class_name == 'Page' ? 'Page' : given_class_name.sub('Page','').titleize
- 6
I18n.t(translation_key, :default => fallback)
end
end
- 1
class PageField < ActiveRecord::Base
- 1
validates_presence_of :name
end
- 1
class PagePart < ActiveRecord::Base
# Default Order
- 19
default_scope {order("name")}
# Associations
- 1
belongs_to :page
# Validations
- 1
validates_presence_of :name
- 1
validates_length_of :name, :maximum => 100
- 1
validates_length_of :filter_id, :maximum => 25, :allow_nil => true
- 1
object_id_attr :filter, TextFilter
- 1
def after_initialize
self.filter_id ||= TrustyCms::Config['defaults.page.filter'] if new_record?
end
end
- 1
class Status
- 1
attr_accessor :id, :name
- 1
def initialize(options = {})
- 5
options = options.symbolize_keys
- 5
@id, @name = options[:id], options[:name]
end
- 1
def symbol
- 61
@name.to_s.downcase.intern
end
- 1
def self.[](value)
- 80
@@statuses.find { |status| status.symbol == value.to_s.downcase.intern }
end
- 1
def self.find(id)
- 24
@@statuses.find { |status| status.id.to_s == id.to_s }
end
- 1
def self.find_all
- 9
@@statuses.dup
end
- 1
def self.selectable
- 9
find_all - [self['Scheduled']]
end
- 1
def self.selectable_values
- 6
self.selectable.map(&:name)
end
- 1
@@statuses = [
Status.new(:id => 1, :name => 'Draft' ),
Status.new(:id => 50, :name => 'Reviewed' ),
Status.new(:id => 90, :name => 'Scheduled'),
Status.new(:id => 100, :name => 'Published'),
Status.new(:id => 101, :name => 'Hidden' )
]
end
- 1
class TextFilter
- 1
include Simpleton
- 1
include Annotatable
- 1
annotate :filter_name, :description
- 1
def filter(text)
text
end
- 1
class << self
- 1
def inherited(subclass)
subclass.filter_name = subclass.name.to_name('Filter')
end
- 1
def filter(text)
instance.filter(text)
end
- 1
def descendants_names
descendants.map { |s| s.filter_name }.sort
end
- 1
def find_descendant(filter_name)
descendants.each do |s|
return s if s.filter_name == filter_name
end
nil
end
end
end
- 1
require 'digest/sha1'
- 1
class User < ActiveRecord::Base
- 1
has_many :pages, :foreign_key => :created_by_id
# Default Order
- 26
default_scope {order("name")}
# Associations
- 1
belongs_to :created_by, :class_name => 'User'
- 1
belongs_to :updated_by, :class_name => 'User'
# Validations
- 1
validates_uniqueness_of :login
- 1
validates_confirmation_of :password, :if => :confirm_password?
- 1
validates_presence_of :name, :login
- 1
validates_presence_of :password, :password_confirmation, :if => :new_record?
- 1
validates_length_of :name, :maximum => 100, :allow_nil => true
- 1
validates_length_of :login, :within => 3..40, :allow_nil => true
- 1
validates_length_of :password, :within => 5..40, :allow_nil => true, :if => :validate_length_of_password?
- 1
validates_length_of :email, :maximum => 255, :allow_nil => true
- 1
attr_writer :confirm_password
- 1
def has_role?(role)
- 130
respond_to?("#{role}?") && send("#{role}?")
end
- 1
def sha1(phrase)
- 19
Digest::SHA1.hexdigest("--#{salt}--#{phrase}--")
end
- 1
def self.authenticate(login_or_email, password)
- 20
user = where(["login = ? OR email = ?", login_or_email, login_or_email]).first
- 20
user if user && user.authenticated?(password)
end
- 1
def authenticated?(password)
- 19
self.password == sha1(password)
end
- 1
def after_initialize
@confirm_password = true
end
- 1
def confirm_password?
- 3
@confirm_password
end
- 1
def remember_me
update_attribute(:session_token, sha1(Time.now + TrustyCms::Config['session_timeout'].to_i)) unless self.session_token?
end
- 1
def forget_me
- 1
update_attribute(:session_token, nil)
end
- 1
def send_password_reset
generate_token(:password_reset_token)
update_attribute(:password_reset_sent_at, Time.zone.now)
PasswordMailer.password_reset(self).deliver_now
end
- 1
private
- 1
def generate_token(column)
self[column] = SecureRandom.urlsafe_base64 if User.exists?(column => self[column])
end
- 1
def validate_length_of_password?
- 3
new_record? or not password.to_s.empty?
end
- 1
before_create :encrypt_password
- 1
def encrypt_password
self.salt = Digest::SHA1.hexdigest("--#{Time.now}--#{login}--sweet harmonious biscuits--")
self.password = sha1(password)
end
- 1
before_update :encrypt_password_unless_empty_or_unchanged
- 1
def encrypt_password_unless_empty_or_unchanged
- 1
user = self.class.find(self.id)
- 1
case password
when ''
- 1
self.password = user.password
when user.password
else
encrypt_password
end
end
end
- 1
class UserActionObserver < ActiveRecord::Observer
- 1
observe User, Page, Layout
- 1
def current_user=(user)
- 136
self.class.current_user = user
end
- 1
def self.current_user=(user)
- 136
Thread.current[:current_user] = user
end
- 1
def current_user
- 8
self.class.current_user
end
- 1
def self.current_user
- 8
Thread.current[:current_user]
end
- 1
def before_create(model)
- 7
model.created_by = self.current_user
end
- 1
def before_update(model)
- 1
model.updated_by = self.current_user
end
end
- 1
module LoginSystem
- 1
def self.included(base)
- 1
base.extend ClassMethods
- 1
base.class_eval do
- 1
prepend_before_action :authenticate
- 1
prepend_before_action :authorize
- 1
helper_method :current_user
end
end
- 1
protected
- 1
def current_user
- 872
@current_user ||= (login_from_session || login_from_cookie || login_from_http)
end
- 1
def current_user=(value=nil)
- 21
if value && value.is_a?(User)
- 18
@current_user = value
- 18
session['user_id'] = value.id
else
- 3
@current_user = nil
- 3
session['user_id'] = nil
end
- 21
@current_user
end
- 1
def authenticate
#puts _process_action_callbacks.map(&:filter)
- 72
if current_user
- 50
session['user_id'] = current_user.id
- 50
true
else
- 22
session[:return_to] = request.original_url
- 22
respond_to do |format|
- 44
format.html { redirect_to login_url }
- 22
format.any(:xml,:json) { request_http_basic_authentication }
end
- 22
false
end
end
- 1
def authorize
#puts _process_action_callbacks.map(&:filter)
- 72
action = action_name.to_s.intern
- 72
if user_has_access_to_action?(action)
- 72
true
else
permissions = self.class.controller_permissions[action]
flash[:error] = permissions[:denied_message] || 'Access denied.'
respond_to do |format|
format.html { redirect_to(permissions[:denied_url] || { :action => :index }) }
format.any(:xml, :json) { head :forbidden }
end
false
end
end
- 1
def user_has_access_to_action?(action)
- 72
self.class.user_has_access_to_action?(current_user, action, self)
end
- 1
def login_from_session
- 579
User.unscoped.find(session['user_id']) rescue nil
end
- 1
def login_from_cookie
- 264
if !cookies[:session_token].blank? && user = User.find_by_session_token(cookies[:session_token]) # don't find by empty value
user.remember_me
set_session_cookie(user)
user
end
end
- 1
def login_from_http
- 264
if [Mime[:xml], Mime[:json]].include?(request.format)
authenticate_with_http_basic do |user_name, password|
User.authenticate(user_name, password)
end
end
end
- 1
def set_session_cookie(user = current_user)
cookies[:session_token] = { :value => user.session_token , :expires => (Time.now + ((TrustyCms::Config['session_timeout'].to_i)/86400).days).utc }
end
- 1
module ClassMethods
- 1
def no_login_required
- 2
skip_before_action :authenticate
- 2
skip_before_action :authorize
# puts _process_action_callbacks.map(&:filter)
end
- 1
def login_required?
filter_chain.any? {|f| f.method == :authenticate || f.method == :authorize }
end
- 1
def login_required
unless login_required?
prepend_before_action :authenticate, :authorize
end
end
- 1
def only_allow_access_to(*args)
- 4
options = {}
- 4
options = args.pop.dup if args.last.kind_of?(Hash)
- 4
options.symbolize_keys!
- 23
actions = args.map { |a| a.to_s.intern }
- 4
actions.each do |action|
- 19
controller_permissions[action] = options
end
end
- 1
def controller_permissions
- 260
@controller_permissions ||= Hash.new { |h,k| h[k.to_s.intern] = Hash.new }
end
- 1
def user_has_access_to_action?(user, action, instance=new)
- 232
permissions = controller_permissions[action.to_s.intern]
case
when allowed_roles = permissions[:when]
- 73
allowed_roles = [allowed_roles].flatten
- 203
user.present? ? allowed_roles.any? { |role| user.has_role?(role) } : false
when condition_method = permissions[:if]
instance.send(condition_method)
else
- 159
true
- 232
end
end
end
end
- 1
class TrustyCms::AdminUI::RegionPartials
- 1
def initialize(template)
- 244
@partials = Hash.new {|h,k| h[k] = "<strong>`#{k}' default partial not found!</strong>" }
- 244
@template = template
end
- 1
def [](key)
- 194
@partials[key.to_s]
end
- 1
def method_missing(method, *args, &block)
- 195
if block_given?
# Ruby 1.9.2 yields self in instance_eval... see https://gist.github.com/479572
# lambdas are as strict as methods in 1.9.x, making sure that the args match, Procs are not.
- 195
if RUBY_VERSION =~ /^1\.9/ and block.lambda? and block.arity != 1
raise "You can only pass a proc ('Proc.new') or a lambda that takes exactly one arg (for self) to TrustyCms::AdminUI::RegionPartials' method_missing."
end
- 195
@partials[method.to_s] = @template.capture(&block)
else
@partials[method.to_s]
end
end
end
- 1
module TrustyCms::AvailableLocales
# Returns the list of available locale files in options_for_select format.
#
- 1
def self.locales
- 7
available_locales = {}
- 7
TrustyCms.configuration.i18n.load_path.each do |path|
- 196
if File.exists?(path) && path !~ /_available_tags/
- 182
locale_yaml = YAML.load_file(path)
- 182
stem = File.basename(path, '.yml')
- 182
if locale_yaml[stem] && lang = locale_yaml[stem]["this_file_language"]
- 14
available_locales[lang] = stem
end
end
end
- 21
available_locales.collect {|k,v| [k, v]}.sort_by { |s| s[0] }
end
end
- 1
module TrustyCms
- 1
module Pagination
- 1
module Controller
# for inclusion into public-facing controllers
- 1
def configure_pagination
# unconfigured parameters remain at will_paginate defaults
# will_paginate controller options are not overridden by tag attribetus
- 21
WillPaginate::ViewHelpers.pagination_options[:param_name] = TrustyCms::Config["pagination.param_name"].to_sym unless TrustyCms::Config["pagination.param_name"].blank?
- 21
WillPaginate::ViewHelpers.pagination_options[:per_page_param_name] = TrustyCms::Config["pagination.per_page_param_name"].blank? ? :per_page : TrustyCms::Config["pagination.per_page_param_name"].to_sym
# will_paginate view options can be overridden by tag attributes
- 21
[:class, :previous_label, :next_label, :inner_window, :outer_window, :separator, :container].each do |opt|
- 147
WillPaginate::ViewHelpers.pagination_options[opt] = TrustyCms::Config["pagination.#{opt}"] unless TrustyCms::Config["pagination.#{opt}"].blank?
end
end
- 1
def pagination_parameters
{
:page => params[WillPaginate::ViewHelpers.pagination_options[:param_name]] || 1,
:per_page => params[WillPaginate::ViewHelpers.pagination_options[:per_page_param_name]] || TrustyCms::Config['pagination.per_page'] || 20
}
end
- 1
def self.included(base)
- 1
base.class_eval {
- 1
helper_method :pagination_parameters
- 1
before_action :configure_pagination
}
end
end
end
end
- 1
require 'ostruct'
- 1
module TrustyCms
- 1
module ResourceResponses
- 1
def self.extended(base)
- 1
base.send :class_attribute, :responses
- 1
base.send :include, InstanceMethods
end
- 1
def create_responses
- 2
r = (self.responses ||= Collector.new)
- 2
yield r if block_given?
- 2
r
end
- 1
module InstanceMethods
- 1
def response_for(action)
- 41
responses = self.class.responses.send(action)
- 41
respond_to do |wants|
- 41
responses.each_format do |f, format_block|
- 30
if format_block
- 30
wants.send(f, &wrap(format_block))
else
wants.send(f)
end
end
- 41
responses.each_published do |pub, pub_block|
- 78
wants.send(pub, &wrap(pub_block))
end
- 41
if responses.default
- 9
wants.any(&wrap(responses.default))
else
- 32
wants.any
end
end
end
- 1
def wrap(proc)
# Makes sure our response blocks get evaluated in the right context
- 117
lambda do
# Ruby 1.9.2 yields self in instance_eval... see https://gist.github.com/479572
# lambdas are as strict as methods in 1.9.x, making sure that the args match, Procs are not.
- 9
if RUBY_VERSION =~ /^1\.9/ and proc.lambda? and proc.arity != 1
raise "You can only pass a proc ('Proc.new') or a lambda that takes exactly one arg (for self) to the wrap method."
end
- 9
instance_eval(&proc)
end
end
end
- 1
class Collector < OpenStruct
- 1
def initialize
- 1
super
- 10
@table = Hash.new {|h,k| h[k] = Response.new }
end
- 1
def initialize_copy(orig)
super
@table.keys.each do |key|
@table[key] = orig.send(key).dup
end
end
end
- 1
class Response
- 1
attr_reader :publish_formats, :publish_block, :blocks, :block_order
- 1
def initialize
- 9
@publish_formats = []
- 9
@blocks = {}
- 9
@block_order = []
end
- 1
def initialize_copy(orig)
@publish_formats = orig.publish_formats.dup
@blocks = orig.blocks.dup
@block_order = orig.block_order.dup
@publish_block = orig.publish_block.dup if orig.publish_block
@default = orig.default.dup if orig.default
end
- 1
def default(&block)
- 57
if block_given?
- 7
@default = block
end
- 57
@default
end
- 1
def publish(*formats, &block)
- 8
@publish_formats.concat(formats)
- 8
if block_given?
- 8
@publish_block = block
else
raise ArgumentError, "Block required to publish" unless @publish_block
end
end
- 1
def each_published
- 41
publish_formats.each do |format|
- 78
yield format, publish_block if block_given?
end
end
- 1
def each_format
- 41
@block_order.each do |format|
- 30
yield format, @blocks[format] if block_given?
end
end
- 1
def method_missing(method, *args, &block)
- 1
if block_given?
- 1
@blocks[method] = block
- 1
@block_order << method unless @block_order.include?(method)
elsif args.empty?
@block_order << method
else
super
end
end
end
end
end
- 1
require 'spec_helper'
- 1
describe ApplicationController, :type => :controller do
- 13
routes { TrustyCms::Engine.routes }
- 1
it 'should initialize the javascript and stylesheets arrays' do
- 1
controller.send :set_javascripts_and_stylesheets
- 1
expect(controller.send(:instance_variable_get, :@javascripts)).not_to be_nil
- 1
expect(controller.send(:instance_variable_get, :@javascripts)).to be_instance_of(Array)
- 1
expect(controller.send(:instance_variable_get, :@stylesheets)).not_to be_nil
- 1
expect(controller.send(:instance_variable_get, :@stylesheets)).to be_instance_of(Array)
end
- 1
describe 'self.template_name' do
- 1
it "should return 'index' when the controller action_name is 'index'" do
- 1
allow(controller).to receive(:action_name).and_return('index')
- 1
expect(controller.template_name).to eq('index')
end
- 1
['new', 'create'].each do |action|
- 2
it "should return 'new' when the action_name is #{action}" do
- 2
allow(controller).to receive(:action_name).and_return(action)
- 2
expect(controller.template_name).to eq('new')
end
end
- 1
['edit', 'update'].each do |action|
- 2
it "should return 'edit' when the action_name is #{action}" do
- 2
allow(controller).to receive(:action_name).and_return(action)
- 2
expect(controller.template_name).to eq('edit')
end
end
- 1
['remove', 'destroy'].each do |action|
- 2
it "should return 'remove' when the action_name is #{action}" do
- 2
allow(controller).to receive(:action_name).and_return(action)
- 2
expect(controller.template_name).to eq('remove')
end
end
- 1
it "should return 'show' when the action_name is show" do
- 1
allow(controller).to receive(:action_name).and_return('show')
- 1
expect(controller.template_name).to eq('show')
end
- 1
it "should return the action_name when the action_name is a non-standard name" do
- 1
allow(controller).to receive(:action_name).and_return('other')
- 1
expect(controller.template_name).to eq('other')
end
end
- 1
describe "set_timezone" do
- 1
it "should use TrustyCms::Config['local.timezone']" do
- 1
TrustyCms::Config['local.timezone'] = 'UTC'
- 1
controller.send(:set_timezone)
- 1
expect(Time.zone.name).to eq('UTC')
end
- 1
it "should default to config.time_zone" do
- 1
TrustyCms::Config.initialize_cache # to clear out setting from previous tests
- 1
controller.send(:set_timezone)
- 1
expect(Time.zone.name).to eq('UTC')
end
end
end
- 1
require 'spec_helper'
- 1
describe Admin::UsersController, :type => :controller do
- 1
routes { TrustyCms::Engine.routes }
end
- 1
require 'spec_helper'
- 1
RSpec.describe Admin::WelcomeController, :type => :controller do
- 1
routes { TrustyCms::Engine.routes }
end
- 1
FactoryGirl.define do
- 1
factory :layout do
- 1
name 'Main Layout'
- 1
content <<-CONTENT
<html>
<head>
<title><r:title /></title>
</head>
<body>
<r:content />
</body>
</html>
CONTENT
end
end
- 1
FactoryGirl.define do
- 1
factory :page do
- 1
title 'Page'
- 1
breadcrumb { title }
- 1
slug { title.slugify }
- 1
trait :with_parts do
- 1
page_parts { [FactoryGirl.create(:page_part, name: 'body')] }
end
- 1
trait :with_children do
- 1
children { [FactoryGirl.create(:page, :with_parts)] }
end
- 1
factory :page_with_layout do
- 1
layout
end
- 1
factory :page_with_page_parts do
- 1
page_parts
end
- 1
factory :file_not_found_page, class: FileNotFoundPage do
end
- 1
factory :parent do
end
- 1
factory :published_page do
- 1
status_id Status[:published].id
- 1
factory :article do
- 1
title { generate(:article_title)}
- 1
slug { generate(:article_slug)}
end
- 1
factory :page_with_body_page_part do
- 1
after(:create) { |page| page.parts.create(name: 'body', content: "#{page.title} body.") }
end
- 1
factory :page_with_body_and_sidebar_parts do
- 1
after(:create) { |page| page.parts.create(name: 'body', content: "#{page.title} body.") }
- 1
after(:create) { |page| page.parts.create(name: 'sidebar', content: "#{page.title} sidebar.") }
end
end
- 1
factory :home do |home|
- 1
title 'Home'
- 1
slug '/'
- 1
status_id Status[:published].id
- 1
parent_id nil
end
end
- 1
sequence :article_slug do |n|
"article#{('-' + n.to_s) unless n == 1 }"
end
- 1
sequence :article_title do |n|
"Article#{(' ' + n.to_s) unless n == 1 }"
end
end
- 1
FactoryGirl.define do
- 1
factory :page_part do
- 1
name 'unnamed'
- 1
content { name }
end
end
- 1
FactoryGirl.define do
- 1
factory :user do
- 1
name 'User'
- 1
email 'email@test.com'
- 1
login 'user'
- 1
password 'password'
- 1
password_confirmation { password }
- 1
factory :admin do
- 1
name 'Admin'
- 1
login 'admin'
- 1
email 'admin@example.com'
- 1
admin true
end
- 1
factory :existing do
- 1
name 'Existing'
- 1
login 'existing'
- 1
email 'existing@example.com'
end
- 1
factory :designer do
- 1
name 'Designer'
- 1
login 'designer'
- 1
email ''
- 1
designer true
end
- 1
factory :non_admin do
- 1
name 'Non Admin'
- 1
login 'non_admin'
- 1
admin false
end
end
end
- 1
require 'rails_helper'
- 1
describe 'Administration Interface Login' do
- 1
fixtures :users
- 1
it 'shows a login page' do
- 1
visit '/'
- 1
expect(page).to have_field 'Username or E-mail Address'
- 1
expect(page).to have_field 'Password'
- 1
expect(page).to have_button 'Login'
end
- 1
it 'shows an error if the username is wrong' do
- 1
log_in_as 'nonexistent_username'
- 1
expect(find('#error')).to have_content "Invalid username, e-mail address, or password."
end
- 1
describe 'as an admin user' do
- 1
before(:each) do
- 7
@admin = users(:captain_janeway)
end
- 1
context 'after login' do
- 1
before(:each) do
- 6
log_in_as @admin.login
end
- 1
it 'shows the admin interface' do
- 1
expect(page).to have_content "Logged in as"
end
- 1
it 'has correct links in header' do
- 1
expect(page).to have_link @admin.name, href: '/admin/preferences/edit'
- 1
expect(page).to have_link 'Logout', href: '/admin/logout'
- 1
expect(page).to have_link 'View Site', href: '/'
end
- 1
it 'has correct links in navigation' do
- 1
within '#navigation' do
- 1
expect(page).to have_link "Content", href: '/admin/pages'
- 1
expect(page).to have_link "Design", href: '/admin/layouts'
- 1
expect(page).to have_link "Settings", href: '/admin/configuration'
end
end
- 1
it 'outputs table header as html' do
- 1
expect(page).to have_selector "table#pages th.name"
end
- 1
it 'can navigate to create new page' do
- 1
visit '/admin/pages/new'
- 1
expect(page).to have_selector "h1", text: "New Page"
end
- 1
it 'can log out' do
- 1
click_link "Logout"
- 1
expect(page).to have_content "You are now logged out."
- 1
visit '/admin/pages/new'
- 1
expect(page).to have_content "Please Login"
end
end
- 1
it 'shows an error if the password is wrong' do
- 1
log_in_as @admin.login, 'passwordwhoops'
- 1
expect(find('#error')).to have_content "Invalid username, e-mail address, or password."
end
end
- 1
describe 'as a regular user after login' do
- 1
before(:each) do
- 2
@user = users(:neelix)
- 2
log_in_as @user.login
end
- 1
it 'can log in to the admin interface' do
- 1
expect(page).to have_content "Logged in as"
end
- 1
it 'has correct links in navigation' do
- 1
within '#navigation' do
- 1
expect(page).to have_link "Content", href: '/admin/pages'
- 1
expect(page).not_to have_link "Design"
- 1
expect(page).to have_link "Settings", href: '/admin/configuration'
end
end
end
end
- 1
require 'rails_helper'
- 1
describe 'Configuration (Settings)' do
- 1
fixtures :users
- 1
before(:each) do
- 3
@admin = users(:captain_janeway)
- 3
log_in_as @admin.login
- 3
click_link 'Settings'
end
- 1
it 'has personal and site preferences' do
- 1
expect(page).to have_content 'Personal Preferences'
- 1
expect(page).to have_content 'Configuration'
end
- 1
it 'lets you edit your personal preferences' do
- 1
click_button 'Edit Preferences'
- 1
fill_in 'Name', with: 'Captain Kathryn Janeway'
- 1
click_button 'Save Changes'
- 1
expect(page).to have_content 'Name Captain Kathryn Janeway'
end
- 1
it 'lets you edit the site preferences' do
- 1
click_button 'Edit Configuration'
- 1
fill_in 'Site Title', with: 'My Special Site'
- 1
click_button 'Save Changes'
- 1
within '#site_title' do
- 1
expect(page).to have_content 'My Special Site'
end
end
end
- 1
require 'rails_helper'
- 1
describe 'Layouts (Design)' do
- 1
fixtures :users
- 1
before(:each) do
- 4
@admin = users(:captain_janeway)
- 4
log_in_as @admin.login
- 4
click_link 'Design'
end
- 1
context 'without any layouts' do
- 1
it 'says it has no layouts' do
- 1
expect(page).to have_content 'No Layouts'
end
- 1
it 'lets you add a layout' do
- 1
click_link 'New Layout'
- 1
fill_in 'Name', with: 'Petunias'
- 1
fill_in 'Body', with: 'Wisteria'
- 1
click_button 'Create Layout'
- 1
expect(page).to have_content 'Petunias'
end
end
- 1
context 'with a layout' do
- 1
before(:each) do
- 2
Layout.create!(name: 'Petunias', content: 'Wisteria')
- 2
visit '/admin/layouts'
end
- 1
it 'lets you edit the layout' do
- 1
click_link 'Petunias'
- 1
expect(page).to have_content 'Edit Layout'
- 1
expect(page).to have_field 'Name', with: 'Petunias'
- 1
expect(page).to have_field 'Body', with: 'Wisteria'
- 1
expect(page).to have_button 'Save Changes'
- 1
expect(page).to have_content 'Last Updated by Kathryn Janeway'
end
- 1
it 'lets you remove the layout' do
- 1
click_link 'Remove'
- 1
expect(page).to have_content 'Are you sure you want to permanently remove the following layout?'
- 1
click_button 'Delete Layout'
- 1
expect(page).to have_content 'No Layouts'
- 1
expect(page).to have_link 'New Layout'
end
end
end
- 1
require 'rails_helper'
- 1
describe 'Pages' do
- 1
fixtures :users
- 1
before(:each) do
- 3
@admin = users(:captain_janeway)
- 3
log_in_as @admin.login
end
- 1
context 'without any pages' do
- 1
it 'can create a new homepage' do
- 1
click_link 'New Homepage'
- 1
fill_in 'Page Title', with: 'Voyager Home'
- 1
fill_in 'Breadcrumb', with: 'Home'
- 1
click_button 'Create Page'
- 1
within 'table#pages' do
- 1
expect(page).to have_selector 'tbody tr', count: 1
- 1
expect(page).to have_link 'Voyager Home'
- 1
expect(page).to have_link 'Add Child'
- 1
expect(page).to have_link 'Normal Page'
- 1
expect(page).to have_link 'File Not Found'
- 1
expect(page).to have_link 'Remove'
end
end
end
- 1
context 'with only a homepage' do
- 1
before(:each) do
- 2
Page.create!(title: 'Voyager Home', breadcrumb: 'Home', slug: '/')
- 2
visit '/admin/pages'
end
- 1
it 'lets you edit the homepage' do
- 1
click_link 'Voyager Home'
- 1
expect(page).to have_field 'Page Title', with: 'Voyager Home'
- 1
expect(page).to have_button 'Save Changes'
- 1
expect(page).to have_content 'Last Updated by Kathryn Janeway'
end
- 1
it 'lets you remove the homepage' do
- 1
click_link 'Remove'
- 1
expect(page).to have_content 'Are you sure you want to permanently remove the following Page?'
- 1
click_button 'Delete Page'
- 1
expect(page).to have_content 'No Pages'
- 1
expect(page).to have_link 'New Homepage'
end
end
end
- 1
require 'spec_helper'
- 1
describe Layout do
- 1
let(:layout){ FactoryGirl.build(:layout) }
- 1
describe 'name' do
- 1
it 'is invalid when blank' do
- 1
layout = FactoryGirl.build(:layout, name: '')
- 1
layout.valid?
- 1
expect(layout.errors[:name]).to include("this must not be blank")
end
- 1
it 'should validate uniqueness of' do
- 1
layout = FactoryGirl.build(:layout, name: 'Normal', content: "Content!")
- 1
layout.save!
- 1
other = FactoryGirl.build(:layout, name: 'Normal', content: "Content!")
- 2
expect{other.save!}.to raise_error(ActiveRecord::RecordInvalid)
end
- 1
it 'should validate length of' do
- 1
layout = FactoryGirl.build(:layout, name: 'x' * 100)
- 1
expect(layout.errors[:name]).to be_blank
- 1
layout = FactoryGirl.build(:layout, name: 'x' * 101)
- 2
expect{layout.save!}.to raise_error(ActiveRecord::RecordInvalid)
- 1
expect(layout.errors[:name]).to include("this must not be longer than 100 characters")
end
end
end
# This file is copied to spec/ when you run 'rails generate rspec:install'
- 1
ENV["RAILS_ENV"] ||= 'test'
- 1
require 'spec_helper'
- 1
require 'rspec/rails'
- 1
require 'capybara/rails'
- 1
require 'capybara/poltergeist'
- 1
Capybara.javascript_driver = :poltergeist
- 1
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, timeout: 60)
end
- 1
require 'database_cleaner'
- 1
DatabaseCleaner.strategy = :truncation, {except: %w[config]}
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
- 1
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
- 1
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
- 1
config.fixture_path = "#{::TRUSTY_CMS_ROOT}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
- 1
config.use_transactional_fixtures = false
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
- 1
config.infer_spec_type_from_file_location!
- 1
config.before(:suite) do
- 1
TrustyCms::Config.initialize_cache
- 1
configs = [
['admin.title', 'TrustyCMS'],
['admin.subtitle', 'Publishing for Small Teams'],
['defaults.page.parts', 'body, extended'],
['defaults.page.status', 'Draft'],
['defaults.page.filter', nil],
['defaults.page.fields', 'Keywords, Description'],
['defaults.snippet.filter', nil],
['session_timeout', '1209600'], # 2.weeks.to_s ????
['default_locale', 'en'],
]
- 1
configs.each do |key, value|
- 9
c = TrustyCms::Config.find_or_initialize_by(key: key)
- 9
c.value = value
- 9
c.save
end
end
- 1
config.after(:each) do
- 39
DatabaseCleaner.clean
end
end
- 1
require "rails_helper"
- 1
RSpec.describe "routes for Welcome", :type => :routing do
- 1
it "routes /admin/welcome to the admin/welcome controller" do
- 1
expect(get("/admin/welcome")).
to route_to("admin/welcome#index")
end
- 1
it "routes /admin/login to the admin/welcome controller" do
- 1
expect(get("/admin/login")).
to route_to("admin/welcome#login")
end
- 1
it "routes /admin/logout to the admin/welcome controller" do
- 1
expect(get("/admin/logout")).
to route_to("admin/welcome#logout")
end
end
# Commonly occurring user actions in tests.
# This takes a username and by default assumes the password is 'password'.
- 1
def log_in_as(login, plaintext_password = 'password')
- 20
visit '/'
- 20
fill_in 'username_or_email', with: login
- 20
fill_in 'password', with: plaintext_password
- 20
click_on 'Login'
end