chore: rubocop

chore: fix api test conventions

chore: rubocop -A spec/

chore: more rubocop -A

fix failing test

rubocop fixes

removes helper methods that are in my opinion dead code

more rubocop fixes

rubocop -a --auto-gen-config
This commit is contained in:
Philipp Rothmann 2023-05-12 13:01:12 +02:00 committed by Philipp Rothmann
parent f6fb804bbe
commit fb2b4d8a8a
331 changed files with 4263 additions and 4507 deletions

View file

@ -1,6 +1,6 @@
class CurrentOrders::ArticlesController < ApplicationController
before_action :authenticate_orders
before_action :find_order_and_order_article, only: [:index, :show]
before_action :find_order_and_order_article, only: %i[index show]
def index
# sometimes need to pass id as parameter for forms
@ -26,11 +26,11 @@ class CurrentOrders::ArticlesController < ApplicationController
def find_order_and_order_article
@current_orders = Order.finished_not_closed
unless params[:order_id].blank?
if params[:order_id].blank?
@order_articles = OrderArticle.where(order_id: @current_orders.all.map(&:id))
else
@order = Order.find(params[:order_id])
@order_articles = @order.order_articles
else
@order_articles = OrderArticle.where(order_id: @current_orders.all.map(&:id))
end
@q = OrderArticle.ransack(params[:q])
@order_articles = @order_articles.ordered.merge(@q.result).includes(:article, :article_price)

View file

@ -4,10 +4,10 @@ class CurrentOrders::GroupOrdersController < ApplicationController
def index
# XXX code duplication lib/foodsoft_current_orders/app/controllers/current_orders/ordergroups_controller.rb
@order_ids = Order.where(state: ['open', 'finished']).all.map(&:id)
@goas = GroupOrderArticle.includes(:group_order => :ordergroup).includes(:order_article)
@order_ids = Order.where(state: %w[open finished]).all.map(&:id)
@goas = GroupOrderArticle.includes(group_order: :ordergroup).includes(:order_article)
.where(group_orders: { order_id: @order_ids, ordergroup_id: @ordergroup.id }).ordered
@articles_grouped_by_category = @goas.includes(:order_article => { :article => :article_category })
@articles_grouped_by_category = @goas.includes(order_article: { article: :article_category })
.order('articles.name')
.group_by { |a| a.order_article.article.article_category.name }
.sort { |a, b| a[0] <=> b[0] }
@ -18,8 +18,8 @@ class CurrentOrders::GroupOrdersController < ApplicationController
# XXX code duplication from GroupOrdersController
def ensure_ordergroup_member
@ordergroup = @current_user.ordergroup
if @ordergroup.nil?
redirect_to root_url, :alert => I18n.t('group_orders.errors.no_member')
end
return unless @ordergroup.nil?
redirect_to root_url, alert: I18n.t('group_orders.errors.no_member')
end
end

View file

@ -1,6 +1,6 @@
class CurrentOrders::OrdergroupsController < ApplicationController
before_action :authenticate_orders
before_action :find_group_orders, only: [:index, :show]
before_action :find_group_orders, only: %i[index show]
def index
# sometimes need to pass id as parameter for forms
@ -34,8 +34,11 @@ class CurrentOrders::OrdergroupsController < ApplicationController
@all_ordergroups.sort_by! { |o| @ordered_group_ids.include?(o.id) ? o.name : "ZZZZZ#{o.name}" }
@ordergroup = Ordergroup.find(params[:id]) unless params[:id].nil?
@goas = GroupOrderArticle.includes(:group_order, :order_article => [:article, :article_price])
.where(group_orders: { order_id: @order_ids, ordergroup_id: @ordergroup.id }).ordered.all unless @ordergroup.nil?
return if @ordergroup.nil?
@goas = GroupOrderArticle.includes(:group_order, order_article: %i[article article_price])
.where(group_orders: { order_id: @order_ids,
ordergroup_id: @ordergroup.id }).ordered.all
end
helper_method \

View file

@ -77,11 +77,11 @@ class MultipleOrdersByArticles < OrderPdf
.includes(:article).references(:article)
.reorder('order_articles.order_id, articles.name')
.preload(:article_price) # preload not join, just in case it went missing
.preload(:order, :group_order_articles => { :group_order => :ordergroup })
.preload(:order, group_order_articles: { group_order: :ordergroup })
end
def each_order_article
order_articles.find_each_with_order(batch_size: BATCH_SIZE) { |oa| yield oa }
def each_order_article(&block)
order_articles.find_each_with_order(batch_size: BATCH_SIZE, &block)
end
def group_order_articles_for(order_article)
@ -90,7 +90,7 @@ class MultipleOrdersByArticles < OrderPdf
goas
end
def each_group_order_article_for(group_order)
group_order_articles_for(group_order).each { |goa| yield goa }
def each_group_order_article_for(group_order, &block)
group_order_articles_for(group_order).each(&block)
end
end

View file

@ -113,7 +113,7 @@ class MultipleOrdersByGroups < OrderPdf
s
end
def each_ordergroup
def each_ordergroup(&block)
ordergroups.find_in_batches_with_order(batch_size: BATCH_SIZE) do |ordergroups|
@group_order_article_batch = GroupOrderArticle
.joins(:group_order)
@ -121,8 +121,8 @@ class MultipleOrdersByGroups < OrderPdf
.where(group_orders: { ordergroup_id: ordergroups.map(&:id) })
.order('group_orders.order_id, group_order_articles.id')
.preload(group_orders: { order: :supplier })
.preload(order_article: [:article, :article_price, :order])
ordergroups.each { |ordergroup| yield ordergroup }
.preload(order_article: %i[article article_price order])
ordergroups.each(&block)
end
end
@ -130,7 +130,7 @@ class MultipleOrdersByGroups < OrderPdf
@group_order_article_batch.select { |goa| goa.group_order.ordergroup_id == ordergroup.id }
end
def each_group_order_article_for(ordergroup)
group_order_articles_for(ordergroup).each { |goa| yield goa }
def each_group_order_article_for(ordergroup, &block)
group_order_articles_for(ordergroup).each(&block)
end
end

View file

@ -6,7 +6,9 @@ module CurrentOrdersHelper
elsif funds == 0
I18n.t('helpers.current_orders.pay_none')
else
content_tag :b, I18n.t('helpers.current_orders.pay_amount', amount: number_to_currency(-ordergroup.get_available_funds))
content_tag :b,
I18n.t('helpers.current_orders.pay_amount',
amount: number_to_currency(-ordergroup.get_available_funds))
end
end
end

View file

@ -1,27 +1,27 @@
Rails.application.routes.draw do
scope '/:foodcoop' do
namespace :current_orders do
resources :ordergroups, :only => [:index, :show] do
resources :ordergroups, only: %i[index show] do
collection do
get :show_on_group_order_article_create
get :show_on_group_order_article_update
end
end
resources :articles, :only => [:index, :show] do
resources :articles, only: %i[index show] do
collection do
get :show_on_group_order_article_create
end
end
resource :orders, :only => [:show] do
resource :orders, only: [:show] do
collection do
get :my
get :receive
end
end
resources :group_orders, :only => [:index]
resources :group_orders, only: [:index]
end
end
end

View file

@ -1,20 +1,21 @@
$:.push File.expand_path("../lib", __FILE__)
$:.push File.expand_path('lib', __dir__)
# Maintain your gem's version:
require "foodsoft_current_orders/version"
require 'foodsoft_current_orders/version'
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "foodsoft_current_orders"
s.name = 'foodsoft_current_orders'
s.version = FoodsoftCurrentOrders::VERSION
s.authors = ["wvengen"]
s.email = ["dev-voko@willem.engen.nl"]
s.homepage = "https://github.com/foodcoop-adam/foodsoft"
s.summary = "Quick support for working on all currently active orders in foodsoft."
s.description = ""
s.authors = ['wvengen']
s.email = ['dev-voko@willem.engen.nl']
s.homepage = 'https://github.com/foodcoop-adam/foodsoft'
s.summary = 'Quick support for working on all currently active orders in foodsoft.'
s.description = ''
s.files = Dir["{app,config,db,lib}/**/*"] + ["Rakefile", "README.md"]
s.files = Dir['{app,config,db,lib}/**/*'] + ['Rakefile', 'README.md']
s.add_dependency "rails"
s.add_dependency "deface", "~> 1.0"
s.add_dependency 'rails'
s.add_dependency 'deface', '~> 1.0'
s.metadata['rubygems_mfa_required'] = 'true'
end

View file

@ -1,5 +1,5 @@
require "deface"
require "foodsoft_current_orders/engine"
require 'deface'
require 'foodsoft_current_orders/engine'
module FoodsoftCurrentOrders
def self.enabled?

View file

