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

@ -29,7 +29,7 @@ class AppleBar
def mean_order_amount_per_job
(1 / @global_avg).round
rescue
rescue StandardError
0
end

View file

@ -41,14 +41,14 @@ class BankAccountConnector
end
end
@@registered_classes = Set.new
@registered_classes = Set.new
def self.register(klass)
@@registered_classes.add klass
@registered_classes.add klass
end
def self.find(iban)
@@registered_classes.each do |klass|
@registered_classes.each do |klass|
return klass if klass.handles(iban)
end
nil

View file

@ -17,16 +17,16 @@ class BankAccountInformationImporter
ret = 0
booked.each do |t|
amount = parse_account_information_amount t[:transactionAmount]
entityName = amount < 0 ? t[:creditorName] : t[:debtorName]
entityAccount = amount < 0 ? t[:creditorAccount] : t[:debtorAccount]
entity_name = amount < 0 ? t[:creditorName] : t[:debtorName]
entity_account = amount < 0 ? t[:creditorAccount] : t[:debtorAccount]
reference = [t[:endToEndId], t[:remittanceInformationUnstructured]].join("\n").strip
@bank_account.bank_transactions.where(external_id: t[:transactionId]).first_or_create.update({
date: t[:bookingDate],
amount: amount,
iban: entityAccount && entityAccount[:iban],
iban: entity_account && entity_account[:iban],
reference: reference,
text: entityName,
text: entity_name,
receipt: t[:additionalInformation]
})
ret += 1
@ -34,7 +34,7 @@ class BankAccountInformationImporter
balances = (data[:balances] ? data[:balances].map { |b| [b[:balanceType], b[:balanceAmount]] } : []).to_h
balance = balances.values.first
%w(closingBooked expected authorised openingBooked interimAvailable forwardAvailable nonInvoiced).each do |type|
%w[closingBooked expected authorised openingBooked interimAvailable forwardAvailable nonInvoiced].each do |type|
value = balances[type]
if value
balance = value

View file

@ -10,66 +10,68 @@ module DateTimeAttributeValidate
super
attributes.each do |attribute|
validate -> { self.send("#{attribute}_datetime_value_valid") }
validate -> { send("#{attribute}_datetime_value_valid") }
# allow resetting the field to nil
before_validation do
if self.instance_variable_get("@#{attribute}_is_set")
date = self.instance_variable_get("@#{attribute}_date_value")
time = self.instance_variable_get("@#{attribute}_time_value")
if date.blank? && time.blank?
self.send("#{attribute}=", nil)
end
if instance_variable_get("@#{attribute}_is_set")
date = instance_variable_get("@#{attribute}_date_value")
time = instance_variable_get("@#{attribute}_time_value")
send("#{attribute}=", nil) if date.blank? && time.blank?
end
end
# remember old date and time values
define_method("#{attribute}_date_value=") do |val|
self.instance_variable_set("@#{attribute}_is_set", true)
self.instance_variable_set("@#{attribute}_date_value", val)
instance_variable_set("@#{attribute}_is_set", true)
instance_variable_set("@#{attribute}_date_value", val)
begin
self.send("#{attribute}_date=", val)
rescue
send("#{attribute}_date=", val)
rescue StandardError
nil
end
end
define_method("#{attribute}_time_value=") do |val|
self.instance_variable_set("@#{attribute}_is_set", true)
self.instance_variable_set("@#{attribute}_time_value", val)
instance_variable_set("@#{attribute}_is_set", true)
instance_variable_set("@#{attribute}_time_value", val)
begin
self.send("#{attribute}_time=", val)
rescue
send("#{attribute}_time=", val)
rescue StandardError
nil
end
end
# fallback to field when values are not set
define_method("#{attribute}_date_value") do
self.instance_variable_get("@#{attribute}_date_value") || self.send("#{attribute}_date").try { |e| e.strftime('%Y-%m-%d') }
instance_variable_get("@#{attribute}_date_value") || send("#{attribute}_date").try do |e|
e.strftime('%Y-%m-%d')
end
end
define_method("#{attribute}_time_value") do
self.instance_variable_get("@#{attribute}_time_value") || self.send("#{attribute}_time").try { |e| e.strftime('%H:%M') }
instance_variable_get("@#{attribute}_time_value") || send("#{attribute}_time").try do |e|
e.strftime('%H:%M')
end
end
private
# validate date and time
define_method("#{attribute}_datetime_value_valid") do
date = self.instance_variable_get("@#{attribute}_date_value")
date = instance_variable_get("@#{attribute}_date_value")
unless date.blank? || begin
Date.parse(date)
rescue
rescue StandardError
nil
end
errors.add(attribute, "is not a valid date") # @todo I18n
errors.add(attribute, 'is not a valid date') # @todo I18n
end
time = self.instance_variable_get("@#{attribute}_time_value")
time = instance_variable_get("@#{attribute}_time_value")
unless time.blank? || begin
Time.parse(time)
rescue
rescue StandardError
nil
end
errors.add(attribute, "is not a valid time") # @todo I18n
errors.add(attribute, 'is not a valid time') # @todo I18n
end
end
end