@ -4,12 +4,15 @@ module FoodsoftCurrentOrders
return unless FoodsoftCurrentOrders.enabled?
return if primary[:orders].nil?
cond = Proc.new { current_user.role_orders? }
cond = proc { current_user.role_orders? }
[
SimpleNavigation::Item.new(primary, :stage_divider, nil, nil, class: 'divider', if: cond),
SimpleNavigation::Item.new(primary, :current_orders_receive, I18n.t('current_orders.navigation.receive'), context.receive_current_orders_orders_path, if: cond),
SimpleNavigation::Item.new(primary, :current_orders_articles, I18n.t('current_orders.navigation.articles'), context.current_orders_articles_path, if: cond),
SimpleNavigation::Item.new(primary, :current_orders_ordergroups, I18n.t('current_orders.navigation.ordergroups'), context.current_orders_ordergroups_path, if: cond)
SimpleNavigation::Item.new(primary, :current_orders_receive, I18n.t('current_orders.navigation.receive'),
context.receive_current_orders_orders_path, if: cond),
SimpleNavigation::Item.new(primary, :current_orders_articles, I18n.t('current_orders.navigation.articles'),
context.current_orders_articles_path, if: cond),
SimpleNavigation::Item.new(primary, :current_orders_ordergroups,
I18n.t('current_orders.navigation.ordergroups'), context.current_orders_ordergroups_path, if: cond)
].each { |i| primary[:orders].sub_navigation.items << i }
end
end

View file

@ -1,3 +1,3 @@
module FoodsoftCurrentOrders
VERSION = "0.0.1"
VERSION = '0.0.1'
end

View file

@ -20,7 +20,7 @@ RDoc::Task.new(:rdoc) do |rdoc|
rdoc.rdoc_files.include('lib/**/*.rb')
end
APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__)
APP_RAKEFILE = File.expand_path('test/dummy/Rakefile', __dir__)
load 'rails/tasks/engine.rake'
Bundler::GemHelper.install_tasks
@ -34,4 +34,4 @@ Rake::TestTask.new(:test) do |t|
t.verbose = false
end
task :default => :test
task default: :test

View file

@ -11,7 +11,7 @@ class DiscourseController < ApplicationController
def redirect_to_with_payload(url, payload)
base64_payload = Base64.strict_encode64 payload.to_query
sso = CGI::escape base64_payload
sso = CGI.escape base64_payload
sig = get_hmac_hex_string base64_payload
redirect_to "#{url}#{url.include?('?') ? '&' : '?'}sso=#{sso}&sig=#{sig}"
end
@ -21,7 +21,7 @@ class DiscourseController < ApplicationController
payload.symbolize_keys!
end
def get_hmac_hex_string payload
def get_hmac_hex_string(payload)
discourse_sso_secret = FoodsoftConfig[:discourse_sso_secret]
OpenSSL::HMAC.hexdigest 'sha256', discourse_sso_secret, payload
end

View file

@ -5,7 +5,7 @@ class DiscourseLoginController < DiscourseController
def initiate
discourse_url = FoodsoftConfig[:discourse_url]
nonce = SecureRandom.hex()
nonce = SecureRandom.hex
return_sso_url = url_for(action: :callback, only_path: false)
session[:discourse_sso_nonce] = nonce
@ -36,7 +36,7 @@ class DiscourseLoginController < DiscourseController
user.save!
login_and_redirect_to_return_to user, notice: I18n.t('discourse.callback.logged_in')
rescue => error
redirect_to login_url, alert: error.to_s
rescue StandardError => e
redirect_to login_url, alert: e.to_s
end
end

View file

@ -17,7 +17,7 @@ class DiscourseSsoController < DiscourseController
external_id: "#{FoodsoftConfig.scope}/#{current_user.id}",
username: current_user.nick,
name: current_user.name
rescue => error
redirect_to root_url, alert: error.to_s
rescue StandardError => e
redirect_to root_url, alert: e.to_s
end
end

View file

@ -1,20 +1,21 @@
$:.push File.expand_path("../lib", __FILE__)
$:.push File.expand_path('lib', __dir__)
# Maintain your gem's version:
require "foodsoft_discourse/version"
require 'foodsoft_discourse/version'
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "foodsoft_discourse"
s.name = 'foodsoft_discourse'
s.version = FoodsoftDiscourse::VERSION
s.authors = ["paroga"]
s.email = ["paroga@paroga.com"]
s.homepage = "https://github.com/foodcoops/foodsoft"
s.summary = "Discourse plugin for foodsoft."
s.description = "Allow SSO login via Discourse"
s.authors = ['paroga']
s.email = ['paroga@paroga.com']
s.homepage = 'https://github.com/foodcoops/foodsoft'
s.summary = 'Discourse plugin for foodsoft.'
s.description = 'Allow SSO login via Discourse'
s.files = Dir["{app,config,db,lib}/**/*"] + ["Rakefile", "README.md"]
s.files = Dir['{app,config,db,lib}/**/*'] + ['Rakefile', 'README.md']
s.add_dependency "rails"
s.add_dependency "deface", "~> 1.0"
s.add_dependency 'rails'
s.add_dependency 'deface', '~> 1.0'
s.metadata['rubygems_mfa_required'] = 'true'
end

View file

@ -2,7 +2,7 @@ module FoodsoftDiscourse
module RedirectToLogin
def self.included(base) # :nodoc:
base.class_eval do
alias foodsoft_discourse_orig_redirect_to_login redirect_to_login
alias_method :foodsoft_discourse_orig_redirect_to_login, :redirect_to_login
def redirect_to_login(options = {})
if FoodsoftDiscourse.enabled? && !FoodsoftConfig[:discourse_sso]
@ -18,5 +18,5 @@ end
# modify existing helper
ActiveSupport.on_load(:after_initialize) do
Concerns::Auth.send :include, FoodsoftDiscourse::RedirectToLogin
Concerns::Auth.include FoodsoftDiscourse::RedirectToLogin
end

View file

@ -1,3 +1,3 @@
module FoodsoftDiscourse
VERSION = "0.0.1"
VERSION = '0.0.1'
end

View file

@ -20,7 +20,7 @@ RDoc::Task.new(:rdoc) do |rdoc|
rdoc.rdoc_files.include('lib/**/*.rb')
end
APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__)
APP_RAKEFILE = File.expand_path('test/dummy/Rakefile', __dir__)
load 'rails/tasks/engine.rake'
Bundler::GemHelper.install_tasks
@ -34,4 +34,4 @@ Rake::TestTask.new(:test) do |t|
t.verbose = false
end
task :default => :test
task default: :test

View file

@ -4,16 +4,16 @@ class DocumentsController < ApplicationController
before_action -> { require_plugin_enabled FoodsoftDocuments }
def index
if params["sort"]
sort = case params["sort"]
when "name" then "data IS NULL DESC, name"
when "created_at" then "created_at"
when "name_reverse" then "data IS NULL, name DESC"
when "created_at_reverse" then "created_at DESC"
sort = if params['sort']
case params['sort']
when 'name' then 'data IS NULL DESC, name'
when 'created_at' then 'created_at'
when 'name_reverse' then 'data IS NULL, name DESC'
when 'created_at_reverse' then 'created_at DESC'
end
else
sort = "data IS NULL DESC, name"
end
else
'data IS NULL DESC, name'
end
@documents = Document.where(parent: @document).page(params[:page]).per(@per_page).order(sort)
end
@ -34,22 +34,22 @@ class DocumentsController < ApplicationController
if @document.name.empty?
name = File.basename(data.original_filename)
@document.name = name.gsub(/[^\w\.\-]/, '_')
@document.name = name.gsub(/[^\w.-]/, '_')
end
end
@document.created_by = current_user
@document.save!
redirect_to @document.parent || documents_path, notice: t('.notice')
rescue => error
redirect_to @document.parent || documents_path, alert: t('.error', error: error.message)
rescue StandardError => e
redirect_to @document.parent || documents_path, alert: t('.error', error: e.message)
end
def update
@document = Document.find(params[:id])
@document.update_attribute(:parent_id, params[:parent_id])
redirect_to @document.parent || documents_path, notice: t('.notice')
rescue => error
redirect_to @document.parent || documents_path, alert: t('errors.general_msg', msg: error.message)
rescue StandardError => e
redirect_to @document.parent || documents_path, alert: t('errors.general_msg', msg: e.message)
end
def destroy
@ -60,8 +60,8 @@ class DocumentsController < ApplicationController
else
redirect_to documents_path, alert: t('.no_right')
end
rescue => error
redirect_to documents_path, alert: t('.error', error: error.message)
rescue StandardError => e
redirect_to documents_path, alert: t('.error', error: e.message)
end
def show

View file

@ -1,21 +1,22 @@
$:.push File.expand_path("../lib", __FILE__)
$:.push File.expand_path('lib', __dir__)
# Maintain your gem's version:
require "foodsoft_documents/version"
require 'foodsoft_documents/version'
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "foodsoft_documents"
s.name = 'foodsoft_documents'
s.version = FoodsoftDocuments::VERSION
s.authors = ["paroga"]
s.email = ["paroga@paroga.com"]
s.homepage = "https://github.com/foodcoops/foodsoft"
s.summary = "Documents plugin for foodsoft."
s.description = "Adds simple document management to foodsoft."
s.authors = ['paroga']
s.email = ['paroga@paroga.com']
s.homepage = 'https://github.com/foodcoops/foodsoft'
s.summary = 'Documents plugin for foodsoft.'
s.description = 'Adds simple document management to foodsoft.'
s.files = Dir["{app,config,db,lib}/**/*"] + ["Rakefile", "README.md"]
s.files = Dir['{app,config,db,lib}/**/*'] + ['Rakefile', 'README.md']
s.add_dependency "rails"
s.add_dependency "deface", "~> 1.0"
s.add_dependency "ruby-filemagic"
s.add_dependency 'rails'
s.add_dependency 'deface', '~> 1.0'
s.add_dependency 'ruby-filemagic'
s.metadata['rubygems_mfa_required'] = 'true'
end

View file

@ -8,9 +8,9 @@ module FoodsoftDocuments
sub_nav.items <<
SimpleNavigation::Item.new(primary, :documents, I18n.t('navigation.documents'), context.documents_path)
# move to right before tasks item
if i = sub_nav.items.index(sub_nav[:tasks])
sub_nav.items.insert(i, sub_nav.items.delete_at(-1))
end
return unless i = sub_nav.items.index(sub_nav[:tasks])
sub_nav.items.insert(i, sub_nav.items.delete_at(-1))
end
def default_foodsoft_config(cfg)

View file

@ -1,3 +1,3 @@
module FoodsoftDocuments
VERSION = "0.0.1"
VERSION = '0.0.1'
end

View file

@ -20,7 +20,7 @@ RDoc::Task.new(:rdoc) do |rdoc|
rdoc.rdoc_files.include('lib/**/*.rb')
end
APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__)
APP_RAKEFILE = File.expand_path('test/dummy/Rakefile', __dir__)
load 'rails/tasks/engine.rake'
Bundler::GemHelper.install_tasks
@ -34,4 +34,4 @@ Rake::TestTask.new(:test) do |t|
t.verbose = false
end
task :default => :test
task default: :test

View file

@ -37,8 +37,8 @@ class Admin::LinksController < Admin::BaseController
link = Link.find(params[:id])
link.destroy!
redirect_to admin_links_path
rescue => error
redirect_to admin_links_path, I18n.t('errors.general_msg', msg: error.message)
rescue StandardError => e
redirect_to admin_links_path, I18n.t('errors.general_msg', msg: e.message)
end
private

View file

@ -5,9 +5,7 @@ class LinksController < ApplicationController
link = Link.find(params[:id])
url = link.url
if link.workgroup && !current_user.role_admin? && !link.workgroup.member?(current_user)
return deny_access
end
return deny_access if link.workgroup && !current_user.role_admin? && !link.workgroup.member?(current_user)
if link.indirect
uri = URI.parse url
@ -19,11 +17,9 @@ class LinksController < ApplicationController
url = result.header['Location']
unless url
return redirect_to root_url, alert: t('.indirect_no_location')
end
return redirect_to root_url, alert: t('.indirect_no_location') unless url
end
redirect_to url, status: 302
redirect_to url, status: :found
end
end

View file

@ -1,20 +1,21 @@
$:.push File.expand_path("../lib", __FILE__)
$:.push File.expand_path('lib', __dir__)
# Maintain your gem's version:
require "foodsoft_links/version"
require 'foodsoft_links/version'
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "foodsoft_links"
s.name = 'foodsoft_links'
s.version = FoodsoftLinks::VERSION
s.authors = ["paroga"]
s.email = ["paroga@paroga.com"]
s.homepage = "https://github.com/foodcoops/foodsoft"
s.summary = "Links plugin for foodsoft."
s.description = "Adds simple link management to foodsoft."
s.authors = ['paroga']
s.email = ['paroga@paroga.com']
s.homepage = 'https://github.com/foodcoops/foodsoft'
s.summary = 'Links plugin for foodsoft.'
s.description = 'Adds simple link management to foodsoft.'
s.files = Dir["{app,config,db,lib}/**/*"] + ["Rakefile", "README.md"]
s.files = Dir['{app,config,db,lib}/**/*'] + ['Rakefile', 'README.md']
s.add_dependency "rails"
s.add_dependency "deface", "~> 1.0"
s.add_dependency 'rails'
s.add_dependency 'deface', '~> 1.0'
s.metadata['rubygems_mfa_required'] = 'true'
end

View file

@ -1,7 +1,7 @@
module FoodsoftLinks
class Engine < ::Rails::Engine
def navigation(primary, context)
primary.item :links, I18n.t('navigation.links'), '#', if: Proc.new { visble_links(context).any? } do |subnav|
primary.item :links, I18n.t('navigation.links'), '#', if: proc { visble_links(context).any? } do |subnav|
visble_links(context).each do |link|
subnav.item link.id, link.name, context.link_path(link)
end
@ -11,15 +11,15 @@ module FoodsoftLinks
primary.items.insert(i, primary.items.delete_at(-1))
end
unless primary[:admin].nil?
sub_nav = primary[:admin].sub_navigation
sub_nav.items <<
SimpleNavigation::Item.new(primary, :links, I18n.t('navigation.admin.links'), context.admin_links_path)
# move to right before config item
if i = sub_nav.items.index(sub_nav[:config])
sub_nav.items.insert(i, sub_nav.items.delete_at(-1))
end
end
return if primary[:admin].nil?
sub_nav = primary[:admin].sub_navigation
sub_nav.items <<
SimpleNavigation::Item.new(primary, :links, I18n.t('navigation.admin.links'), context.admin_links_path)
# move to right before config item
return unless i = sub_nav.items.index(sub_nav[:config])
sub_nav.items.insert(i, sub_nav.items.delete_at(-1))
end
def visble_links(context)

View file

@ -1,3 +1,3 @@
module FoodsoftLinks
VERSION = "0.0.1"
VERSION = '0.0.1'
end

View file

@ -20,7 +20,7 @@ RDoc::Task.new(:rdoc) do |rdoc|
rdoc.rdoc_files.include('lib/**/*.rb')
end
APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__)
APP_RAKEFILE = File.expand_path('test/dummy/Rakefile', __dir__)
load 'rails/tasks/engine.rake'
Bundler::GemHelper.install_tasks
@ -34,4 +34,4 @@ Rake::TestTask.new(:test) do |t|
t.verbose = false
end
task :default => :test
task default: :test

View file

@ -4,7 +4,7 @@ class Admin::MessagegroupsController < Admin::BaseController
def index
@messagegroups = Messagegroup.order('name ASC')
# if somebody uses the search field:
@messagegroups = @messagegroups.where('name LIKE ?', "%#{params[:query]}%") unless params[:query].blank?
@messagegroups = @messagegroups.where('name LIKE ?', "%#{params[:query]}%") if params[:query].present?
@messagegroups = @messagegroups.page(params[:page]).per(@per_page)
end
@ -13,7 +13,7 @@ class Admin::MessagegroupsController < Admin::BaseController
@messagegroup = Messagegroup.find(params[:id])
@messagegroup.destroy
redirect_to admin_messagegroups_url, notice: t('admin.messagegroups.destroy.notice')
rescue => error
redirect_to admin_messagegroups_url, alert: t('admin.messagegroups.destroy.error', error: error.message)
rescue StandardError => e
redirect_to admin_messagegroups_url, alert: t('admin.messagegroups.destroy.error', error: e.message)
end
end

View file

@ -1,17 +1,17 @@
class MessagegroupsController < ApplicationController
def index
@messagegroups = Messagegroup.order("name")
@messagegroups = Messagegroup.order('name')
end
def join
@messagegroup = Messagegroup.find(params[:id])
@messagegroup.users << current_user
redirect_to messagegroups_url, :notice => I18n.t('messagegroups.join.notice')
redirect_to messagegroups_url, notice: I18n.t('messagegroups.join.notice')
end
def leave
@messagegroup = Messagegroup.find(params[:id])
@messagegroup.users.destroy(current_user)
redirect_to messagegroups_url, :notice => I18n.t('messagegroups.leave.notice')
redirect_to messagegroups_url, notice: I18n.t('messagegroups.leave.notice')
end
end

View file