View file

@ -14,7 +14,7 @@ module Foodsoft
cattr_accessor :variables
# Hash of variables. Note that keys are Strings.
@@variables = {
@variables = {
'scope' => -> { FoodsoftConfig.scope },
'name' => -> { FoodsoftConfig[:name] },
'contact.street' => -> { FoodsoftConfig[:contact][:street] },
@ -39,13 +39,13 @@ module Foodsoft
'supplier_count' => -> { Supplier.undeleted.count },
'active_supplier_count' => -> { active_supplier_count },
'active_suppliers' => -> { active_suppliers },
'first_order_date' => -> { I18n.l Order.first.try { |o| o.starts.to_date } }
'first_order_date' => -> { I18n.l(Order.first.try { |o| o.starts.to_date }) }
}
# Return expanded variable
# @return [String] Expanded variable
def self.get(var)
s = @@variables[var.to_s]
s = @variables[var.to_s]
s.respond_to?(:call) ? s.call : s.to_s
end
@ -55,7 +55,7 @@ module Foodsoft
# @return [String] Expanded string
def self.expand(str, options = {})
str.gsub(/{{([._a-zA-Z0-9]+)}}/) do
options[::Regexp.last_match(1)] || self.get(::Regexp.last_match(1))
options[::Regexp.last_match(1)] || get(::Regexp.last_match(1))
end
end

View file

@ -70,7 +70,7 @@ class FoodsoftConfig
# Load initial config from development or production
set_config Rails.env
# Overwrite scope to have a better namescope than 'production'
self.scope = config[:default_scope] or raise "No default_scope is set"
self.scope = config[:default_scope] or raise 'No default_scope is set'
# Set defaults for backward-compatibility
set_missing
# Make sure relevant configuration is applied, also in single coops mode,
@ -79,7 +79,7 @@ class FoodsoftConfig
end
def init_mailing
[:protocol, :host, :port, :script_name].each do |k|
%i[protocol host port script_name].each do |k|
ActionMailer::Base.default_url_options[k] = self[k] if self[k]
end
end
@ -117,7 +117,7 @@ class FoodsoftConfig
# @return [Object] Value of the key.
def [](key)
if RailsSettings::CachedSettings.table_exists? && allowed_key?(key)
value = RailsSettings::CachedSettings["foodcoop.#{self.scope}.#{key}"]
value = RailsSettings::CachedSettings["foodcoop.#{scope}.#{key}"]
value = config[key] if value.nil?
value
else
@ -139,20 +139,20 @@ class FoodsoftConfig
if config[key] == value || (config[key].nil? && value == false)
# delete (ok if it was already deleted)
begin
RailsSettings::CachedSettings.destroy "foodcoop.#{self.scope}.#{key}"
RailsSettings::CachedSettings.destroy "foodcoop.#{scope}.#{key}"
rescue RailsSettings::Settings::SettingNotFound
end
else
# or store
RailsSettings::CachedSettings["foodcoop.#{self.scope}.#{key}"] = value
RailsSettings::CachedSettings["foodcoop.#{scope}.#{key}"] = value
end
true
end
# @return [Array<String>] Configuration keys that are set (either in +app_config.yml+ or database).
def keys
keys = RailsSettings::CachedSettings.get_all("foodcoop.#{self.scope}.").try(:keys) || []
keys.map! { |k| k.gsub(/^foodcoop\.#{self.scope}\./, '') }
keys = RailsSettings::CachedSettings.get_all("foodcoop.#{scope}.").try(:keys) || []
keys.map! { |k| k.gsub(/^foodcoop\.#{scope}\./, '') }
keys += config.keys
keys.map(&:to_s).uniq
end
@ -181,10 +181,10 @@ class FoodsoftConfig
# @return [Boolean] Whether this key may be set in the database
def allowed_key?(key)
# fast check for keys without nesting
if self.config[:protected].include? key
!self.config[:protected][key]
if config[:protected].include? key
!config[:protected][key]
else
!self.config[:protected][:all]
!config[:protected][:all]
end
# @todo allow to check nested keys as well
end
@ -287,7 +287,9 @@ class FoodsoftConfig
def normalize_value(value)
value = value.map { |v| normalize_value(v) } if value.is_a? Array
if value.is_a? Hash
value = ActiveSupport::HashWithIndifferentAccess[value.to_a.map { |a| [a[0], normalize_value(a[1])] }]
value = ActiveSupport::HashWithIndifferentAccess[value.to_a.map do |a|
[a[0], normalize_value(a[1])]
end]
end
case value
when 'true' then true

View file

@ -8,26 +8,24 @@ module FoodsoftDateUtil
# @todo handle ical parse errors
occ = begin
schedule.next_occurrence(from).to_time
rescue
rescue StandardError
nil
end
end
if options && options[:time] && occ
occ = occ.beginning_of_day.advance(seconds: Time.parse(options[:time]).seconds_since_midnight)
end
occ = occ.beginning_of_day.advance(seconds: Time.parse(options[:time]).seconds_since_midnight) if options && options[:time] && occ
occ
end
# @param p [String, Symbol, Hash, IceCube::Rule] What to return a rule from.
# @param rule [String, Symbol, Hash, IceCube::Rule] What to return a rule from.
# @return [IceCube::Rule] Recurring rule
def self.rule_from(p)
case p
def self.rule_from(rule)
case rule
when String
IceCube::Rule.from_ical(p)
IceCube::Rule.from_ical(rule)
when Hash
IceCube::Rule.from_hash(p)
IceCube::Rule.from_hash(rule)
else
p
rule
end
end
end

View file

@ -7,17 +7,17 @@ class FoodsoftFile
SpreadsheetFile.parse file, options do |row, row_index|
next if row[2].blank?
article = { :order_number => row[1],
:name => row[2],
:note => row[3],
:manufacturer => row[4],
:origin => row[5],
:unit => row[6],
:price => row[7],
:tax => row[8],
:deposit => (row[9].nil? ? "0" : row[9]),
:unit_quantity => row[10],
:article_category => row[13] }
article = { order_number: row[1],
name: row[2],
note: row[3],
manufacturer: row[4],
origin: row[5],
unit: row[6],
price: row[7],
tax: row[8],
deposit: (row[9].nil? ? '0' : row[9]),
unit_quantity: row[10],
article_category: row[13] }
status = row[0] && row[0].strip.downcase == 'x' ? :outlisted : nil
yield status, article, row_index
end

View file

@ -23,8 +23,8 @@ class FoodsoftMailReceiver < MidiSmtpServer::Smtpd
recipient = rcpt_to.gsub(/^\s*<\s*(.*)\s*>\s*$/, '\1')
@handlers << self.class.find_handler(recipient)
rcpt_to
rescue => error
logger.info("Can not accept mail for '#{rcpt_to}': #{error}")
rescue StandardError => e
logger.info("Can not accept mail for '#{rcpt_to}': #{e}")
raise MidiSmtpServer::Smtpd550Exception
end
@ -32,16 +32,16 @@ class FoodsoftMailReceiver < MidiSmtpServer::Smtpd
@handlers.each do |handler|
handler.call(ctx[:message][:data])
end
rescue => error
ExceptionNotifier.notify_exception(error, data: ctx)
raise error
rescue StandardError => e
ExceptionNotifier.notify_exception(e, data: ctx)
raise e
ensure
@handlers.clear
end
def self.find_handler(recipient)
m = /(?<foodcoop>[^@.]+)\.(?<address>[^@]+)(@(?<hostname>[^@]+))?/.match recipient
raise "recipient is missing or has an invalid format" if m.nil?
raise 'recipient is missing or has an invalid format' if m.nil?
raise "Foodcoop '#{m[:foodcoop]}' could not be found" unless FoodsoftConfig.allowed_foodcoop? m[:foodcoop]
FoodsoftConfig.select_multifoodcoop m[:foodcoop]
@ -53,6 +53,6 @@ class FoodsoftMailReceiver < MidiSmtpServer::Smtpd
end
end
raise "invalid format for recipient"
raise 'invalid format for recipient'
end
end

View file

@ -14,7 +14,7 @@ class OrderCsv < RenderCsv
end
def data
@object.order_articles.ordered.includes([:article, :article_price]).all.map do |oa|
@object.order_articles.ordered.includes(%i[article article_price]).all.map do |oa|
yield [
oa.units_to_order,
oa.article.order_number,

View file

@ -55,7 +55,7 @@ class OrderPdf < RenderPdf
end
def group_order_article_quantity_with_tolerance(goa)
goa.tolerance > 0 ? "#{goa.quantity} + #{goa.tolerance}" : "#{goa.quantity}"
goa.tolerance > 0 ? "#{goa.quantity} + #{goa.tolerance}" : goa.quantity.to_s
end
def group_order_article_result(goa)
@ -88,7 +88,7 @@ class OrderPdf < RenderPdf
.pluck('groups.name', 'SUM(group_orders.price)', 'ordergroup_id', 'SUM(group_orders.transport)')
result.map do |item|
[item.first || stock_ordergroup_name] + item[1..-1]
[item.first || stock_ordergroup_name] + item[1..]
end
end
@ -103,7 +103,7 @@ class OrderPdf < RenderPdf
def each_ordergroup_batch(batch_size)
offset = 0
while true
loop do
go_records = ordergroups(offset, batch_size)
break unless go_records.any?
@ -136,7 +136,7 @@ class OrderPdf < RenderPdf
group_order_articles(ordergroup)
.includes(order_article: { article: [:supplier] })
.order('suppliers.name, articles.name')
.preload(order_article: [:article_price, :order])
.preload(order_article: %i[article_price order])
.each(&block)
end

View file

@ -8,23 +8,19 @@ class OrderTxt
def to_txt
supplier = @order.supplier
contact = FoodsoftConfig[:contact].symbolize_keys
text = I18n.t('orders.fax.heading', :name => FoodsoftConfig[:name])
text += "\n#{Supplier.human_attribute_name(:customer_number)}: #{supplier.customer_number}" unless supplier.customer_number.blank?
text = I18n.t('orders.fax.heading', name: FoodsoftConfig[:name])
text += "\n#{Supplier.human_attribute_name(:customer_number)}: #{supplier.customer_number}" if supplier.customer_number.present?
text += "\n" + I18n.t('orders.fax.delivery_day')
text += "\n\n#{supplier.name}\n#{supplier.address}\n#{Supplier.human_attribute_name(:fax)}: #{supplier.fax}\n\n"
text += "****** " + I18n.t('orders.fax.to_address') + "\n\n"
text += '****** ' + I18n.t('orders.fax.to_address') + "\n\n"
text += "#{FoodsoftConfig[:name]}\n#{contact[:street]}\n#{contact[:zip_code]} #{contact[:city]}\n\n"
text += "****** " + I18n.t('orders.fax.articles') + "\n\n"
text += format("%8s %8s %s\n", I18n.t('orders.fax.number'), I18n.t('orders.fax.amount'), I18n.t('orders.fax.name'))
text += '****** ' + I18n.t('orders.fax.articles') + "\n\n"
text += format("%8s %8s %s\n", I18n.t('orders.fax.number'), I18n.t('orders.fax.amount'),
I18n.t('orders.fax.name'))
# now display all ordered articles
@order.order_articles.ordered.includes([:article, :article_price]).each do |oa|
@order.order_articles.ordered.includes(%i[article article_price]).each do |oa|
text += format("%8s %8d %s\n", oa.article.order_number, oa.units_to_order.to_i, oa.article.name)
end
text
end
# Helper method to test pdf via rails console: OrderTxt.new(order).save_tmp
def save_tmp
File.write("#{Rails.root}/tmp/#{self.class.to_s.underscore}.txt", to_csv.force_encoding("UTF-8"))
end
end

View file

@ -13,7 +13,7 @@ class RenderCsv
end
def to_csv
options = @options.select { |k| %w(col_sep row_sep).include? k.to_s }
options = @options.select { |k| %w[col_sep row_sep].include? k.to_s }
ret = CSV.generate options do |csv|
if h = header
csv << h
@ -31,12 +31,6 @@ class RenderCsv
yield []
end
# Helper method to test pdf via rails console: OrderCsv.new(order).save_tmp
def save_tmp
encoding = @options[:encoding] || 'UTF-8'
File.write("#{Rails.root}/tmp/#{self.class.to_s.underscore}.csv", to_csv.force_encoding(encoding))
end
# XXX disable unit to avoid encoding problems, both in unit and whitespace. Also allows computations in spreadsheet.
def number_to_currency(number, options = {})
super(number, options.merge({ unit: '' }))

View file

@ -28,9 +28,9 @@ class RotatedCell < Prawn::Table::Cell::Text
with_font { (@pdf.width_of(@content, options) + padding_top + padding_bottom) * tan_rotation }
end
def draw_borders(pt)
def draw_borders(point)
@pdf.mask(:line_width, :stroke_color) do
x, y = pt
x, y = point
from = [[x - skew, y + (border_top_width / 2.0)],
to = [x, y - height - (border_bottom_width / 2.0)]]
@ -118,11 +118,6 @@ class RenderPdf < Prawn::Document
render # Render pdf
end
# Helper method to test pdf via rails console: OrderByGroups.new(order).save_tmp
def save_tmp
File.write("#{Rails.root}/tmp/#{self.class.to_s.underscore}.pdf", to_pdf.force_encoding("UTF-8"))
end
# @todo avoid underscore instead of unicode whitespace in pdf :/
def number_to_currency(number, options = {})
super(number, options).gsub("\u202f", ' ') if number
@ -148,8 +143,8 @@ class RenderPdf < Prawn::Document
protected
def fontsize(n)
n
def fontsize(size)
size
end
# return whether pagebreak or vertical whitespace is used for breaks

View file

@ -19,9 +19,9 @@ class TokenVerifier < ActiveSupport::MessageVerifier
raise InvalidPrefix unless r[1] == @_prefix
# return original message
if r.length > 2
r[2]
end
return unless r.length > 2
r[2]
end
class InvalidMessage < ActiveSupport::MessageVerifier::InvalidSignature; end