@ -10,21 +10,20 @@ class MessagesController < ApplicationController
def new
@message = Message.new(params[:message])
if @message.reply_to
original_message = Message.find(@message.reply_to)
if original_message.reply_to
@message.reply_to = original_message.reply_to
end
if original_message.is_readable_for?(current_user)
@message.add_recipients [original_message.sender_id]
@message.group_id = original_message.group_id
@message.private = original_message.private
@message.subject = I18n.t('messages.model.reply_subject', :subject => original_message.subject)
@message.body = I18n.t('messages.model.reply_header', :user => original_message.sender.display, :when => I18n.l(original_message.created_at, :format => :short)) + "\n"
original_message.body.each_line { |l| @message.body += I18n.t('messages.model.reply_indent', :line => l) }
else
redirect_to new_message_url, alert: I18n.t('messages.new.error_private')
end
return unless @message.reply_to
original_message = Message.find(@message.reply_to)
@message.reply_to = original_message.reply_to if original_message.reply_to
if original_message.is_readable_for?(current_user)
@message.add_recipients [original_message.sender_id]
@message.group_id = original_message.group_id
@message.private = original_message.private
@message.subject = I18n.t('messages.model.reply_subject', subject: original_message.subject)
@message.body = I18n.t('messages.model.reply_header', user: original_message.sender.display,
when: I18n.l(original_message.created_at, format: :short)) + "\n"
original_message.body.each_line { |l| @message.body += I18n.t('messages.model.reply_indent', line: l) }
else
redirect_to new_message_url, alert: I18n.t('messages.new.error_private')
end
end
@ -33,18 +32,18 @@ class MessagesController < ApplicationController
@message = @current_user.send_messages.new(params[:message])
if @message.save
DeliverMessageJob.perform_later(@message)
redirect_to messages_url, :notice => I18n.t('messages.create.notice')
redirect_to messages_url, notice: I18n.t('messages.create.notice')
else
render :action => 'new'
render action: 'new'
end
end
# Shows a single message.
def show
@message = Message.find(params[:id])
unless @message.is_readable_for?(current_user)
redirect_to messages_url, alert: I18n.t('messages.new.error_private')
end
return if @message.is_readable_for?(current_user)
redirect_to messages_url, alert: I18n.t('messages.new.error_private')
end
def toggle_private

View file

@ -1,11 +1,11 @@
module MessagesHelper
def format_subject(message, length)
if message.subject.length > length
subject = truncate(message.subject, :length => length)
body = ""
subject = truncate(message.subject, length: length)
body = ''
else
subject = message.subject
body = truncate(message.body, :length => length - subject.length)
body = truncate(message.body, length: length - subject.length)
end
"<b>#{link_to(h(subject), message)}</b> <span style='color:grey'>#{h(body)}</span>".html_safe
end

View file

@ -1,4 +1,4 @@
require "email_reply_trimmer"
require 'email_reply_trimmer'
class MessagesMailReceiver
def self.regexp
@ -9,29 +9,25 @@ class MessagesMailReceiver
@message = Message.find_by_id(match[:message_id])
@user = User.find_by_id(match[:user_id])
raise "Message could not be found" if @message.nil?
raise "User could not be found" if @user.nil?
raise 'Message could not be found' if @message.nil?
raise 'User could not be found' if @user.nil?
hash = @message.mail_hash_for_user(@user)
raise "Hash does not match expectations" unless hash.casecmp(match[:hash]) == 0
raise 'Hash does not match expectations' unless hash.casecmp(match[:hash]) == 0
end
def received(data)
mail = Mail.new data
mail_part = get_mail_part(mail)
raise "No valid content could be found" if mail_part.nil?
raise 'No valid content could be found' if mail_part.nil?
body = mail_part.body.decoded
unless mail_part.content_type_parameters.nil?
body = body.force_encoding mail_part.content_type_parameters[:charset]
end
body = body.force_encoding mail_part.content_type_parameters[:charset] unless mail_part.content_type_parameters.nil?
if MIME::Type.simplified(mail_part.content_type) == "text/html"
body = Nokogiri::HTML(body).text
end
body = Nokogiri::HTML(body).text if MIME::Type.simplified(mail_part.content_type) == 'text/html'
body.encode!(Encoding::default_internal)
body.encode!(Encoding.default_internal)
body = EmailReplyTrimmer.trim(body)
raise BlankBodyException if body.empty?
@ -39,16 +35,16 @@ class MessagesMailReceiver
group: @message.group,
private: @message.private,
received_email: data
if @message.reply_to
message.reply_to_message = @message.reply_to_message
else
message.reply_to_message = @message
end
if mail.subject
message.subject = mail.subject.gsub("[#{FoodsoftConfig[:name]}] ", "")
else
message.subject = I18n.t('messages.model.reply_subject', subject: message.reply_to_message.subject)
end
message.reply_to_message = if @message.reply_to
@message.reply_to_message
else
@message
end
message.subject = if mail.subject
mail.subject.gsub("[#{FoodsoftConfig[:name]}] ", '')
else
I18n.t('messages.model.reply_subject', subject: message.reply_to_message.subject)
end
message.add_recipients [@message.sender_id]
message.save!
@ -64,9 +60,7 @@ class MessagesMailReceiver
for part in mail.parts
part = get_mail_part(part)
content_type = MIME::Type.simplified(part.content_type)
if content_type == "text/plain" || !mail_part && content_type == "text/html"
mail_part = part
end
mail_part = part if content_type == 'text/plain' || (!mail_part && content_type == 'text/html')
end
mail_part
end

View file

@ -1,17 +1,17 @@
require "base32"
require 'base32'
class Message < ApplicationRecord
belongs_to :sender, class_name: 'User', foreign_key: 'sender_id'
belongs_to :group, optional: true, class_name: 'Group', foreign_key: 'group_id'
belongs_to :sender, class_name: 'User'
belongs_to :group, optional: true, class_name: 'Group'
belongs_to :reply_to_message, optional: true, class_name: 'Message', foreign_key: 'reply_to'
has_many :message_recipients, dependent: :destroy
has_many :recipients, through: :message_recipients, source: :user
attr_accessor :send_method, :recipient_tokens, :order_id
scope :threads, -> { where(:reply_to => nil) }
scope :thread, ->(id) { where("id = ? OR reply_to = ?", id, id) }
scope :readable_for, ->(user) {
scope :threads, -> { where(reply_to: nil) }
scope :thread, ->(id) { where('id = ? OR reply_to = ?', id, id) }
scope :readable_for, lambda { |user|
user_id = user.try(&:id)
joins(:message_recipients)
@ -20,7 +20,7 @@ class Message < ApplicationRecord
}
validates_presence_of :message_recipients, :subject, :body
validates_length_of :subject, :in => 1..255
validates_length_of :subject, in: 1..255
after_initialize do
@recipients_ids ||= []
@ -33,7 +33,7 @@ class Message < ApplicationRecord
def create_message_recipients
user_ids = @recipients_ids
user_ids += User.undeleted.pluck(:id) if send_method == 'all'
user_ids += Group.find(group_id).users.pluck(:id) unless group_id.blank?
user_ids += Group.find(group_id).users.pluck(:id) if group_id.present?
user_ids += Order.find(order_id).users_ordered.pluck(:id) if send_method == 'order'
user_ids.uniq.each do |user_id|
@ -47,7 +47,7 @@ class Message < ApplicationRecord
end
def group_id=(group_id)
group = Group.find(group_id) unless group_id.blank?
group = Group.find(group_id) if group_id.present?
if group
@send_method = 'workgroup' if group.type == 'Workgroup'
@send_method = 'ordergroup' if group.type == 'Ordergroup'
@ -96,29 +96,29 @@ class Message < ApplicationRecord
def mail_hash_for_user(user)
digest = Digest::SHA1.new
digest.update self.id.to_s
digest.update ":"
digest.update id.to_s
digest.update ':'
digest.update salt
digest.update ":"
digest.update ':'
digest.update user.id.to_s
Base32.encode digest.digest
end
# Returns true if this message is a system message, i.e. was sent automatically by Foodsoft itself.
def system_message?
self.sender_id.nil?
sender_id.nil?
end
def sender_name
system_message? ? I18n.t('layouts.foodsoft') : sender.display rescue "?"
system_message? ? I18n.t('layouts.foodsoft') : sender.display
rescue StandardError
'?'
end
def recipients_ids
@recipients_ids
end
attr_reader :recipients_ids
def last_reply
Message.where(reply_to: self.id).order(:created_at).last
Message.where(reply_to: id).order(:created_at).last
end
def is_readable_for?(user)
@ -135,6 +135,6 @@ class Message < ApplicationRecord
private
def create_salt
self.salt = [Array.new(6) { rand(256).chr }.join].pack("m").chomp
self.salt = [Array.new(6) { rand(256).chr }.join].pack('m').chomp
end
end

View file

@ -2,5 +2,5 @@ class MessageRecipient < ActiveRecord::Base
belongs_to :message
belongs_to :user
enum email_state: [:pending, :sent, :skipped]
enum email_state: %i[pending sent skipped]
end

View file

@ -1,5 +1,3 @@
class Messagegroup < Group
validates_uniqueness_of :name
protected
end

View file

@ -1,13 +1,13 @@
Rails.application.routes.draw do
scope '/:foodcoop' do
resources :messages, :only => [:index, :show, :new, :create] do
resources :messages, only: %i[index show new create] do
member do
get :thread
post :toggle_private
end
end
resources :message_threads, :only => [:index, :show]
resources :message_threads, only: %i[index show]
resources :messagegroups, only: [:index] do
member do

View file

@ -1,6 +1,6 @@
class AddEmailToMessage < ActiveRecord::Migration[4.2]
def change
add_column :messages, :salt, :string
add_column :messages, :received_email, :binary, :limit => 1.megabyte
add_column :messages, :received_email, :binary, limit: 1.megabyte
end
end

View file

@ -1,25 +1,26 @@
$:.push File.expand_path("../lib", __FILE__)
$:.push File.expand_path('lib', __dir__)
# Maintain your gem's version:
require "foodsoft_messages/version"
require 'foodsoft_messages/version'
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "foodsoft_messages"
s.name = 'foodsoft_messages'
s.version = FoodsoftMessages::VERSION
s.authors = ["robwa"]
s.email = ["foodsoft-messages@ini.tiative.net"]
s.homepage = "https://github.com/foodcoops/foodsoft"
s.summary = "Messaging plugin for foodsoft."
s.description = "Adds the ability to exchange messages to foodsoft."
s.authors = ['robwa']
s.email = ['foodsoft-messages@ini.tiative.net']
s.homepage = 'https://github.com/foodcoops/foodsoft'
s.summary = 'Messaging plugin for foodsoft.'
s.description = 'Adds the ability to exchange messages to foodsoft.'
s.files = Dir["{app,config,db,lib}/**/*"] + ["Rakefile", "README.md"]
s.files = Dir['{app,config,db,lib}/**/*'] + ['Rakefile', 'README.md']
s.add_dependency "rails"
s.add_dependency "base32"
s.add_dependency "deface", "~> 1.0"
s.add_dependency "email_reply_trimmer"
s.add_dependency "mail"
s.add_dependency 'rails'
s.add_dependency 'base32'
s.add_dependency 'deface', '~> 1.0'
s.add_dependency 'email_reply_trimmer'
s.add_dependency 'mail'
s.add_development_dependency "sqlite3"
s.add_development_dependency 'sqlite3'
s.metadata['rubygems_mfa_required'] = 'true'
end

View file

@ -1,7 +1,7 @@
require "foodsoft_messages/engine"
require "foodsoft_messages/mail_receiver"
require "foodsoft_messages/user_link"
require "deface"
require 'foodsoft_messages/engine'
require 'foodsoft_messages/mail_receiver'
require 'foodsoft_messages/user_link'
require 'deface'
module FoodsoftMessages
# Return whether messages are used or not.

View file

@ -12,15 +12,16 @@ module FoodsoftMessages
sub_nav.items.insert(i, sub_nav.items.delete_at(-1))
end
end
unless primary[:admin].nil?
sub_nav = primary[:admin].sub_navigation
sub_nav.items <<
SimpleNavigation::Item.new(primary, :messagegroups, I18n.t('navigation.admin.messagegroups'), context.admin_messagegroups_path)
# move to right before config item
if i = sub_nav.items.index(sub_nav[:config])
sub_nav.items.insert(i, sub_nav.items.delete_at(-1))
end
end
return if primary[:admin].nil?
sub_nav = primary[:admin].sub_navigation
sub_nav.items <<
SimpleNavigation::Item.new(primary, :messagegroups, I18n.t('navigation.admin.messagegroups'),
context.admin_messagegroups_path)
# move to right before config item
return unless i = sub_nav.items.index(sub_nav[:config])
sub_nav.items.insert(i, sub_nav.items.delete_at(-1))
end
def default_foodsoft_config(cfg)

View file

@ -8,7 +8,7 @@ module FoodsoftMessages
show_user user
else
link_to show_user(user), new_message_path('message[mail_to]' => user.id),
:title => I18n.t('helpers.messages.write_message')
title: I18n.t('helpers.messages.write_message')
end
end
end
@ -18,5 +18,5 @@ end
# modify existing helper
ActiveSupport.on_load(:after_initialize) do
ApplicationHelper.send :include, FoodsoftMessages::UserLink
ApplicationHelper.include FoodsoftMessages::UserLink
end

View file

@ -1,3 +1,3 @@
module FoodsoftMessages
VERSION = "0.0.1"
VERSION = '0.0.1'
end

View file

@ -20,7 +20,7 @@ RDoc::Task.new(:rdoc) do |rdoc|
rdoc.rdoc_files.include('lib/**/*.rb')
end
APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__)
APP_RAKEFILE = File.expand_path('test/dummy/Rakefile', __dir__)
load 'rails/tasks/engine.rake'
Bundler::GemHelper.install_tasks
@ -34,4 +34,4 @@ Rake::TestTask.new(:test) do |t|
t.verbose = false
end
task :default => :test
task default: :test

View file

@ -27,9 +27,9 @@ class PollsController < ApplicationController
def edit
@poll = Poll.find(params[:id])
if user_has_no_right
redirect_to polls_path, alert: t('.no_right')
end
return unless user_has_no_right
redirect_to polls_path, alert: t('.no_right')
end
def update
@ -53,8 +53,8 @@ class PollsController < ApplicationController
@poll.destroy
redirect_to polls_path, notice: t('.notice')
end
rescue => error
redirect_to polls_path, alert: t('.error', error: error.message)
rescue StandardError => e
redirect_to polls_path, alert: t('.error', error: e.message)
end
def vote
@ -73,25 +73,25 @@ class PollsController < ApplicationController
@poll_vote = @poll.poll_votes.where(attributes).first_or_initialize
if request.post?
@poll_vote.update!(note: params[:note], user: current_user)
return unless request.post?
if @poll.single_select?
choices = {}
choice = params[:choice]
choices[choice] = '1' if choice
else
choices = params[:choices].try(:to_h) || {}
end
@poll_vote.update!(note: params[:note], user: current_user)
@poll_vote.poll_choices = choices.map do |choice, value|
poll_choice = @poll_vote.poll_choices.where(choice: choice).first_or_initialize
poll_choice.update!(value: value)
poll_choice
end
redirect_to @poll
if @poll.single_select?
choices = {}
choice = params[:choice]
choices[choice] = '1' if choice
else
choices = params[:choices].try(:to_h) || {}
end
@poll_vote.poll_choices = choices.map do |choice, value|
poll_choice = @poll_vote.poll_choices.where(choice: choice).first_or_initialize
poll_choice.update!(value: value)
poll_choice
end
redirect_to @poll
end
private

View file

@ -24,14 +24,14 @@ class CreatePolls < ActiveRecord::Migration[4.2]
t.references :ordergroup
t.text :note
t.timestamps
t.index [:poll_id, :user_id, :ordergroup_id], unique: true
t.index %i[poll_id user_id ordergroup_id], unique: true
end
create_table :poll_choices do |t|
t.references :poll_vote, null: false
t.integer :choice, null: false
t.integer :value, null: false
t.index [:poll_vote_id, :choice], unique: true
t.index %i[poll_vote_id choice], unique: true
end
end
end

View file

@ -1,5 +1,5 @@
class IncreaseChoicesSize < ActiveRecord::Migration[4.2]
def up
change_column :polls, :choices, :text, limit: 65535
change_column :polls, :choices, :text, limit: 65_535
end
end

View file

@ -1,20 +1,21 @@
$:.push File.expand_path("../lib", __FILE__)
$:.push File.expand_path('lib', __dir__)
# Maintain your gem's version:
require "foodsoft_polls/version"
require 'foodsoft_polls/version'
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "foodsoft_polls"
s.name = 'foodsoft_polls'
s.version = FoodsoftPolls::VERSION
s.authors = ["paroga"]
s.email = ["paroga@paroga.com"]
s.homepage = "https://github.com/foodcoops/foodsoft"
s.summary = "Polls plugin for foodsoft."
s.description = "Adds possibility to do polls with foodsoft."
s.authors = ['paroga']
s.email = ['paroga@paroga.com']
s.homepage = 'https://github.com/foodcoops/foodsoft'
s.summary = 'Polls plugin for foodsoft.'
s.description = 'Adds possibility to do polls with foodsoft.'
s.files = Dir["{app,config,db,lib}/**/*"] + ["Rakefile", "README.md"]
s.files = Dir['{app,config,db,lib}/**/*'] + ['Rakefile', 'README.md']
s.add_dependency "rails"
s.add_dependency "deface", "~> 1.0"
s.add_dependency 'rails'
s.add_dependency 'deface', '~> 1.0'
s.metadata['rubygems_mfa_required'] = 'true'
end

View file

@ -8,9 +8,9 @@ module FoodsoftPolls
sub_nav.items <<
SimpleNavigation::Item.new(primary, :polls, I18n.t('navigation.polls'), context.polls_path)
# move to right before tasks item
if i = sub_nav.items.index(sub_nav[:tasks])
sub_nav.items.insert(i, sub_nav.items.delete_at(-1))
end
return unless i = sub_nav.items.index(sub_nav[:tasks])
sub_nav.items.insert(i, sub_nav.items.delete_at(-1))
end
end
end

View file

@ -1,3 +1,3 @@
module FoodsoftPolls
VERSION = "0.0.1"
VERSION = '0.0.1'
end

View file

@ -20,7 +20,7 @@ RDoc::Task.new(:rdoc) do |rdoc|
rdoc.rdoc_files.include('lib/**/*.rb')
end
APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__)
APP_RAKEFILE = File.expand_path('test/dummy/Rakefile', __dir__)
load 'rails/tasks/engine.rake'
Bundler::GemHelper.install_tasks
@ -34,4 +34,4 @@ Rake::TestTask.new(:test) do |t|
t.verbose = false
end
task :default => :test
task default: :test

View file

@ -37,9 +37,7 @@ class PrinterController < ApplicationController
job = PrinterJob.unfinished.find_by_id(json[:id])
return unless job
if json[:state]
job.add_update! json[:state], json[:message]
end
job.add_update! json[:state], json[:message] if json[:state]
job.finish! if json[:finish]
end

View file

@ -15,7 +15,7 @@ class PrinterJobsController < ApplicationController
state = order.open? ? 'queued' : 'ready'
count = 0
PrinterJob.transaction do
%w(articles fax groups matrix).each do |document|
%w[articles fax groups matrix].each do |document|
next unless FoodsoftConfig["printer_print_order_#{document}"]
job = PrinterJob.create! order: order, document: document, created_by: current_user
@ -47,7 +47,7 @@ class PrinterJobsController < ApplicationController
job = PrinterJob.find(params[:id])
job.finish! current_user
redirect_to printer_jobs_path, notice: t('.notice')
rescue => error
redirect_to printer_jobs_path, t('errors.general_msg', msg: error.message)
rescue StandardError => e
redirect_to printer_jobs_path, t('errors.general_msg', msg: e.message)
end
end

View file

@ -4,7 +4,7 @@ Rails.application.routes.draw do
get :socket, on: :collection
end
resources :printer_jobs, only: [:index, :create, :show, :destroy] do
resources :printer_jobs, only: %i[index create show destroy] do
post :requeue, on: :member
get :document, on: :member
end

View file

@ -15,6 +15,6 @@ class CreatePrinterJobs < ActiveRecord::Migration[4.2]
t.text :message
end
add_index :printer_job_updates, [:printer_job_id, :created_at]
add_index :printer_job_updates, %i[printer_job_id created_at]
end
end

View file

@ -1,21 +1,22 @@
$:.push File.expand_path("../lib", __FILE__)
$:.push File.expand_path('lib', __dir__)
# Maintain your gem's version:
require "foodsoft_printer/version"
require 'foodsoft_printer/version'
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "foodsoft_printer"
s.name = 'foodsoft_printer'
s.version = FoodsoftPrinter::VERSION
s.authors = ["paroga"]
s.email = ["paroga@paroga.com"]
s.homepage = "https://github.com/foodcoops/foodsoft"
s.summary = "Printer plugin for foodsoft."
s.description = "Add a printer queue to foodsoft."
s.authors = ['paroga']
s.email = ['paroga@paroga.com']
s.homepage = 'https://github.com/foodcoops/foodsoft'
s.summary = 'Printer plugin for foodsoft.'
s.description = 'Add a printer queue to foodsoft.'
s.files = Dir["{app,config,db,lib}/**/*"] + ["Rakefile", "README.md"]
s.files = Dir['{app,config,db,lib}/**/*'] + ['Rakefile', 'README.md']
s.add_dependency "rails"
s.add_dependency "deface", "~> 1.0"
s.add_dependency "tubesock"
s.add_dependency 'rails'
s.add_dependency 'deface', '~> 1.0'
s.add_dependency 'tubesock'
s.metadata['rubygems_mfa_required'] = 'true'
end

View file

@ -3,18 +3,19 @@ module FoodsoftPrinter
def navigation(primary, context)
return unless FoodsoftPrinter.enabled?
unless primary[:orders].nil?
sub_nav = primary[:orders].sub_navigation
sub_nav.items <<
SimpleNavigation::Item.new(primary, :printer_jobs, I18n.t('navigation.orders.printer_jobs'), context.printer_jobs_path)
end
return if primary[:orders].nil?
sub_nav = primary[:orders].sub_navigation
sub_nav.items <<
SimpleNavigation::Item.new(primary, :printer_jobs, I18n.t('navigation.orders.printer_jobs'),
context.printer_jobs_path)
end
def default_foodsoft_config(cfg)
cfg[:use_printer] = false
end
initializer 'foodsoft_printer.order_printer_jobs' do |app|
initializer 'foodsoft_printer.order_printer_jobs' do |_app|
if Rails.configuration.cache_classes
OrderPrinterJobs.install
else

View file

@ -4,14 +4,14 @@ module FoodsoftPrinter
base.class_eval do
has_many :printer_jobs, dependent: :destroy
alias foodsoft_printer_orig_finish! finish!
alias_method :foodsoft_printer_orig_finish!, :finish!
def finish!(user)
foodsoft_printer_orig_finish!(user)
unless finished?
printer_jobs.unfinished.each do |job|
job.add_update! 'ready'
end
return if finished?
printer_jobs.unfinished.each do |job|
job.add_update! 'ready'
end
end
end

View file

@ -1,3 +1,3 @@
module FoodsoftPrinter
VERSION = "0.0.1"
VERSION = '0.0.1'
end

View file

@ -1,20 +1,21 @@
$:.push File.expand_path("../lib", __FILE__)
$:.push File.expand_path('lib', __dir__)
# Maintain your gem's version:
require "foodsoft_uservoice/version"
require 'foodsoft_uservoice/version'
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "foodsoft_uservoice"
s.name = 'foodsoft_uservoice'
s.version = FoodsoftUservoice::VERSION
s.authors = ["wvengen"]
s.email = ["dev-foodsoft@willem.engen.nl"]
s.homepage = "https://github.com/foodcoops/foodsoft"
s.summary = "Uservoice plugin for foodsoft."
s.description = "Adds a uservoice feedback button to foodsoft."
s.authors = ['wvengen']
s.email = ['dev-foodsoft@willem.engen.nl']
s.homepage = 'https://github.com/foodcoops/foodsoft'
s.summary = 'Uservoice plugin for foodsoft.'
s.description = 'Adds a uservoice feedback button to foodsoft.'
s.files = Dir["{app,config,db,lib}/**/*"] + ["README.md"]
s.files = Dir['{app,config,db,lib}/**/*'] + ['README.md']
s.add_dependency "rails"
s.add_dependency "content_for_in_controllers"
s.add_dependency 'rails'
s.add_dependency 'content_for_in_controllers'
s.metadata['rubygems_mfa_required'] = 'true'
end

View file

@ -1,5 +1,5 @@
require "content_for_in_controllers"
require "foodsoft_uservoice/engine"
require 'content_for_in_controllers'
require 'foodsoft_uservoice/engine'
module FoodsoftUservoice
# enabled when configured, but can still be disabled by use_uservoice option
@ -19,11 +19,11 @@ module FoodsoftUservoice
# include uservoice javascript
api_key = FoodsoftConfig[:uservoice]['api_key']
js_pre = "UserVoice=window.UserVoice||[];"
js_pre = 'UserVoice=window.UserVoice||[];'
js_load = "var uv=document.createElement('script');uv.type='text/javascript';uv.async=true;uv.src='//widget.uservoice.com/#{view_context.j api_key}.js';var s=document.getElementsByTagName('script')[0];s.parentNode.insertBefore(uv,s);"
# configuration
sections = FoodsoftConfig[:uservoice].reject { |k, v| k == 'api_key' }
sections = FoodsoftConfig[:uservoice].except('api_key')
sections.each_pair do |k, v|
if k == 'identify'
v['id'] = current_user.try(:id) if v.include?('id')
@ -48,5 +48,5 @@ module FoodsoftUservoice
end
ActiveSupport.on_load(:after_initialize) do
ApplicationController.send :include, FoodsoftUservoice::LoadUservoice
ApplicationController.include FoodsoftUservoice::LoadUservoice
end

View file

@ -1,3 +1,3 @@
module FoodsoftUservoice
VERSION = "0.0.1"
VERSION = '0.0.1'
end

View file

@ -20,7 +20,7 @@ RDoc::Task.new(:rdoc) do |rdoc|
rdoc.rdoc_files.include('lib/**/*.rb')
end
APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__)
APP_RAKEFILE = File.expand_path('test/dummy/Rakefile', __dir__)
load 'rails/tasks/engine.rake'
Bundler::GemHelper.install_tasks
@ -34,4 +34,4 @@ Rake::TestTask.new(:test) do |t|
t.verbose = false
end
task :default => :test
task default: :test

View file

@ -1,20 +1,20 @@
class PagesController < ApplicationController
before_action -> { require_plugin_enabled FoodsoftWiki }
before_action :catch_special_pages, only: [:show, :new]
before_action :catch_special_pages, only: %i[show new]
skip_before_action :authenticate, :only => :all
before_action :only => :all do
authenticate_or_token(['wiki', 'all'])
skip_before_action :authenticate, only: :all
before_action only: :all do
authenticate_or_token(%w[wiki all])
end
before_action do
content_for :head, view_context.rss_meta_tag
end
def index
@page = Page.find_by_permalink "Home"
@page = Page.find_by_permalink 'Home'
if @page
render :action => 'show'
render action: 'show'
else
redirect_to all_pages_path
end
@ -34,11 +34,11 @@ class PagesController < ApplicationController
end
if @page.nil?
redirect_to new_page_path(:title => params[:permalink])
redirect_to new_page_path(title: params[:permalink])
elsif @page.redirect?
page = Page.find_by_id(@page.redirect)
unless page.nil?
flash[:notice] = I18n.t('pages.cshow.redirect_notice', :page => @page.title)
flash[:notice] = I18n.t('pages.cshow.redirect_notice', page: @page.title)
redirect_to wiki_page_path(page.permalink)
end
end
@ -46,12 +46,12 @@ class PagesController < ApplicationController
def new
@page = Page.new
@page.title = params[:title].gsub("_", " ") if params[:title]
@page.title = params[:title].gsub('_', ' ') if params[:title]
@page.parent = Page.find_by_permalink(params[:parent]) if params[:parent]
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @page }
format.xml { render xml: @page }
end
end
@ -60,36 +60,32 @@ class PagesController < ApplicationController
end
def create
@page = Page.new(params[:page].merge({ :user => current_user }))
@page = Page.new(params[:page].merge({ user: current_user }))
if params[:preview]
render :action => 'new'
render action: 'new'
elsif @page.save
flash[:notice] = I18n.t('pages.create.notice')
redirect_to(wiki_page_path(@page.permalink))
else
if @page.save
flash[:notice] = I18n.t('pages.create.notice')
redirect_to(wiki_page_path(@page.permalink))
else
render :action => "new"
end
render action: 'new'
end
end
def update
@page = Page.find(params[:id])
@page.attributes = params[:page].merge({ :user => current_user })
@page.attributes = params[:page].merge({ user: current_user })
if params[:preview]
@page.attributes = params[:page]
render :action => 'edit'
render action: 'edit'
elsif @page.save
@page.parent_id = parent_id if params[:parent_id].present? \
&& params[:parent_id] != @page_id
flash[:notice] = I18n.t('pages.update.notice')
redirect_to wiki_page_path(@page.permalink)
else
if @page.save
@page.parent_id = parent_id if (!params[:parent_id].blank? \
&& params[:parent_id] != @page_id)
flash[:notice] = I18n.t('pages.update.notice')
redirect_to wiki_page_path(@page.permalink)
else
render :action => "edit"
end
render action: 'edit'
end
rescue ActiveRecord::StaleObjectError
flash[:error] = I18n.t('pages.error_stale_object')
@ -100,7 +96,7 @@ class PagesController < ApplicationController
@page = Page.find(params[:id])
@page.destroy
flash[:notice] = I18n.t('pages.destroy.notice', :page => @page.title)
flash[:notice] = I18n.t('pages.destroy.notice', page: @page.title)
redirect_to wiki_path
end
@ -109,23 +105,23 @@ class PagesController < ApplicationController
@partial = params[:view] || 'site_map'
if params[:name]
@pages = @pages.where("title LIKE ?", "%#{params[:name]}%").limit(20)
@pages = @pages.where('title LIKE ?', "%#{params[:name]}%").limit(20)
@partial = 'title_list'
end
if params[:sort]
sort = case params[:sort]
when "title" then "title"
when "title_reverse" then "title DESC"
when "last_updated" then "updated_at DESC"
when "last_updated_reverse" then "updated_at"
sort = if params[:sort]
case params[:sort]
when 'title' then 'title'
when 'title_reverse' then 'title DESC'
when 'last_updated' then 'updated_at DESC'
when 'last_updated_reverse' then 'updated_at'
end
else
sort = "title"
end
else
'title'
end
@pages = @pages.order(sort)
respond_to do |format|
format.html
format.rss { render :layout => false }
format.rss { render layout: false }
end
end
@ -150,15 +146,15 @@ class PagesController < ApplicationController
def variables
keys = Foodsoft::ExpansionVariables.variables.keys
@variables = Hash[keys.map { |k| [k, Foodsoft::ExpansionVariables.get(k)] }]
@variables = keys.index_with { |k| Foodsoft::ExpansionVariables.get(k) }
render 'variables'
end
private
def catch_special_pages
if params[:id] == 'Help:Foodsoft_variables'
variables
end
return unless params[:id] == 'Help:Foodsoft_variables'
variables
end
end

View file

@ -2,70 +2,70 @@ module PagesHelper
include WikiCloth
def rss_meta_tag
tag.link(rel: "alternate", type: "application/rss+xml", title: "RSS", href: all_pages_rss_url).html_safe
tag.link(rel: 'alternate', type: 'application/rss+xml', title: 'RSS', href: all_pages_rss_url).html_safe
end
def wikified_body(body, title = nil)
FoodsoftWiki::WikiParser.new(data: body + "\n", params: { referer: title }).to_html(noedit: true).html_safe
rescue => e
rescue StandardError => e
# try the following with line breaks: === one === == two == = three =
content_tag :span, class: 'alert alert-error' do
I18n.t '.wikicloth_exception', :msg => e
I18n.t '.wikicloth_exception', msg: e
end.html_safe
end
def link_to_wikipage(page, text = nil)
if text == nil
link_to page.title, wiki_page_path(:permalink => page.permalink)
if text.nil?
link_to page.title, wiki_page_path(permalink: page.permalink)
else
link_to text, wiki_page_path(:permalink => page.permalink)
link_to text, wiki_page_path(permalink: page.permalink)
end
end
def link_to_wikipage_by_permalink(permalink, text = nil)
unless permalink.blank?
page = Page.find_by_permalink(permalink)
if page.nil?
if text.nil?
link_to permalink, new_page_path(:title => permalink)
else
link_to text, new_page_path(:title => permalink)
end
return if permalink.blank?
page = Page.find_by_permalink(permalink)
if page.nil?
if text.nil?
link_to permalink, new_page_path(title: permalink)
else
link_to_wikipage(page, text)
link_to text, new_page_path(title: permalink)
end
else
link_to_wikipage(page, text)
end
end
def generate_toc(body)
toc = String.new
body.gsub(/^([=]{1,6})\s*(.*?)\s*(\1)/) do
number = $1.length - 1
name = $2
body.gsub(/^(={1,6})\s*(.*?)\s*(\1)/) do
number = ::Regexp.last_match(1).length - 1
name = ::Regexp.last_match(2)
toc << "*" * number + " #{name}\n"
toc << (('*' * number) + " #{name}\n")
end
unless toc.blank?
FoodsoftWiki::WikiParser.new(data: toc).to_html.gsub(/<li>([^<>\n]*)/) do
name = $1
anchor = name.gsub(/\s/, '_').gsub(/[^a-zA-Z_]/, '')
"<li><a href='##{anchor}'>#{name.truncate(20)}</a>"
end.html_safe
end
return if toc.blank?
FoodsoftWiki::WikiParser.new(data: toc).to_html.gsub(/<li>([^<>\n]*)/) do
name = ::Regexp.last_match(1)
anchor = name.gsub(/\s/, '_').gsub(/[^a-zA-Z_]/, '')
"<li><a href='##{anchor}'>#{name.truncate(20)}</a>"
end.html_safe
end
def parent_pages_to_select(current_page)
unless current_page.homepage? # Homepage is the page trees root!
if current_page.homepage?
[]
else # Homepage is the page trees root!
Page.non_redirected.reject { |p| p == current_page || p.ancestors.include?(current_page) }
else
Array.new
end
end
# return url for all_pages rss feed
def all_pages_rss_url(options = {})
token = TokenVerifier.new(['wiki', 'all']).generate
all_pages_url({ :format => 'rss', :token => token }.merge(options))
token = TokenVerifier.new(%w[wiki all]).generate
all_pages_url({ format: 'rss', token: token }.merge(options))
end
end

View file

@ -1,61 +1,62 @@
class Page < ApplicationRecord
include ActsAsTree
belongs_to :user, :foreign_key => 'updated_by'
belongs_to :user, foreign_key: 'updated_by'
acts_as_versioned version_column: :lock_version
self.non_versioned_columns += %w(permalink created_at title)
self.non_versioned_columns += %w[permalink created_at title]
acts_as_tree :order => "title"
acts_as_tree order: 'title'
attr_accessor :old_title # Save title to create redirect page when editing title
validates_presence_of :title, :body
validates_uniqueness_of :permalink, :title
before_validation :set_permalink, :on => :create
before_validation :update_permalink, :on => :update
before_validation :set_permalink, on: :create
before_validation :update_permalink, on: :update
after_update :create_redirect
scope :non_redirected, -> { where(:redirect => nil) }
scope :no_parent, -> { where(:parent_id => nil) }
scope :non_redirected, -> { where(redirect: nil) }
scope :no_parent, -> { where(parent_id: nil) }
def self.permalink(title)
title.gsub(/[\/\.,;@\s]/, "_").gsub(/[\"\']/, "")
title.gsub(%r{[/.,;@\s]}, '_').gsub(/["']/, '')
end
def homepage?
permalink == "Home"
permalink == 'Home'
end
def self.dashboard
where(permalink: "Dashboard").first
where(permalink: 'Dashboard').first
end
def self.public_front_page
where(permalink: "Public_frontpage").first
where(permalink: 'Public_frontpage').first
end
def self.welcome_mail
where(permalink: "Welcome_mail").first
where(permalink: 'Welcome_mail').first
end
def set_permalink
unless title.blank?
self.permalink = Page.count == 0 ? "Home" : Page.permalink(title)
end
return if title.blank?
self.permalink = Page.count == 0 ? 'Home' : Page.permalink(title)
end
def diff
current = versions.latest
old = versions.where(["page_id = ? and lock_version < ?", current.page_id, current.lock_version]).order('lock_version DESC').first
old = versions.where(['page_id = ? and lock_version < ?', current.page_id,
current.lock_version]).order('lock_version DESC').first
if old
o = ''
Diffy::Diff.new(old.body, current.body).each do |line|
case line
when /^\+/ then o += "#{line.chomp}<br />" unless line.chomp == "+"
when /^-/ then o += "#{line.chomp}<br />" unless line.chomp == "-"
when /^\+/ then o += "#{line.chomp}<br />" unless line.chomp == '+'
when /^-/ then o += "#{line.chomp}<br />" unless line.chomp == '-'
end
end
o
@ -67,19 +68,19 @@ class Page < ApplicationRecord
protected
def update_permalink
if changed.include?("title")
set_permalink
self.old_title = changes["title"].first # Save title for creating redirect
end
return unless changed.include?('title')
set_permalink
self.old_title = changes['title'].first # Save title for creating redirect
end
def create_redirect
unless old_title.blank?
Page.create :redirect => id,
:title => old_title,
:body => I18n.t('model.page.redirect', :title => title),
:permalink => Page.permalink(old_title),
:updated_by => updated_by
end
return if old_title.blank?
Page.create redirect: id,
title: old_title,
body: I18n.t('model.page.redirect', title: title),
permalink: Page.permalink(old_title),
updated_by: updated_by
end
end

View file

@ -1,16 +1,16 @@
xml.instruct! :xml, :version => "1.0"
xml.rss :version => "2.0" do
xml.instruct! :xml, version: '1.0'
xml.rss version: '2.0' do
xml.channel do
xml.title FoodsoftConfig[:name] + " Wiki"
xml.description ""
xml.title FoodsoftConfig[:name] + ' Wiki'
xml.description ''
xml.link FoodsoftConfig[:homepage]
for page in @pages
xml.item do
xml.title page.title
xml.description page.diff, :type => "html"
xml.description page.diff, type: 'html'
xml.author User.find_by_id(page.updated_by).try(:display)
xml.pubDate page.updated_at.to_s(:rfc822)
xml.pubDate page.updated_at.to_fs(:rfc822)
xml.link wiki_page_path(page.permalink)
xml.guid page.updated_at.to_i
end

View file

@ -1,12 +1,12 @@
Rails.application.routes.draw do
scope '/:foodcoop' do
resources :pages do
get :all, :on => :collection
get :version, :on => :member
get :revert, :on => :member
get :diff, :on => :member
get :all, on: :collection
get :version, on: :member
get :revert, on: :member
get :diff, on: :member
end
get '/wiki/:permalink' => 'pages#show', :as => 'wiki_page' # , :constraints => {:permalink => /[^\s]+/}
get '/wiki' => 'pages#show', :defaults => { :permalink => 'Home' }, :as => 'wiki'
get '/wiki' => 'pages#show', :defaults => { permalink: 'Home' }, :as => 'wiki'
end
end

View file

@ -4,7 +4,7 @@ class CreatePages < ActiveRecord::Migration[4.2]
t.string :title
t.text :body
t.string :permalink
t.integer :lock_version, :default => 0
t.integer :lock_version, default: 0
t.integer :updated_by
t.integer :redirect
t.integer :parent_id

View file

@ -1,26 +1,27 @@
$:.push File.expand_path("../lib", __FILE__)
$:.push File.expand_path('lib', __dir__)
# Maintain your gem's version:
require "foodsoft_wiki/version"
require 'foodsoft_wiki/version'
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "foodsoft_wiki"
s.name = 'foodsoft_wiki'
s.version = FoodsoftWiki::VERSION
s.authors = ["wvengen"]
s.email = ["dev-foodsoft@willem.engen.nl"]
s.homepage = "https://github.com/foodcoops/foodsoft"
s.summary = "Wiki plugin for foodsoft."
s.description = "Adds a wiki to foodsoft."
s.authors = ['wvengen']
s.email = ['dev-foodsoft@willem.engen.nl']
s.homepage = 'https://github.com/foodcoops/foodsoft'
s.summary = 'Wiki plugin for foodsoft.'
s.description = 'Adds a wiki to foodsoft.'
s.files = Dir["{app,config,db,lib}/**/*"] + ["Rakefile", "README.md"]
s.files = Dir['{app,config,db,lib}/**/*'] + ['Rakefile', 'README.md']
s.add_dependency "rails"
s.add_dependency 'rails'
s.add_dependency 'wikicloth'
s.add_dependency 'twitter-text', '~> 1.14' # wikicloth doesn't support version 2
s.add_dependency 'acts_as_versioned' # need git version, make sure that is included in foodsoft's Gemfile
s.add_dependency "deface", "~> 1.0"
s.add_dependency 'deface', '~> 1.0'
s.add_dependency 'diffy'
s.add_dependency 'content_for_in_controllers'
s.add_development_dependency "sqlite3"
s.add_development_dependency 'sqlite3'
s.metadata['rubygems_mfa_required'] = 'true'
end

View file

@ -8,17 +8,17 @@ module FoodsoftWiki
subnav.item :all_pages, I18n.t('navigation.wiki.all_pages'), ctx.all_pages_path, id: nil
end
# move this last added item to just after the foodcoop menu
if i = primary.items.index(primary[:foodcoop])
primary.items.insert(i + 1, primary.items.delete_at(-1))
end
return unless i = primary.items.index(primary[:foodcoop])
primary.items.insert(i + 1, primary.items.delete_at(-1))
end
def default_foodsoft_config(cfg)
cfg[:use_wiki] = true
end
initializer "foodsoft_wiki.assets.precompile" do |app|
app.config.assets.precompile += %w(icons/feed-icon-14x14.png)
initializer 'foodsoft_wiki.assets.precompile' do |app|
app.config.assets.precompile += %w[icons/feed-icon-14x14.png]
end
end
end

View file

@ -3,10 +3,10 @@ module FoodsoftWiki
def self.included(base) # :nodoc:
base.class_eval do
# modify user presentation link to writing a message for the user
def additonal_welcome_text(user)
if FoodsoftWiki.enabled? && (page = Page.welcome_mail)
page.body
end
def additonal_welcome_text(_user)
return unless FoodsoftWiki.enabled? && (page = Page.welcome_mail)
page.body
end
end
end
@ -15,5 +15,5 @@ end
# modify existing helper
ActiveSupport.on_load(:after_initialize) do
Mailer.send :include, FoodsoftWiki::Mailer
Mailer.include FoodsoftWiki::Mailer
end

View file

@ -1,3 +1,3 @@
module FoodsoftWiki
VERSION = "0.0.1"
VERSION = '0.0.1'
end

View file

@ -10,7 +10,7 @@ module FoodsoftWiki
link_attributes_for do |page|
permalink = Page.permalink(page)
if Page.exists?(:permalink => permalink)
if Page.exists?(permalink: permalink)
{ href: url_for(:wiki_page_path, permalink: permalink) }
elsif page.include? '#'
# If "Foo#Bar" does not exist then consider "Foo" with anchor.
@ -20,8 +20,8 @@ module FoodsoftWiki
end
end
section_link do |section|
""
section_link do |_section|
''
end
def to_html(render_options = {})
@ -41,7 +41,7 @@ module FoodsoftWiki
return { href: '#' + anchor } if page.empty?
permalink = Page.permalink(page)
if Page.exists?(:permalink => permalink)
if Page.exists?(permalink: permalink)
{ href: url_for(:wiki_page_path, permalink: permalink, anchor: anchor) }
else
# Do not suggest to use number signs in the title.