From 757f0ac9bddaf348a6929bcf7d43d1180ea106f4 Mon Sep 17 00:00:00 2001 From: Thorsten Eckel Date: Sun, 1 Oct 2017 14:25:52 +0200 Subject: [PATCH 1/3] Applied RuboCop Style/BlockDelimiters to improve readability. --- .rubocop.yml | 8 - .../application_controller/handles_errors.rb | 4 +- .../logs_http_access.rb | 8 +- .../application_controller/renders_models.rb | 12 +- app/controllers/applications_controller.rb | 4 +- app/controllers/calendars_controller.rb | 4 +- app/controllers/channels_email_controller.rb | 20 +- .../channels_facebook_controller.rb | 8 +- .../channels_telegram_controller.rb | 4 +- .../channels_twitter_controller.rb | 8 +- app/controllers/chats_controller.rb | 4 +- .../concerns/creates_ticket_articles.rb | 16 +- app/controllers/concerns/ticket_stats.rb | 4 +- app/controllers/first_steps_controller.rb | 8 +- app/controllers/form_controller.rb | 4 +- app/controllers/getting_started_controller.rb | 4 +- app/controllers/import_otrs_controller.rb | 12 +- app/controllers/import_zendesk_controller.rb | 4 +- .../integration/check_mk_controller.rb | 12 +- .../integration/sipgate_controller.rb | 8 +- app/controllers/links_controller.rb | 4 +- app/controllers/long_polling_controller.rb | 8 +- app/controllers/monitoring_controller.rb | 24 +- app/controllers/organizations_controller.rb | 28 +-- app/controllers/reports_controller.rb | 12 +- app/controllers/search_controller.rb | 32 +-- app/controllers/sessions/collection_base.rb | 20 +- app/controllers/sessions/collection_ticket.rb | 32 +-- app/controllers/sessions_controller.rb | 8 +- app/controllers/settings_controller.rb | 12 +- app/controllers/slas_controller.rb | 8 +- app/controllers/tags_controller.rb | 8 +- app/controllers/ticket_articles_controller.rb | 16 +- .../ticket_overviews_controller.rb | 12 +- app/controllers/tickets_controller.rb | 60 ++--- .../time_accountings_controller.rb | 60 ++--- .../user_access_token_controller.rb | 16 +- app/controllers/user_devices_controller.rb | 8 +- app/controllers/users_controller.rb | 48 ++-- app/models/application_model/can_assets.rb | 16 +- .../application_model/can_associations.rb | 56 ++--- .../application_model/can_cleanup_param.rb | 16 +- .../can_creates_and_updates.rb | 32 +-- app/models/application_model/can_lookup.rb | 12 +- .../can_lookup_search_index_attributes.rb | 8 +- .../checks_attribute_values_and_length.rb | 4 +- app/models/application_model/has_cache.rb | 4 +- app/models/calendar.rb | 32 +-- app/models/channel.rb | 12 +- app/models/channel/assets.rb | 8 +- app/models/channel/driver/facebook.rb | 16 +- app/models/channel/driver/twitter.rb | 44 ++-- app/models/channel/email_parser.rb | 72 +++--- .../bounce_delivery_permanent_failed.rb | 20 +- .../channel/filter/bounce_follow_up_check.rb | 4 +- app/models/channel/filter/database.rb | 12 +- app/models/channel/filter/follow_up_check.rb | 12 +- app/models/channel/filter/follow_up_merged.rb | 4 +- app/models/channel/filter/identify_sender.rb | 20 +- app/models/channel/filter/monitoring_base.rb | 12 +- .../filter/sender_is_system_address.rb | 4 +- app/models/channel/filter/trusted.rb | 8 +- app/models/chat.rb | 48 ++-- app/models/chat/session.rb | 24 +- app/models/concerns/can_uniq_name.rb | 4 +- .../concerns/has_activity_stream_log.rb | 4 +- app/models/concerns/has_history.rb | 12 +- .../concerns/has_search_index_backend.rb | 8 +- app/models/cti/caller_id.rb | 28 +-- app/models/cti/log.rb | 20 +- app/models/email_address.rb | 8 +- app/models/external_sync.rb | 8 +- app/models/job/assets.rb | 4 +- app/models/karma/activity_log.rb | 4 +- app/models/karma/user.rb | 4 +- app/models/link.rb | 8 +- app/models/locale.rb | 4 +- app/models/object_manager/attribute.rb | 44 ++-- .../observer/organization/ref_object_touch.rb | 8 +- .../observer/sla/ticket_rebuild_escalation.rb | 4 +- .../communicate_email/background_job.rb | 8 +- .../communicate_telegram/background_job.rb | 4 +- .../communicate_twitter/background_job.rb | 4 +- .../background_job.rb | 4 +- app/models/observer/transaction.rb | 28 +-- app/models/observer/user/geo.rb | 12 +- app/models/observer/user/ref_object_touch.rb | 4 +- .../observer/user/ticket_organization.rb | 4 +- app/models/online_notification.rb | 16 +- app/models/organization/assets.rb | 8 +- app/models/organization/search.rb | 12 +- app/models/organization/search_index.rb | 4 +- app/models/overview/assets.rb | 8 +- app/models/package.rb | 36 +-- app/models/permission.rb | 4 +- app/models/postmaster_filter.rb | 4 +- app/models/recent_view.rb | 4 +- app/models/report.rb | 8 +- app/models/role.rb | 20 +- app/models/role/assets.rb | 8 +- app/models/scheduler.rb | 12 +- app/models/setting.rb | 12 +- app/models/sla/assets.rb | 4 +- app/models/store.rb | 4 +- app/models/store/file.rb | 8 +- app/models/store/provider/file.rb | 16 +- app/models/tag.rb | 16 +- app/models/taskbar.rb | 20 +- app/models/text_module.rb | 8 +- app/models/ticket.rb | 76 +++--- app/models/ticket/article.rb | 32 +-- app/models/ticket/article/assets.rb | 4 +- app/models/ticket/assets.rb | 4 +- app/models/ticket/escalation.rb | 32 +-- app/models/ticket/number.rb | 4 +- app/models/ticket/number/date.rb | 8 +- app/models/ticket/number/increment.rb | 12 +- app/models/ticket/overviews.rb | 16 +- app/models/ticket/priority.rb | 4 +- app/models/ticket/screen_options.rb | 8 +- app/models/ticket/search.rb | 16 +- app/models/ticket/search_index.rb | 12 +- app/models/ticket/state.rb | 4 +- app/models/ticket/time_accounting.rb | 4 +- app/models/token.rb | 8 +- app/models/transaction/background_job.rb | 4 +- app/models/transaction/karma.rb | 8 +- app/models/transaction/notification.rb | 20 +- app/models/transaction/slack.rb | 20 +- app/models/transaction/trigger.rb | 4 +- app/models/translation.rb | 60 ++--- app/models/user.rb | 68 +++--- app/models/user/assets.rb | 16 +- app/models/user/search.rb | 4 +- app/models/user/search_index.rb | 4 +- app/models/user_device.rb | 8 +- config/initializers/core_ext.rb | 4 +- config/initializers/vendor_lib.rb | 4 +- config/routes.rb | 4 +- contrib/packager.io/fetch_locales.rb | 4 +- .../20150979000001_update_timestamps.rb | 4 +- ..._object_manager_attribute_create_middle.rb | 4 +- db/migrate/20170116000002_fixed_typos_622.rb | 4 +- .../20170123000002_fixed_translation.rb | 4 +- .../20170314000001_fixed_translation2.rb | 4 +- ...3000001_fixed_admin_user_permission_920.rb | 12 +- .../20170419000002_overview_role_ids.rb | 4 +- ...20170516000001_trigger_recipient_update.rb | 4 +- ...822000001_agend_based_sender_issue_1351.rb | 4 +- .../20170830000001_last_owner_update.rb | 8 +- db/seeds/settings.rb | 4 +- lib/auto_wizard.rb | 24 +- lib/calendar_subscriptions.rb | 8 +- .../postgresql/schema_statements.rb | 4 +- lib/core_ext/string.rb | 56 ++--- lib/email_helper.rb | 12 +- lib/email_helper/probe.rb | 28 +-- lib/email_helper/verify.rb | 4 +- lib/enrichment/clearbit/user.rb | 4 +- lib/external_credential/facebook.rb | 8 +- lib/external_credential/twitter.rb | 4 +- lib/facebook.rb | 24 +- lib/fill_db.rb | 24 +- lib/html_sanitizer.rb | 36 +-- lib/idoit.rb | 4 +- lib/import/helper.rb | 4 +- lib/import/otrs.rb | 12 +- lib/import/otrs/async.rb | 4 +- lib/import/otrs/helper.rb | 4 +- lib/import/otrs/import_stats.rb | 4 +- lib/import/otrs/state_factory.rb | 4 +- lib/import/otrs/ticket.rb | 12 +- lib/import/otrs/user.rb | 16 +- lib/import/zendesk/async.rb | 4 +- lib/import/zendesk/helper.rb | 4 +- lib/import/zendesk/import_stats.rb | 4 +- lib/import/zendesk/object_attribute/select.rb | 4 +- lib/import/zendesk/ticket_factory.rb | 4 +- lib/import/zendesk/user/group.rb | 8 +- lib/ldap/group.rb | 4 +- lib/ldap/user.rb | 4 +- lib/mixin/instance_wrapper.rb | 4 +- lib/models.rb | 48 ++-- lib/notification_factory/mailer.rb | 8 +- lib/notification_factory/renderer.rb | 4 +- lib/push_messages.rb | 4 +- lib/report/article_by_type_sender.rb | 4 +- lib/report/base.rb | 24 +- lib/report/ticket_backlog.rb | 4 +- lib/report/ticket_first_solution.rb | 12 +- lib/report/ticket_generic_time.rb | 12 +- lib/report/ticket_moved.rb | 8 +- lib/report/ticket_reopened.rb | 16 +- lib/search_index_backend.rb | 16 +- lib/session_helper.rb | 8 +- lib/sessions.rb | 80 +++---- lib/sessions/backend/collections.rb | 8 +- lib/sessions/backend/collections/base.rb | 8 +- lib/sessions/backend/ticket_overview_list.rb | 12 +- lib/sessions/client.rb | 8 +- lib/sessions/event/base.rb | 4 +- lib/sessions/event/broadcast.rb | 8 +- lib/sessions/event/chat_status_agent.rb | 4 +- lib/sessions/event/spool.rb | 4 +- lib/signature_detection.rb | 32 +-- lib/sso.rb | 8 +- lib/stats.rb | 32 +-- lib/stats/ticket_channel_distribution.rb | 12 +- lib/stats/ticket_response_time.rb | 4 +- lib/stats/ticket_waiting_time.rb | 8 +- lib/telegram.rb | 28 +-- lib/tweet_base.rb | 20 +- lib/user_agent.rb | 8 +- script/websocket-server.rb | 56 ++--- spec/lib/import/base_resource_spec.rb | 8 +- spec/lib/import/model_resource_spec.rb | 4 +- .../otrs/article/attachment_factory_spec.rb | 8 +- spec/lib/import/otrs/article_spec.rb | 16 +- spec/lib/import/otrs/customer_spec.rb | 9 +- spec/lib/import/otrs/customer_user_spec.rb | 15 +- spec/lib/import/otrs/dynamic_field_spec.rb | 4 +- spec/lib/import/otrs/history_spec.rb | 4 +- spec/lib/import/otrs/priority_spec.rb | 4 +- spec/lib/import/otrs/queue_spec.rb | 4 +- spec/lib/import/otrs/requester_spec.rb | 4 +- spec/lib/import/otrs/state_factory_spec.rb | 12 +- spec/lib/import/otrs/state_spec.rb | 4 +- spec/lib/import/otrs/ticket_spec.rb | 12 +- spec/lib/import/otrs/user_spec.rb | 12 +- spec/lib/import/statistical_factory_spec.rb | 4 +- spec/lib/ldap/group_spec.rb | 12 +- spec/lib/ldap/user_spec.rb | 16 +- .../unit/common/attribute_mapper_spec.rb | 4 +- spec/models/concerns/has_groups_examples.rb | 4 +- spec/models/concerns/has_roles_examples.rb | 4 +- spec/models/ticket_spec.rb | 8 +- spec/models/translation_spec.rb | 16 +- spec/models/user_spec.rb | 12 +- test/browser/aaa_getting_started_test.rb | 16 +- test/browser/first_steps_test.rb | 4 +- test/browser/keyboard_shortcuts_test.rb | 8 +- test/browser_test_helper.rb | 216 +++++++++--------- test/controllers/form_controller_test.rb | 8 +- .../controllers/monitoring_controller_test.rb | 8 +- test/controllers/settings_controller_test.rb | 8 +- test/controllers/tickets_controller_test.rb | 4 +- test/fixtures/seeds.rb | 4 +- test/integration/auto_wizard_test.rb | 48 ++-- .../calendar_subscriptions_tickets_test.rb | 28 +-- test/integration/email_deliver_test.rb | 20 +- test/integration/facebook_test.rb | 8 +- test/integration/otrs_import_test.rb | 6 +- test/integration/slack_test.rb | 8 +- test/integration/telegram_controller_test.rb | 16 +- test/integration/twitter_browser_test.rb | 4 +- test/integration/twitter_test.rb | 92 ++++---- test/integration/zendesk_import_test.rb | 40 ++-- test/test_helper.rb | 12 +- test/unit/assets_test.rb | 4 +- test/unit/auth_test.rb | 8 +- test/unit/email_build_test.rb | 8 +- test/unit/history_test.rb | 20 +- test/unit/model_test.rb | 8 +- ...object_create_update_with_ref_name_test.rb | 4 +- test/unit/object_manager_test.rb | 52 ++--- test/unit/online_notifiaction_test.rb | 4 +- .../organization_ref_object_touch_test.rb | 4 +- test/unit/package_test.rb | 8 +- test/unit/role_test.rb | 12 +- test/unit/role_validate_agent_limit_test.rb | 4 +- test/unit/session_collections_test.rb | 12 +- test/unit/session_enhanced_test.rb | 20 +- test/unit/store_test.rb | 12 +- test/unit/tag_test.rb | 12 +- test/unit/ticket_test.rb | 4 +- test/unit/ticket_trigger_test.rb | 4 +- test/unit/user_out_of_office_test.rb | 24 +- test/unit/user_ref_object_touch_test.rb | 4 +- test/unit/user_test.rb | 40 ++-- test/unit/user_validate_agent_limit_test.rb | 8 +- 280 files changed, 1979 insertions(+), 1983 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index 1f7ed20d9..f9156d529 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -99,14 +99,6 @@ Style/EmptyLinesAroundModuleBody: Description: "Keeps track of empty lines around module bodies." Enabled: false -Style/BlockDelimiters: - Description: >- - Avoid using {...} for multi-line blocks (multiline chaining is - always ugly). - Prefer {...} over do...end for single-line blocks. - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#single-line-blocks' - Enabled: false - Style/MultilineBlockChain: Description: 'Avoid multi-line chains of blocks.' StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#single-line-blocks' diff --git a/app/controllers/application_controller/handles_errors.rb b/app/controllers/application_controller/handles_errors.rb index 5ada95335..1ec299704 100644 --- a/app/controllers/application_controller/handles_errors.rb +++ b/app/controllers/application_controller/handles_errors.rb @@ -44,12 +44,12 @@ module ApplicationController::HandlesErrors respond_to do |format| format.json { render json: humanize_error(e.message), status: status } - format.any { + format.any do @exception = e @traceback = !Rails.env.production? file = File.open(Rails.root.join('public', "#{status_code}.html"), 'r') render inline: file.read, status: status - } + end end end diff --git a/app/controllers/application_controller/logs_http_access.rb b/app/controllers/application_controller/logs_http_access.rb index ef49c2f3c..fe783693c 100644 --- a/app/controllers/application_controller/logs_http_access.rb +++ b/app/controllers/application_controller/logs_http_access.rb @@ -22,14 +22,14 @@ module ApplicationController::LogsHttpAccess content_encoding: request.headers['Content-Encoding'], source: request.headers['User-Agent'] || request.headers['Server'], } - request.headers.each { |key, value| + request.headers.each do |key, value| next if key[0, 5] != 'HTTP_' request_data[:content] += if key == 'HTTP_COOKIE' "#{key}: xxxxx\n" else "#{key}: #{value}\n" end - } + end body = request.body.read if body request_data[:content] += "\n" + body @@ -44,9 +44,9 @@ module ApplicationController::LogsHttpAccess content_encoding: nil, source: nil, } - response.headers.each { |key, value| + response.headers.each do |key, value| response_data[:content] += "#{key}: #{value}\n" - } + end body = response.body if body response_data[:content] += "\n" + body diff --git a/app/controllers/application_controller/renders_models.rb b/app/controllers/application_controller/renders_models.rb index bedadcb79..a4eb681d1 100644 --- a/app/controllers/application_controller/renders_models.rb +++ b/app/controllers/application_controller/renders_models.rb @@ -111,9 +111,9 @@ module ApplicationController::RendersModels if params[:expand] list = [] - generic_objects.each { |generic_object| + generic_objects.each do |generic_object| list.push generic_object.attributes_with_association_names - } + end render json: list, status: :ok return end @@ -121,10 +121,10 @@ module ApplicationController::RendersModels if params[:full] assets = {} item_ids = [] - generic_objects.each { |item| + generic_objects.each do |item| item_ids.push item.id assets = item.assets(assets) - } + end render json: { record_ids: item_ids, assets: assets, @@ -133,9 +133,9 @@ module ApplicationController::RendersModels end generic_objects_with_associations = [] - generic_objects.each { |item| + generic_objects.each do |item| generic_objects_with_associations.push item.attributes_with_association_ids - } + end model_index_render_result(generic_objects_with_associations) end diff --git a/app/controllers/applications_controller.rb b/app/controllers/applications_controller.rb index fd1744156..6cf408d1b 100644 --- a/app/controllers/applications_controller.rb +++ b/app/controllers/applications_controller.rb @@ -8,7 +8,7 @@ class ApplicationsController < ApplicationController if params[:full] assets = {} item_ids = [] - all.each { |item| + all.each do |item| item_ids.push item.id if !assets[:Application] assets[:Application] = {} @@ -16,7 +16,7 @@ class ApplicationsController < ApplicationController application = item.attributes application[:clients] = Doorkeeper::AccessToken.where(application_id: item.id).count assets[:Application][item.id] = application - } + end render json: { record_ids: item_ids, assets: assets, diff --git a/app/controllers/calendars_controller.rb b/app/controllers/calendars_controller.rb index d2169fae8..75ca96bb3 100644 --- a/app/controllers/calendars_controller.rb +++ b/app/controllers/calendars_controller.rb @@ -8,10 +8,10 @@ class CalendarsController < ApplicationController # calendars assets = {} calendar_ids = [] - Calendar.all.order(:name, :created_at).each { |calendar| + Calendar.all.order(:name, :created_at).each do |calendar| calendar_ids.push calendar.id assets = calendar.assets(assets) - } + end ical_feeds = Calendar.ical_feeds timezones = Calendar.timezones diff --git a/app/controllers/channels_email_controller.rb b/app/controllers/channels_email_controller.rb index 4f3b1ccec..633d13dfb 100644 --- a/app/controllers/channels_email_controller.rb +++ b/app/controllers/channels_email_controller.rb @@ -11,12 +11,12 @@ class ChannelsEmailController < ApplicationController not_used_email_address_ids = [] accounts_fixed = [] assets = {} - Channel.order(:id).each { |channel| + Channel.order(:id).each do |channel| if system_online_service && channel.preferences && channel.preferences['online_service_disable'] email_addresses = EmailAddress.where(channel_id: channel.id) - email_addresses.each { |email_address| + email_addresses.each do |email_address| accounts_fixed.push email_address - } + end next end if channel.area == 'Email::Account' @@ -26,15 +26,15 @@ class ChannelsEmailController < ApplicationController notification_channel_ids.push channel.id assets = channel.assets(assets) end - } - EmailAddress.all.each { |email_address| + end + EmailAddress.all.each do |email_address| next if system_online_service && email_address.preferences && email_address.preferences['online_service_disable'] email_address_ids.push email_address.id assets = email_address.assets(assets) if !email_address.channel_id || !email_address.active || !Channel.find_by(id: email_address.channel_id) not_used_email_address_ids.push email_address.id end - } + end render json: { accounts_fixed: accounts_fixed, assets: assets, @@ -224,7 +224,7 @@ class ChannelsEmailController < ApplicationController # save settings if result[:result] == 'ok' - Channel.where(area: 'Email::Notification').each { |channel| + Channel.where(area: 'Email::Notification').each do |channel| active = false if adapter =~ /^#{channel.options[:outbound][:adapter]}$/i active = true @@ -239,7 +239,7 @@ class ChannelsEmailController < ApplicationController end channel.active = active channel.save - } + end end render json: result end @@ -247,7 +247,7 @@ class ChannelsEmailController < ApplicationController private def account_duplicate?(result, channel_id = nil) - Channel.where(area: 'Email::Account').each { |channel| + Channel.where(area: 'Email::Account').each do |channel| next if !channel.options next if !channel.options[:inbound] next if !channel.options[:inbound][:adapter] @@ -261,7 +261,7 @@ class ChannelsEmailController < ApplicationController message: 'Account already exists!', } return true - } + end false end diff --git a/app/controllers/channels_facebook_controller.rb b/app/controllers/channels_facebook_controller.rb index c0596598a..0b92602fb 100644 --- a/app/controllers/channels_facebook_controller.rb +++ b/app/controllers/channels_facebook_controller.rb @@ -5,14 +5,14 @@ class ChannelsFacebookController < ApplicationController def index assets = {} - ExternalCredential.where(name: 'facebook').each { |external_credential| + ExternalCredential.where(name: 'facebook').each do |external_credential| assets = external_credential.assets(assets) - } + end channel_ids = [] - Channel.where(area: 'Facebook::Account').order(:id).each { |channel| + Channel.where(area: 'Facebook::Account').order(:id).each do |channel| assets = channel.assets(assets) channel_ids.push channel.id - } + end render json: { assets: assets, channel_ids: channel_ids, diff --git a/app/controllers/channels_telegram_controller.rb b/app/controllers/channels_telegram_controller.rb index 639201767..dbc6834f5 100644 --- a/app/controllers/channels_telegram_controller.rb +++ b/app/controllers/channels_telegram_controller.rb @@ -7,10 +7,10 @@ class ChannelsTelegramController < ApplicationController def index assets = {} channel_ids = [] - Channel.where(area: 'Telegram::Bot').order(:id).each { |channel| + Channel.where(area: 'Telegram::Bot').order(:id).each do |channel| assets = channel.assets(assets) channel_ids.push channel.id - } + end render json: { assets: assets, channel_ids: channel_ids diff --git a/app/controllers/channels_twitter_controller.rb b/app/controllers/channels_twitter_controller.rb index e2fe2a821..e93966704 100644 --- a/app/controllers/channels_twitter_controller.rb +++ b/app/controllers/channels_twitter_controller.rb @@ -5,14 +5,14 @@ class ChannelsTwitterController < ApplicationController def index assets = {} - ExternalCredential.where(name: 'twitter').each { |external_credential| + ExternalCredential.where(name: 'twitter').each do |external_credential| assets = external_credential.assets(assets) - } + end channel_ids = [] - Channel.where(area: 'Twitter::Account').order(:id).each { |channel| + Channel.where(area: 'Twitter::Account').order(:id).each do |channel| assets = channel.assets(assets) channel_ids.push channel.id - } + end render json: { assets: assets, channel_ids: channel_ids, diff --git a/app/controllers/chats_controller.rb b/app/controllers/chats_controller.rb index d2f0e5315..20b61d3e7 100644 --- a/app/controllers/chats_controller.rb +++ b/app/controllers/chats_controller.rb @@ -6,10 +6,10 @@ class ChatsController < ApplicationController def index chat_ids = [] assets = {} - Chat.order(:id).each { |chat| + Chat.order(:id).each do |chat| chat_ids.push chat.id assets = chat.assets(assets) - } + end setting = Setting.find_by(name: 'chat') assets = setting.assets(assets) render json: { diff --git a/app/controllers/concerns/creates_ticket_articles.rb b/app/controllers/concerns/creates_ticket_articles.rb index b3c662c2e..1569a7436 100644 --- a/app/controllers/concerns/creates_ticket_articles.rb +++ b/app/controllers/concerns/creates_ticket_articles.rb @@ -62,7 +62,7 @@ module CreatesTicketArticles article.save! # store inline attachments - attachments_inline.each { |attachment| + attachments_inline.each do |attachment| Store.add( object: 'Ticket::Article', o_id: article.id, @@ -70,24 +70,24 @@ module CreatesTicketArticles filename: attachment[:filename], preferences: attachment[:preferences], ) - } + end # add attachments as param if params[:attachments].present? - params[:attachments].each_with_index { |attachment, index| + params[:attachments].each_with_index do |attachment, index| # validation - ['mime-type', 'filename', 'data'].each { |key| + ['mime-type', 'filename', 'data'].each do |key| next if attachment[key] raise Exceptions::UnprocessableEntity, "Attachment needs '#{key}' param for attachment with index '#{index}'" - } + end preferences = {} - ['charset', 'mime-type'].each { |key| + ['charset', 'mime-type'].each do |key| next if !attachment[key] store_key = key.tr('-', '_').camelize.gsub(/(.+)([A-Z])/, '\1_\2').tr('_', '-') preferences[store_key] = attachment[key] - } + end if attachment[:data] !~ %r{^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$} raise Exceptions::UnprocessableEntity, "Invalid base64 for attachment with index '#{index}'" @@ -100,7 +100,7 @@ module CreatesTicketArticles filename: attachment[:filename], preferences: preferences, ) - } + end end # account time diff --git a/app/controllers/concerns/ticket_stats.rb b/app/controllers/concerns/ticket_stats.rb index 4060dfbf3..ddb07c82b 100644 --- a/app/controllers/concerns/ticket_stats.rb +++ b/app/controllers/concerns/ticket_stats.rb @@ -16,7 +16,7 @@ module TicketStats volume_by_year = [] now = Time.zone.now - (0..11).each { |month_back| + (0..11).each do |month_back| date_to_check = now - month_back.month date_start = "#{date_to_check.year}-#{date_to_check.month}-01 00:00:00" date_end = "#{date_to_check.year}-#{date_to_check.month}-#{date_to_check.end_of_month.day} 00:00:00" @@ -41,7 +41,7 @@ module TicketStats closed: closed, } volume_by_year.push data - } + end volume_by_year end diff --git a/app/controllers/first_steps_controller.rb b/app/controllers/first_steps_controller.rb index e6641e272..096879693 100644 --- a/app/controllers/first_steps_controller.rb +++ b/app/controllers/first_steps_controller.rb @@ -243,14 +243,14 @@ class FirstStepsController < ApplicationController test_ticket_active = false end return result if test_ticket_active - result.each { |item| + result.each do |item| items = [] - item[:items].each { |local_item| + item[:items].each do |local_item| next if local_item[:name] == 'Create a Test Ticket' items.push local_item - } + end item[:items] = items - } + end result end diff --git a/app/controllers/form_controller.rb b/app/controllers/form_controller.rb index 9e1328748..16740d90b 100644 --- a/app/controllers/form_controller.rb +++ b/app/controllers/form_controller.rb @@ -128,7 +128,7 @@ class FormController < ApplicationController if params[:file] - params[:file].each { |file| + params[:file].each do |file| Store.add( object: 'Ticket::Article', o_id: article.id, @@ -138,7 +138,7 @@ class FormController < ApplicationController 'Mime-Type' => file.content_type, } ) - } + end end UserInfo.current_user_id = 1 diff --git a/app/controllers/getting_started_controller.rb b/app/controllers/getting_started_controller.rb index 2dcdd646b..c074b928e 100644 --- a/app/controllers/getting_started_controller.rb +++ b/app/controllers/getting_started_controller.rb @@ -174,9 +174,9 @@ curl http://localhost/api/v1/getting_started -v -u #{login}:#{password} end # set changed settings - settings.each { |key, value| + settings.each do |key, value| Setting.set(key, value) - } + end render json: { result: 'ok', diff --git a/app/controllers/import_otrs_controller.rb b/app/controllers/import_otrs_controller.rb index f390ed26c..9177de868 100644 --- a/app/controllers/import_otrs_controller.rb +++ b/app/controllers/import_otrs_controller.rb @@ -25,11 +25,11 @@ class ImportOtrsController < ApplicationController response = UserAgent.request(params[:url]) if !response.success? && response.code.to_s !~ /^40.$/ message_human = '' - translation_map.each { |key, message| + translation_map.each do |key, message| if response.error.to_s =~ /#{Regexp.escape(key)}/i message_human = message end - } + end render json: { result: 'invalid', message_human: message_human, @@ -128,20 +128,20 @@ class ImportOtrsController < ApplicationController # check count of dynamic fields dynamic_field_count = 0 dynamic_fields = Import::OTRS::Requester.load('DynamicField') - dynamic_fields.each { |dynamic_field| + dynamic_fields.each do |dynamic_field| next if dynamic_field['ValidID'].to_i != 1 dynamic_field_count += 1 - } + end if dynamic_field_count > 20 issues.push 'otrsDynamicFields' end # check if process exsists sys_configs = Import::OTRS::Requester.load('SysConfig') - sys_configs.each { |sys_config| + sys_configs.each do |sys_config| next if sys_config['Key'] != 'Process' issues.push 'otrsProcesses' - } + end result = 'ok' if !issues.empty? diff --git a/app/controllers/import_zendesk_controller.rb b/app/controllers/import_zendesk_controller.rb index 62d56093e..2b2f23541 100644 --- a/app/controllers/import_zendesk_controller.rb +++ b/app/controllers/import_zendesk_controller.rb @@ -27,11 +27,11 @@ class ImportZendeskController < ApplicationController if !response.success? message_human = '' - translation_map.each { |key, message| + translation_map.each do |key, message| if response.error.to_s =~ /#{Regexp.escape(key)}/i message_human = message end - } + end render json: { result: 'invalid', message_human: message_human, diff --git a/app/controllers/integration/check_mk_controller.rb b/app/controllers/integration/check_mk_controller.rb index 3d9fb6373..4335af3a6 100644 --- a/app/controllers/integration/check_mk_controller.rb +++ b/app/controllers/integration/check_mk_controller.rb @@ -25,7 +25,7 @@ class Integration::CheckMkController < ApplicationController open_states = Ticket::State.by_category(:open) ticket_ids = Ticket.where(state: open_states).order(created_at: :desc).limit(5000).pluck(:id) ticket_ids_found = [] - ticket_ids.each { |ticket_id| + ticket_ids.each do |ticket_id| ticket = Ticket.find_by(id: ticket_id) next if !ticket next if !ticket.preferences @@ -36,7 +36,7 @@ class Integration::CheckMkController < ApplicationController # found open ticket for service+host ticket_ids_found.push ticket.id - } + end # new ticket, set meta data title = "#{params[:host]} is #{params[:state]}" @@ -51,7 +51,7 @@ UserAgent: #{request.env['HTTP_USER_AGENT']} # add article if params[:state].present? && ticket_ids_found.present? - ticket_ids_found.each { |ticket_id| + ticket_ids_found.each do |ticket_id| ticket = Ticket.find_by(id: ticket_id) next if !ticket article = Ticket::Article.create!( @@ -62,7 +62,7 @@ UserAgent: #{request.env['HTTP_USER_AGENT']} subject: title, internal: false, ) - } + end if (!auto_close && params[:state].match(/#{state_recovery_match}/i)) || !params[:state].match(/#{state_recovery_match}/i) render json: { result: 'ticket already open, added note', @@ -81,12 +81,12 @@ UserAgent: #{request.env['HTTP_USER_AGENT']} return end state = Ticket::State.lookup(id: auto_close_state_id) - ticket_ids_found.each { |ticket_id| + ticket_ids_found.each do |ticket_id| ticket = Ticket.find_by(id: ticket_id) next if !ticket ticket.state_id = auto_close_state_id ticket.save! - } + end render json: { result: "closed tickets with ids #{ticket_ids_found.join(',')}", ticket_ids: ticket_ids_found, diff --git a/app/controllers/integration/sipgate_controller.rb b/app/controllers/integration/sipgate_controller.rb index e311cffab..10545e891 100644 --- a/app/controllers/integration/sipgate_controller.rb +++ b/app/controllers/integration/sipgate_controller.rb @@ -13,7 +13,7 @@ class Integration::SipgateController < ApplicationController block_caller_ids = config_inbound[:block_caller_ids] || [] # check if call need to be blocked - block_caller_ids.each { |item| + block_caller_ids.each do |item| next unless item[:caller_id] == params['from'] xml = Builder::XmlMarkup.new(indent: 2) xml.instruct! @@ -30,7 +30,7 @@ class Integration::SipgateController < ApplicationController end Cti::Log.process(params) return true - } + end end Cti::Log.process(params) @@ -54,7 +54,7 @@ class Integration::SipgateController < ApplicationController to = params[:to] from = nil if to - config_outbound.each { |row| + config_outbound.each do |row| dest = row[:dest].gsub(/\*/, '.+?') next if to !~ /^#{dest}$/ from = row[:caller_id] @@ -62,7 +62,7 @@ class Integration::SipgateController < ApplicationController xml.Dial(callerId: from) { xml.Number(params[:to]) } end break - } + end if !content && default_caller_id from = default_caller_id content = xml.Response(onHangup: url, onAnswer: url) do diff --git a/app/controllers/links_controller.rb b/app/controllers/links_controller.rb index 929e21eb4..2ae8c7e96 100644 --- a/app/controllers/links_controller.rb +++ b/app/controllers/links_controller.rb @@ -12,13 +12,13 @@ class LinksController < ApplicationController assets = {} link_list = [] - links.each { |item| + links.each do |item| link_list.push item if item['link_object'] == 'Ticket' ticket = Ticket.lookup(id: item['link_object_value']) assets = ticket.assets(assets) end - } + end # return result render json: { diff --git a/app/controllers/long_polling_controller.rb b/app/controllers/long_polling_controller.rb index f1ef6554e..1bc6b1937 100644 --- a/app/controllers/long_polling_controller.rb +++ b/app/controllers/long_polling_controller.rb @@ -63,9 +63,9 @@ class LongPollingController < ApplicationController begin # update last ping - 4.times { + 4.times do sleep 0.25 - } + end #sleep 1 Sessions.touch(client_id) @@ -82,9 +82,9 @@ class LongPollingController < ApplicationController render json: queue return end - 8.times { + 8.times do sleep 0.25 - } + end #sleep 2 if count.zero? render json: { event: 'pong' } diff --git a/app/controllers/monitoring_controller.rb b/app/controllers/monitoring_controller.rb index 248e7b1e8..0bdcfd6df 100644 --- a/app/controllers/monitoring_controller.rb +++ b/app/controllers/monitoring_controller.rb @@ -34,15 +34,15 @@ curl http://localhost/api/v1/monitoring/health_check?token=XXX # channel check last_run_tolerance = Time.zone.now - 1.hour - Channel.where(active: true).each { |channel| + Channel.where(active: true).each do |channel| # inbound channel if channel.status_in == 'error' message = "Channel: #{channel.area} in " - %w(host user uid).each { |key| + %w(host user uid).each do |key| next if !channel.options[key] || channel.options[key].empty? message += "key:#{channel.options[key]};" - } + end issues.push "#{message} #{channel.last_log_in}" end if channel.preferences && channel.preferences['last_fetch'] && channel.preferences['last_fetch'] < last_run_tolerance @@ -52,32 +52,32 @@ curl http://localhost/api/v1/monitoring/health_check?token=XXX # outbound channel next if channel.status_out != 'error' message = "Channel: #{channel.area} out " - %w(host user uid).each { |key| + %w(host user uid).each do |key| next if !channel.options[key] || channel.options[key].empty? message += "key:#{channel.options[key]};" - } + end issues.push "#{message} #{channel.last_log_out}" - } + end # unprocessable mail check directory = "#{Rails.root}/tmp/unprocessable_mail" if File.exist?(directory) count = 0 - Dir.glob("#{directory}/*.eml") { |_entry| + Dir.glob("#{directory}/*.eml") do |_entry| count += 1 - } + end if count.nonzero? issues.push "unprocessable mails: #{count}" end end # scheduler check - Scheduler.where(active: true).where.not(last_run: nil).each { |scheduler| + Scheduler.where(active: true).where.not(last_run: nil).each do |scheduler| next if scheduler.period <= 300 next if scheduler.last_run + scheduler.period.seconds > Time.zone.now - 5.minutes issues.push 'scheduler not running' break - } + end if Scheduler.where(active: true, last_run: nil).count == Scheduler.where(active: true).count issues.push 'scheduler not running' end @@ -158,13 +158,13 @@ curl http://localhost/api/v1/monitoring/status?token=XXX tickets: Ticket, ticket_articles: Ticket::Article, } - map.each { |key, class_name| + map.each do |key, class_name| status[:counts][key] = class_name.count last = class_name.last status[:last_created_at][key] = if last last.created_at end - } + end render json: status end diff --git a/app/controllers/organizations_controller.rb b/app/controllers/organizations_controller.rb index 4e3814608..5ba533af3 100644 --- a/app/controllers/organizations_controller.rb +++ b/app/controllers/organizations_controller.rb @@ -71,9 +71,9 @@ curl http://localhost/api/v1/organizations -v -u #{login}:#{password} if params[:expand] list = [] - organizations.each { |organization| + organizations.each do |organization| list.push organization.attributes_with_association_names - } + end render json: list, status: :ok return end @@ -81,10 +81,10 @@ curl http://localhost/api/v1/organizations -v -u #{login}:#{password} if params[:full] assets = {} item_ids = [] - organizations.each { |item| + organizations.each do |item| item_ids.push item.id assets = item.assets(assets) - } + end render json: { record_ids: item_ids, assets: assets, @@ -92,9 +92,9 @@ curl http://localhost/api/v1/organizations -v -u #{login}:#{password} return end list = [] - organizations.each { |organization| + organizations.each do |organization| list.push organization.attributes_with_association_ids - } + end render json: list end @@ -257,9 +257,9 @@ curl http://localhost/api/v1/organization/{id} -v -u #{login}:#{password} -H "Co if params[:expand] list = [] - organization_all.each { |organization| + organization_all.each do |organization| list.push organization.attributes_with_association_names - } + end render json: list, status: :ok return end @@ -267,10 +267,10 @@ curl http://localhost/api/v1/organization/{id} -v -u #{login}:#{password} -H "Co # build result list if params[:label] organizations = [] - organization_all.each { |organization| + organization_all.each do |organization| a = { id: organization.id, label: organization.name, value: organization.name } organizations.push a - } + end # return result render json: organizations @@ -280,10 +280,10 @@ curl http://localhost/api/v1/organization/{id} -v -u #{login}:#{password} -H "Co if params[:full] organization_ids = [] assets = {} - organization_all.each { |organization| + organization_all.each do |organization| assets = organization.assets(assets) organization_ids.push organization.id - } + end # return result render json: { @@ -294,9 +294,9 @@ curl http://localhost/api/v1/organization/{id} -v -u #{login}:#{password} -H "Co end list = [] - organization_all.each { |organization| + organization_all.each do |organization| list.push organization.attributes_with_association_ids - } + end render json: list, status: :ok end diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rb index 7abb9ccf8..01c36af9f 100644 --- a/app/controllers/reports_controller.rb +++ b/app/controllers/reports_controller.rb @@ -25,7 +25,7 @@ class ReportsController < ApplicationController return if !get_params result = {} - get_params[:metric][:backend].each { |backend| + get_params[:metric][:backend].each do |backend| condition = get_params[:profile].condition if backend[:condition] backend[:condition].merge(condition) @@ -40,7 +40,7 @@ class ReportsController < ApplicationController selector: backend[:condition], params: backend[:params], ) - } + end #created = aggs(start, stop, range, 'created_at', profile.condition) #closed = aggs(start, stop, range, 'close_at', profile.condition) @@ -76,7 +76,7 @@ class ReportsController < ApplicationController # get data result = {} - get_params[:metric][:backend].each { |backend| + get_params[:metric][:backend].each do |backend| next if params[:downloadBackendSelected] != backend[:name] condition = get_params[:profile].condition if backend[:condition] @@ -103,7 +103,7 @@ class ReportsController < ApplicationController type: 'application/vnd.ms-excel', disposition: 'attachment' ) - } + end return if params[:sheet] render json: result @@ -117,10 +117,10 @@ class ReportsController < ApplicationController if params[:profile_id] profile = Report::Profile.find(params[:profile_id]) else - params[:profiles].each { |profile_id, active| + params[:profiles].each do |profile_id, active| next if !active profile = Report::Profile.find(profile_id) - } + end end if !profile raise Exceptions::UnprocessableEntity, 'No such active profile' diff --git a/app/controllers/search_controller.rb b/app/controllers/search_controller.rb index 8e8df76af..af280d34a 100644 --- a/app/controllers/search_controller.rb +++ b/app/controllers/search_controller.rb @@ -29,14 +29,14 @@ class SearchController < ApplicationController # get priorities of result objects_in_order = [] objects_in_order_hash = {} - objects.each { |object| + objects.each do |object| preferences = object.constantize.search_preferences(current_user) next if !preferences objects_in_order_hash[preferences[:prio]] = object - } - objects_in_order_hash.keys.sort.reverse_each { |prio| + end + objects_in_order_hash.keys.sort.reverse_each do |prio| objects_in_order.push objects_in_order_hash[prio] - } + end # try search index backend assets = {} @@ -46,7 +46,7 @@ class SearchController < ApplicationController # get direct search index based objects objects_with_direct_search_index = [] objects_without_direct_search_index = [] - objects.each { |object| + objects.each do |object| preferences = object.constantize.search_preferences(current_user) next if !preferences if preferences[:direct_search_index] @@ -54,48 +54,48 @@ class SearchController < ApplicationController else objects_without_direct_search_index.push object end - } + end # do only one query to index search backend if objects_with_direct_search_index.present? items = SearchIndexBackend.search(query, limit, objects_with_direct_search_index) - items.each { |item| + items.each do |item| require item[:type].to_filename record = Kernel.const_get(item[:type]).lookup(id: item[:id]) next if !record assets = record.assets(assets) result.push item - } + end end # e. g. do ticket query by Ticket class to handle ticket permissions - objects_without_direct_search_index.each { |object| + objects_without_direct_search_index.each do |object| object_result = search_generic_backend(object, query, limit, current_user, assets) if object_result.present? result = result.concat(object_result) end - } + end # sort order by object priority result_in_order = [] - objects_in_order.each { |object| - result.each { |item| + objects_in_order.each do |object| + result.each do |item| next if item[:type] != object item[:id] = item[:id].to_i result_in_order.push item - } - } + end + end result = result_in_order else # do query - objects_in_order.each { |object| + objects_in_order.each do |object| object_result = search_generic_backend(object, query, limit, current_user, assets) if object_result.present? result = result.concat(object_result) end - } + end end render json: { diff --git a/app/controllers/sessions/collection_base.rb b/app/controllers/sessions/collection_base.rb index 55eb9c078..6a98f90cf 100644 --- a/app/controllers/sessions/collection_base.rb +++ b/app/controllers/sessions/collection_base.rb @@ -7,9 +7,9 @@ module ExtraCollection collections[ Locale.to_app_model ] = Locale.where(active: true) collections[ Taskbar.to_app_model ] = Taskbar.where(user_id: user.id) - collections[ Taskbar.to_app_model ].each { |item| + collections[ Taskbar.to_app_model ].each do |item| assets = item.assets(assets) - } + end collections[ OnlineNotification.to_app_model ] = OnlineNotification.list(user, 100) assets = ApplicationModel.assets_of_object_list(collections[ OnlineNotification.to_app_model ], assets) @@ -18,25 +18,25 @@ module ExtraCollection assets = RecentView.assets_of_object_list(collections[ RecentView.to_app_model ], assets) collections[ Permission.to_app_model ] = [] - Permission.all.each { |item| + Permission.all.each do |item| assets = item.assets(assets) - } + end collections[ Role.to_app_model ] = [] - Role.all.each { |item| + Role.all.each do |item| assets = item.assets(assets) - } + end collections[ Group.to_app_model ] = [] - Group.all.each { |item| + Group.all.each do |item| assets = item.assets(assets) - } + end collections[ Organization.to_app_model ] = [] if user.organization_id - Organization.where(id: user.organization_id).each { |item| + Organization.where(id: user.organization_id).each do |item| assets = item.assets(assets) - } + end end [collections, assets] diff --git a/app/controllers/sessions/collection_ticket.rb b/app/controllers/sessions/collection_ticket.rb index 1c52b4f8d..e7c74d1a4 100644 --- a/app/controllers/sessions/collection_ticket.rb +++ b/app/controllers/sessions/collection_ticket.rb @@ -5,42 +5,42 @@ module ExtraCollection # all ticket stuff collections[ Macro.to_app_model ] = [] - Macro.all.each { |item| + Macro.all.each do |item| assets = item.assets(assets) - } + end collections[ Ticket::StateType.to_app_model ] = [] - Ticket::StateType.all.each { |item| + Ticket::StateType.all.each do |item| assets = item.assets(assets) - } + end collections[ Ticket::State.to_app_model ] = [] - Ticket::State.all.each { |item| + Ticket::State.all.each do |item| assets = item.assets(assets) - } + end collections[ Ticket::Priority.to_app_model ] = [] - Ticket::Priority.all.each { |item| + Ticket::Priority.all.each do |item| assets = item.assets(assets) - } + end collections[ Ticket::Article::Type.to_app_model ] = [] - Ticket::Article::Type.all.each { |item| + Ticket::Article::Type.all.each do |item| assets = item.assets(assets) - } + end collections[ Ticket::Article::Sender.to_app_model ] = [] - Ticket::Article::Sender.all.each { |item| + Ticket::Article::Sender.all.each do |item| assets = item.assets(assets) - } + end if user.permissions?(['ticket.agent', 'admin.channel_email']) # all signatures collections[ Signature.to_app_model ] = [] - Signature.all.each { |item| + Signature.all.each do |item| assets = item.assets(assets) - } + end # all email addresses collections[ EmailAddress.to_app_model ] = [] - EmailAddress.all.each { |item| + EmailAddress.all.each do |item| assets = item.assets(assets) - } + end end [collections, assets] end diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index 0c2500fc6..fbcc7ad05 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -281,14 +281,14 @@ class SessionsController < ApplicationController permission_check('admin.session') assets = {} sessions_clean = [] - SessionHelper.list.each { |session| + SessionHelper.list.each do |session| next if session.data['user_id'].blank? sessions_clean.push session next if session.data['user_id'] user = User.lookup(id: session.data['user_id']) next if !user assets = user.assets(assets) - } + end render json: { sessions: sessions_clean, assets: assets, @@ -307,12 +307,12 @@ class SessionsController < ApplicationController # config config = {} - Setting.select('name, preferences').where(frontend: true).each { |setting| + Setting.select('name, preferences').where(frontend: true).each do |setting| next if setting.preferences[:authentication] == true && !current_user value = Setting.get(setting.name) next if !current_user && (value == false || value.nil?) config[setting.name] = value - } + end # remember if we can to swich back to user if session[:switched_from_user_id] diff --git a/app/controllers/settings_controller.rb b/app/controllers/settings_controller.rb index 1a92a432a..d9288d6c0 100644 --- a/app/controllers/settings_controller.rb +++ b/app/controllers/settings_controller.rb @@ -6,10 +6,10 @@ class SettingsController < ApplicationController # GET /settings def index list = [] - Setting.all.each { |setting| + Setting.all.each do |setting| next if setting.preferences[:permission] && !current_user.permissions?(setting.preferences[:permission]) list.push setting - } + end render json: list, status: :ok end @@ -93,13 +93,13 @@ class SettingsController < ApplicationController def keep_certain_attributes setting = Setting.find(params[:id]) - [:name, :area, :state_initial, :frontend, :options].each { |key| + [:name, :area, :state_initial, :frontend, :options].each do |key| params.delete(key) - } + end if !params[:preferences].empty? - [:online_service_disable, :permission, :render].each { |key| + [:online_service_disable, :permission, :render].each do |key| params[:preferences].delete(key) - } + end params[:preferences].merge!(setting.preferences) end params diff --git a/app/controllers/slas_controller.rb b/app/controllers/slas_controller.rb index 99a2ceae0..574738ee5 100644 --- a/app/controllers/slas_controller.rb +++ b/app/controllers/slas_controller.rb @@ -53,16 +53,16 @@ curl http://localhost/api/v1/slas.json -v -u #{login}:#{password} # calendars assets = {} calendar_ids = [] - Calendar.all.each { |calendar| + Calendar.all.each do |calendar| assets = calendar.assets(assets) - } + end # slas sla_ids = [] - Sla.all.each { |item| + Sla.all.each do |item| sla_ids.push item.id assets = item.assets(assets) - } + end render json: { record_ids: sla_ids, assets: assets, diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rb index e9e66b0b7..5c910f039 100644 --- a/app/controllers/tags_controller.rb +++ b/app/controllers/tags_controller.rb @@ -7,13 +7,13 @@ class TagsController < ApplicationController def search list = Tag::Item.where('name_downcase LIKE ?', "#{params[:term].strip.downcase}%").order('name ASC').limit(params[:limit] || 10) results = [] - list.each { |item| + list.each do |item| result = { id: item.id, value: item.name, } results.push result - } + end render json: results end @@ -63,14 +63,14 @@ class TagsController < ApplicationController permission_check('admin.tag') list = Tag::Item.order('name ASC').limit(params[:limit] || 1000) results = [] - list.each { |item| + list.each do |item| result = { id: item.id, name: item.name, count: Tag.where(tag_item_id: item.id).count } results.push result - } + end render json: results end diff --git a/app/controllers/ticket_articles_controller.rb b/app/controllers/ticket_articles_controller.rb index baa28649b..bb10603da 100644 --- a/app/controllers/ticket_articles_controller.rb +++ b/app/controllers/ticket_articles_controller.rb @@ -39,13 +39,13 @@ class TicketArticlesController < ApplicationController articles = [] if params[:expand] - ticket.articles.each { |article| + ticket.articles.each do |article| # ignore internal article if customer is requesting next if article.internal == true && current_user.permissions?('ticket.customer') result = article.attributes_with_association_names articles.push result - } + end render json: articles, status: :ok return @@ -54,14 +54,14 @@ class TicketArticlesController < ApplicationController if params[:full] assets = {} record_ids = [] - ticket.articles.each { |article| + ticket.articles.each do |article| # ignore internal article if customer is requesting next if article.internal == true && current_user.permissions?('ticket.customer') record_ids.push article.id assets = article.assets({}) - } + end render json: { record_ids: record_ids, assets: assets, @@ -69,12 +69,12 @@ class TicketArticlesController < ApplicationController return end - ticket.articles.each { |article| + ticket.articles.each do |article| # ignore internal article if customer is requesting next if article.internal == true && current_user.permissions?('ticket.customer') articles.push article.attributes_with_association_names - } + end render json: articles end @@ -224,11 +224,11 @@ class TicketArticlesController < ApplicationController list = article.attachments || [] access = false - list.each { |item| + list.each do |item| if item.id.to_i == params[:id].to_i access = true end - } + end raise Exceptions::NotAuthorized, 'Requested file id is not linked with article_id.' if !access # find file diff --git a/app/controllers/ticket_overviews_controller.rb b/app/controllers/ticket_overviews_controller.rb index 6aa6ae1f1..58e3a774d 100644 --- a/app/controllers/ticket_overviews_controller.rb +++ b/app/controllers/ticket_overviews_controller.rb @@ -12,7 +12,7 @@ class TicketOverviewsController < ApplicationController if !params[:view] index_and_lists = Ticket::Overviews.index(current_user) indexes = [] - index_and_lists.each { |index| + index_and_lists.each do |index| assets = {} overview = Overview.lookup(id: index[:overview][:id]) meta = { @@ -22,7 +22,7 @@ class TicketOverviewsController < ApplicationController count: index[:count], } indexes.push meta - } + end render json: indexes return end @@ -31,17 +31,17 @@ class TicketOverviewsController < ApplicationController assets = {} result = {} - index_and_lists.each { |index| + index_and_lists.each do |index| next if index[:overview][:view] != params[:view] overview = Overview.lookup(id: index[:overview][:id]) assets = overview.assets(assets) - index[:tickets].each { |ticket_meta| + index[:tickets].each do |ticket_meta| ticket = Ticket.lookup(id: ticket_meta[:id]) assets = ticket.assets(assets) - } + end result = index - } + end render json: { assets: assets, diff --git a/app/controllers/tickets_controller.rb b/app/controllers/tickets_controller.rb index fd5c73ee3..5f289bb01 100644 --- a/app/controllers/tickets_controller.rb +++ b/app/controllers/tickets_controller.rb @@ -25,9 +25,9 @@ class TicketsController < ApplicationController if params[:expand] list = [] - tickets.each { |ticket| + tickets.each do |ticket| list.push ticket.attributes_with_association_names - } + end render json: list, status: :ok return end @@ -35,10 +35,10 @@ class TicketsController < ApplicationController if params[:full] assets = {} item_ids = [] - tickets.each { |item| + tickets.each do |item| item_ids.push item.id assets = item.assets(assets) - } + end render json: { record_ids: item_ids, assets: assets, @@ -80,9 +80,9 @@ class TicketsController < ApplicationController # overwrite params if !current_user.permissions?('ticket.agent') - [:owner, :owner_id, :customer, :customer_id, :organization, :organization_id, :preferences].each { |key| + [:owner, :owner_id, :customer, :customer_id, :organization, :organization_id, :preferences].each do |key| clean_params.delete(key) - } + end clean_params[:customer_id] = current_user.id end @@ -124,9 +124,9 @@ class TicketsController < ApplicationController # create tags if given if params[:tags].present? tags = params[:tags].split(/,/) - tags.each { |tag| + tags.each do |tag| ticket.tag_add(tag) - } + end end # create article if given @@ -145,11 +145,11 @@ class TicketsController < ApplicationController if params[:links].present? link = params[:links].permit!.to_h raise Exceptions::UnprocessableEntity, 'Invalid link structure' if !link.is_a? Hash - link.each { |target_object, link_types_with_object_ids| + link.each do |target_object, link_types_with_object_ids| raise Exceptions::UnprocessableEntity, 'Invalid link structure (Object)' if !link_types_with_object_ids.is_a? Hash - link_types_with_object_ids.each { |link_type, object_ids| + link_types_with_object_ids.each do |link_type, object_ids| raise Exceptions::UnprocessableEntity, 'Invalid link structure (Object->LinkType)' if !object_ids.is_a? Array - object_ids.each { |local_object_id| + object_ids.each do |local_object_id| link = Link.add( link_type: link_type, link_object_target: target_object, @@ -157,9 +157,9 @@ class TicketsController < ApplicationController link_object_source: 'Ticket', link_object_source_value: ticket.id, ) - } - } - } + end + end + end end if params[:expand] @@ -186,9 +186,9 @@ class TicketsController < ApplicationController # overwrite params if !current_user.permissions?('ticket.agent') - [:owner, :owner_id, :customer, :customer_id, :organization, :organization_id, :preferences].each { |key| + [:owner, :owner_id, :customer, :customer_id, :organization, :organization_id, :preferences].each do |key| clean_params.delete(key) - } + end end ticket.with_lock do @@ -285,20 +285,20 @@ class TicketsController < ApplicationController # get related assets ticket_ids_by_customer = [] - ticket_lists.each { |ticket_list| + ticket_lists.each do |ticket_list| ticket_ids_by_customer.push ticket_list.id assets = ticket_list.assets(assets) - } + end ticket_ids_recent_viewed = [] recent_views = RecentView.list(current_user, 8, 'Ticket').delete_if { |object| object['o_id'] == ticket.id } - recent_views.each { |recent_view| + recent_views.each do |recent_view| next if recent_view['object'] != 'Ticket' ticket_ids_recent_viewed.push recent_view['o_id'] recent_view_ticket = Ticket.find(recent_view['o_id']) next if recent_view_ticket.state.state_type.name == 'merged' assets = recent_view_ticket.assets(assets) - } + end # return result render json: { @@ -405,9 +405,9 @@ class TicketsController < ApplicationController if params[:expand] list = [] - tickets.each { |ticket| + tickets.each do |ticket| list.push ticket.attributes_with_association_names - } + end render json: list, status: :ok return end @@ -490,9 +490,9 @@ class TicketsController < ApplicationController }, }, } - conditions.each { |key, local_condition| + conditions.each do |key, local_condition| user_tickets[key] = ticket_ids_and_assets(local_condition, current_user, limit, assets) - } + end # generate stats by user condition = { @@ -531,9 +531,9 @@ class TicketsController < ApplicationController }, }, } - conditions.each { |key, local_condition| + conditions.each do |key, local_condition| org_tickets[key] = ticket_ids_and_assets(local_condition, current_user, limit, assets) - } + end # generate stats by org condition = { @@ -566,14 +566,14 @@ class TicketsController < ApplicationController # get related users article_ids = [] - ticket.articles.each { |article| + ticket.articles.each do |article| # ignore internal article if customer is requesting next if article.internal == true && current_user.permissions?('ticket.customer') article_ids.push article.id assets = article.assets(assets) - } + end # get links links = Link.list( @@ -581,13 +581,13 @@ class TicketsController < ApplicationController link_object_value: ticket.id, ) link_list = [] - links.each { |item| + links.each do |item| link_list.push item if item['link_object'] == 'Ticket' linked_ticket = Ticket.lookup(id: item['link_object_value']) assets = linked_ticket.assets(assets) end - } + end # get tags tags = ticket.tag_list diff --git a/app/controllers/time_accountings_controller.rb b/app/controllers/time_accountings_controller.rb index e393b1c51..2c93797f6 100644 --- a/app/controllers/time_accountings_controller.rb +++ b/app/controllers/time_accountings_controller.rb @@ -12,7 +12,7 @@ class TimeAccountingsController < ApplicationController end_periode = start_periode.end_of_month time_unit = {} - Ticket::TimeAccounting.where('created_at >= ? AND created_at <= ?', start_periode, end_periode).pluck(:ticket_id, :time_unit, :created_by_id).each { |record| + Ticket::TimeAccounting.where('created_at >= ? AND created_at <= ?', start_periode, end_periode).pluck(:ticket_id, :time_unit, :created_by_id).each do |record| if !time_unit[record[0]] time_unit[record[0]] = { time_unit: 0, @@ -20,12 +20,12 @@ class TimeAccountingsController < ApplicationController } end time_unit[record[0]][:time_unit] += record[1] - } + end customers = {} organizations = {} agents = {} results = [] - time_unit.each { |ticket_id, local_time_unit| + time_unit.each do |ticket_id, local_time_unit| ticket = Ticket.lookup(id: ticket_id) next if !ticket if !customers[ticket.customer_id] @@ -61,7 +61,7 @@ class TimeAccountingsController < ApplicationController agent: agents[local_time_unit[:agent_id]], } results.push result - } + end if params[:download] header = [ @@ -163,13 +163,13 @@ class TimeAccountingsController < ApplicationController }, ] result = [] - results.each { |row| - row[:ticket].keys.each { |field| + results.each do |row| + row[:ticket].keys.each do |field| next if row[:ticket][field].blank? next if !row[:ticket][field].is_a?(ActiveSupport::TimeWithZone) row[:ticket][field] = row[:ticket][field].iso8601 - } + end result_row = [ row[:ticket]['number'], @@ -198,7 +198,7 @@ class TimeAccountingsController < ApplicationController row[:ticket]['escalation_at'], ] result.push result_row - } + end content = sheet("By Ticket #{year}-#{month}", header, result) send_data( content, @@ -221,7 +221,7 @@ class TimeAccountingsController < ApplicationController end_periode = start_periode.end_of_month time_unit = {} - Ticket::TimeAccounting.where('created_at >= ? AND created_at <= ?', start_periode, end_periode).pluck(:ticket_id, :time_unit, :created_by_id).each { |record| + Ticket::TimeAccounting.where('created_at >= ? AND created_at <= ?', start_periode, end_periode).pluck(:ticket_id, :time_unit, :created_by_id).each do |record| if !time_unit[record[0]] time_unit[record[0]] = { time_unit: 0, @@ -229,10 +229,10 @@ class TimeAccountingsController < ApplicationController } end time_unit[record[0]][:time_unit] += record[1] - } + end customers = {} - time_unit.each { |ticket_id, local_time_unit| + time_unit.each do |ticket_id, local_time_unit| ticket = Ticket.lookup(id: ticket_id) next if !ticket if !customers[ticket.customer_id] @@ -248,11 +248,11 @@ class TimeAccountingsController < ApplicationController next end customers[ticket.customer_id][:time_unit] += local_time_unit[:time_unit] - } + end results = [] - customers.each { |_customer_id, content| + customers.each do |_customer_id, content| results.push content - } + end if params[:download] header = [ @@ -270,7 +270,7 @@ class TimeAccountingsController < ApplicationController } ] result = [] - results.each { |row| + results.each do |row| customer_name = User.find(row[:customer]['id']).fullname organization_name = '' if row[:organization].present? @@ -278,7 +278,7 @@ class TimeAccountingsController < ApplicationController end result_row = [customer_name, organization_name, row[:time_unit]] result.push result_row - } + end content = sheet("By Customer #{year}-#{month}", header, result) send_data( content, @@ -301,7 +301,7 @@ class TimeAccountingsController < ApplicationController end_periode = start_periode.end_of_month time_unit = {} - Ticket::TimeAccounting.where('created_at >= ? AND created_at <= ?', start_periode, end_periode).pluck(:ticket_id, :time_unit, :created_by_id).each { |record| + Ticket::TimeAccounting.where('created_at >= ? AND created_at <= ?', start_periode, end_periode).pluck(:ticket_id, :time_unit, :created_by_id).each do |record| if !time_unit[record[0]] time_unit[record[0]] = { time_unit: 0, @@ -309,10 +309,10 @@ class TimeAccountingsController < ApplicationController } end time_unit[record[0]][:time_unit] += record[1] - } + end organizations = {} - time_unit.each { |ticket_id, local_time_unit| + time_unit.each do |ticket_id, local_time_unit| ticket = Ticket.lookup(id: ticket_id) next if !ticket next if !ticket.organization_id @@ -324,11 +324,11 @@ class TimeAccountingsController < ApplicationController next end organizations[ticket.organization_id][:time_unit] += local_time_unit[:time_unit] - } + end results = [] - organizations.each { |_customer_id, content| + organizations.each do |_customer_id, content| results.push content - } + end if params[:download] header = [ @@ -342,14 +342,14 @@ class TimeAccountingsController < ApplicationController } ] result = [] - results.each { |row| + results.each do |row| organization_name = '' if row[:organization].present? organization_name = row[:organization]['name'] end result_row = [organization_name, row[:time_unit]] result.push result_row - } + end content = sheet("By Organization #{year}-#{month}", header, result) send_data( content, @@ -389,23 +389,23 @@ class TimeAccountingsController < ApplicationController format_header.set_bg_color('gray') format_header.set_color('white') count = 0 - header.each { |item| + header.each do |item| if item[:width] worksheet.set_column(count, count, item[:width]) end worksheet.write(2, count, item[:name], format_header) count += 1 - } + end row_count = 2 - result.each { |row| + result.each do |row| row_count += 1 row_item_count = 0 - row.each { |item| + row.each do |item| worksheet.write(row_count, row_item_count, item) row_item_count += 1 - } - } + end + end workbook.close diff --git a/app/controllers/user_access_token_controller.rb b/app/controllers/user_access_token_controller.rb index 7a4a27dc8..16def0e98 100644 --- a/app/controllers/user_access_token_controller.rb +++ b/app/controllers/user_access_token_controller.rb @@ -6,34 +6,34 @@ class UserAccessTokenController < ApplicationController def index tokens = Token.where(action: 'api', persistent: true, user_id: current_user.id).order('updated_at DESC, label ASC') token_list = [] - tokens.each { |token| + tokens.each do |token| attributes = token.attributes attributes.delete('persistent') attributes.delete('name') token_list.push attributes - } + end local_permissions = current_user.permissions local_permissions_new = {} - local_permissions.each { |key, _value| + local_permissions.each do |key, _value| keys = Object.const_get('Permission').with_parents(key) - keys.each { |local_key| + keys.each do |local_key| next if local_permissions_new.key?([local_key]) if local_permissions[local_key] == true local_permissions_new[local_key] = true next end local_permissions_new[local_key] = false - } - } + end + end permissions = [] - Permission.all.where(active: true).order(:name).each { |permission| + Permission.all.where(active: true).order(:name).each do |permission| next if !local_permissions_new.key?(permission.name) && !current_user.permissions?(permission.name) permission_attributes = permission.attributes if local_permissions_new[permission.name] == false permission_attributes['preferences']['disabled'] = true end permissions.push permission_attributes - } + end render json: { tokens: token_list, diff --git a/app/controllers/user_devices_controller.rb b/app/controllers/user_devices_controller.rb index 10f9a13f3..b419b336c 100644 --- a/app/controllers/user_devices_controller.rb +++ b/app/controllers/user_devices_controller.rb @@ -6,7 +6,7 @@ class UserDevicesController < ApplicationController def index devices = UserDevice.where(user_id: current_user.id).order('updated_at DESC, name ASC') devices_full = [] - devices.each { |device| + devices.each do |device| attributes = device.attributes if device.location_details['city_name'] && !device.location_details['city_name'].empty? attributes['location'] += ", #{device.location_details['city_name']}" @@ -21,7 +21,7 @@ class UserDevicesController < ApplicationController attributes['current'] = true end devices_full.push attributes - } + end model_index_render_result(devices_full) end @@ -32,12 +32,12 @@ class UserDevicesController < ApplicationController # delete device and session's if user_device - SessionHelper.list.each { |session| + SessionHelper.list.each do |session| next if !session.data['user_id'] next if !session.data['user_device_id'] next if session.data['user_device_id'] != user_device.id SessionHelper.destroy( session.id ) - } + end user_device.destroy end render json: {}, status: :ok diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 92e289b6b..35c3ab3fa 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -34,9 +34,9 @@ class UsersController < ApplicationController if params[:expand] list = [] - users.each { |user| + users.each do |user| list.push user.attributes_with_association_names - } + end render json: list, status: :ok return end @@ -44,10 +44,10 @@ class UsersController < ApplicationController if params[:full] assets = {} item_ids = [] - users.each { |item| + users.each do |item| item_ids.push item.id assets = item.assets(assets) - } + end render json: { record_ids: item_ids, assets: assets, @@ -56,9 +56,9 @@ class UsersController < ApplicationController end users_all = [] - users.each { |user| + users.each do |user| users_all.push User.lookup(id: user.id).attributes_with_association_ids - } + end render json: users_all, status: :ok end @@ -145,12 +145,12 @@ class UsersController < ApplicationController group_ids = [] role_ids = [] if count <= 2 - Role.where(name: %w(Admin Agent)).each { |role| + Role.where(name: %w(Admin Agent)).each do |role| role_ids.push role.id - } - Group.all().each { |group| + end + Group.all().each do |group| group_ids.push group.id - } + end # everybody else will go as customer per default else @@ -384,9 +384,9 @@ class UsersController < ApplicationController if params[:expand] list = [] - user_all.each { |user| + user_all.each do |user| list.push user.attributes_with_association_names - } + end render json: list, status: :ok return end @@ -394,14 +394,14 @@ class UsersController < ApplicationController # build result list if params[:label] users = [] - user_all.each { |user| + user_all.each do |user| realname = user.firstname.to_s + ' ' + user.lastname.to_s if user.email && user.email.to_s != '' realname = realname + ' <' + user.email.to_s + '>' end a = { id: user.id, label: realname, value: realname } users.push a - } + end # return result render json: users @@ -411,10 +411,10 @@ class UsersController < ApplicationController if params[:full] user_ids = [] assets = {} - user_all.each { |user| + user_all.each do |user| assets = user.assets(assets) user_ids.push user.id - } + end # return result render json: { @@ -425,9 +425,9 @@ class UsersController < ApplicationController end list = [] - user_all.each { |user| + user_all.each do |user| list.push user.attributes_with_association_ids - } + end render json: list, status: :ok end @@ -464,14 +464,14 @@ class UsersController < ApplicationController # build result list if !params[:full] users = [] - user_all.each { |user| + user_all.each do |user| realname = user.firstname.to_s + ' ' + user.lastname.to_s if user.email && user.email.to_s != '' realname = realname + ' <' + user.email.to_s + '>' end a = { id: user.id, label: realname, value: realname } users.push a - } + end # return result render json: users @@ -480,10 +480,10 @@ class UsersController < ApplicationController user_ids = [] assets = {} - user_all.each { |user| + user_all.each do |user| assets = user.assets(assets) user_ids.push user.id - } + end # return result render json: { @@ -806,9 +806,9 @@ curl http://localhost/api/v1/users/preferences -v -u #{login}:#{password} -H "Co if params[:user] user = User.find(current_user.id) user.with_lock do - params[:user].each { |key, value| + params[:user].each do |key, value| user.preferences[key.to_sym] = value - } + end user.save! end end diff --git a/app/models/application_model/can_assets.rb b/app/models/application_model/can_assets.rb index 838670092..c66c563c7 100644 --- a/app/models/application_model/can_assets.rb +++ b/app/models/application_model/can_assets.rb @@ -33,13 +33,13 @@ returns return data if !self['created_by_id'] && !self['updated_by_id'] app_model_user = User.to_app_model - %w(created_by_id updated_by_id).each { |local_user_id| + %w(created_by_id updated_by_id).each do |local_user_id| next if !self[ local_user_id ] next if data[ app_model_user ] && data[ app_model_user ][ self[ local_user_id ] ] user = User.lookup(id: self[ local_user_id ]) next if !user data = user.assets(data) - } + end data end @@ -57,7 +57,7 @@ get assets and record_ids of selector # get assets of condition models = Models.all - send(selector).each { |item, content| + send(selector).each do |item, content| attribute = item.split(/\./) next if !attribute[1] begin @@ -74,19 +74,19 @@ get assets and record_ids of selector next if !models[attribute_class][:reflections][reflection].klass attribute_ref_class = models[attribute_class][:reflections][reflection].klass if content['value'].instance_of?(Array) - content['value'].each { |item_id| + content['value'].each do |item_id| attribute_object = attribute_ref_class.find_by(id: item_id) if attribute_object assets = attribute_object.assets(assets) end - } + end else attribute_object = attribute_ref_class.find_by(id: content['value']) if attribute_object assets = attribute_object.assets(assets) end end - } + end assets end @@ -134,7 +134,7 @@ get assets of object list =end def assets_of_object_list(list, assets = {}) - list.each { |item| + list.each do |item| require item['object'].to_filename record = Kernel.const_get(item['object']).find(item['o_id']) assets = record.assets(assets) @@ -146,7 +146,7 @@ get assets of object list user = User.find(item['updated_by_id']) assets = user.assets(assets) end - } + end assets end end diff --git a/app/models/application_model/can_associations.rb b/app/models/application_model/can_associations.rb index 0eb97ee03..2b5ac620a 100644 --- a/app/models/application_model/can_associations.rb +++ b/app/models/application_model/can_associations.rb @@ -29,7 +29,7 @@ returns end # set relations by id/verify if ref exists - self.class.reflect_on_all_associations.map { |assoc| + self.class.reflect_on_all_associations.map do |assoc| assoc_name = assoc.name next if association_attributes_ignored.include?(assoc_name) real_ids = assoc_name[0, assoc_name.length - 1] + '_ids' @@ -40,7 +40,7 @@ returns list_of_items = [ params[real_ids] ] end list = [] - list_of_items.each { |item_id| + list_of_items.each do |item_id| next if !item_id lookup = assoc.klass.lookup(id: item_id) @@ -49,12 +49,12 @@ returns raise ArgumentError, "No value found for '#{assoc_name}' with id #{item_id.inspect}" end list.push item_id - } + end send("#{real_ids}=", list) - } + end # set relations by name/lookup - self.class.reflect_on_all_associations.map { |assoc| + self.class.reflect_on_all_associations.map do |assoc| assoc_name = assoc.name next if association_attributes_ignored.include?(assoc_name) real_ids = assoc_name[0, assoc_name.length - 1] + '_ids' @@ -66,7 +66,7 @@ returns next if !params[real_values].instance_of?(Array) list = [] class_object = assoc.klass - params[real_values].each { |value| + params[real_values].each do |value| lookup = nil if class_object == User if !lookup @@ -84,9 +84,9 @@ returns raise ArgumentError, "No lookup value found for '#{assoc_name}': #{value.inspect}" end list.push lookup.id - } + end send("#{real_ids}=", list) - } + end end =begin @@ -110,12 +110,12 @@ returns # get relations attributes = self.attributes - self.class.reflect_on_all_associations.map { |assoc| + self.class.reflect_on_all_associations.map do |assoc| next if association_attributes_ignored.include?(assoc.name) real_ids = assoc.name.to_s[0, assoc.name.to_s.length - 1] + '_ids' next if !respond_to?(real_ids) attributes[real_ids] = send(real_ids) - } + end # special handling for group access associations if respond_to?(:group_ids_access_map) @@ -145,21 +145,21 @@ returns # get relations attributes = attributes_with_association_ids - self.class.reflect_on_all_associations.map { |assoc| + self.class.reflect_on_all_associations.map do |assoc| next if !respond_to?(assoc.name) next if association_attributes_ignored.include?(assoc.name) ref = send(assoc.name) next if !ref if ref.respond_to?(:first) attributes[assoc.name.to_s] = [] - ref.each { |item| + ref.each do |item| if item[:login] attributes[assoc.name.to_s].push item[:login] next end next if !item[:name] attributes[assoc.name.to_s].push item[:name] - } + end if ref.count.positive? && attributes[assoc.name.to_s].empty? attributes.delete(assoc.name.to_s) end @@ -171,7 +171,7 @@ returns end next if !ref[:name] attributes[assoc.name.to_s] = ref[:name] - } + end # special handling for group access associations if respond_to?(:group_names_access_map) @@ -182,12 +182,12 @@ returns { 'created_by_id' => 'created_by', 'updated_by_id' => 'updated_by', - }.each { |source, destination| + }.each do |source, destination| next if !attributes[source] user = User.lookup(id: attributes[source]) next if !user attributes[destination] = user.login - } + end filter_attributes(attributes) @@ -196,9 +196,9 @@ returns def filter_attributes(attributes) # remove forbitten attributes - %w(password token tokens token_ids).each { |item| + %w(password token tokens token_ids).each do |item| attributes.delete(item) - } + end end =begin @@ -217,22 +217,22 @@ returns def association_id_validation(attribute_id, value) return true if value.nil? - attributes.each { |key, _value| + attributes.each do |key, _value| next if key != attribute_id # check if id is assigned next if !key.end_with?('_id') key_short = key.chomp('_id') - self.class.reflect_on_all_associations.map { |assoc| + self.class.reflect_on_all_associations.map do |assoc| next if assoc.name.to_s != key_short item = assoc.class_name.constantize return false if !item.respond_to?(:find_by) ref_object = item.find_by(id: value) return false if !ref_object return true - } - } + end + end true end @@ -298,13 +298,13 @@ returns end data = {} - params.each { |key, value| + params.each do |key, value| data[key.to_sym] = value - } + end data.symbolize_keys! available_attributes = attribute_names - reflect_on_all_associations.map { |assoc| + reflect_on_all_associations.map do |assoc| assoc_name = assoc.name value = data[assoc_name] @@ -360,7 +360,7 @@ returns # get association class and do lookup class_object = assoc.klass lookup_ids = [] - value.each { |item| + value.each do |item| lookup = nil if class_object == User if item.instance_of?(String) @@ -382,14 +382,14 @@ returns raise ArgumentError, "No lookup value found for '#{assoc_name}': #{item.inspect}" end lookup_ids.push lookup.id - } + end # release data value data.delete(assoc_name) # remember id reference data[ref_names.to_sym] = lookup_ids - } + end data end diff --git a/app/models/application_model/can_cleanup_param.rb b/app/models/application_model/can_cleanup_param.rb index 16b823094..d6bc032e0 100644 --- a/app/models/application_model/can_cleanup_param.rb +++ b/app/models/application_model/can_cleanup_param.rb @@ -32,9 +32,9 @@ returns end data = {} - params.each { |key, value| + params.each do |key, value| data[key.to_sym] = value - } + end # ignore id for new objects if new_object && params[:id] @@ -43,11 +43,11 @@ returns # only use object attributes clean_params = {} - new.attributes.each { |attribute, _value| + new.attributes.each do |attribute, _value| next if !data.key?(attribute.to_sym) # check reference records, referenced by _id attributes - reflect_on_all_associations.map { |assoc| + reflect_on_all_associations.map do |assoc| class_name = assoc.options[:class_name] next if !class_name name = "#{assoc.name}_id".to_sym @@ -55,9 +55,9 @@ returns next if data[name].blank? next if assoc.klass.lookup(id: data[name]) raise ArgumentError, "Invalid value for param '#{name}': #{data[name].inspect}" - } + end clean_params[attribute.to_sym] = data[attribute.to_sym] - } + end # we do want to set this via database filter_unused_params(clean_params) @@ -80,9 +80,9 @@ returns def filter_unused_params(data) # we do want to set this via database - [:action, :controller, :updated_at, :created_at, :updated_by_id, :created_by_id, :updated_by, :created_by].each { |key| + [:action, :controller, :updated_at, :created_at, :updated_by_id, :created_by_id, :updated_by, :created_by].each do |key| data.delete(key) - } + end data end diff --git a/app/models/application_model/can_creates_and_updates.rb b/app/models/application_model/can_creates_and_updates.rb index 1f0bf2557..d31417821 100644 --- a/app/models/application_model/can_creates_and_updates.rb +++ b/app/models/application_model/can_creates_and_updates.rb @@ -29,9 +29,9 @@ returns else where(name: data[:name]) end - records.each { |loop_record| + records.each do |loop_record| return loop_record if loop_record.name == data[:name] - } + end elsif data[:login] # do lookup with == to handle case insensitive databases @@ -40,9 +40,9 @@ returns else where(login: data[:login]) end - records.each { |loop_record| + records.each do |loop_record| return loop_record if loop_record.login == data[:login] - } + end elsif data[:email] # do lookup with == to handle case insensitive databases @@ -51,9 +51,9 @@ returns else where(email: data[:email]) end - records.each { |loop_record| + records.each do |loop_record| return loop_record if loop_record.email == data[:email] - } + end elsif data[:locale] && data[:source] # do lookup with == to handle case insensitive databases @@ -62,9 +62,9 @@ returns else where(locale: data[:locale], source: data[:source]) end - records.each { |loop_record| + records.each do |loop_record| return loop_record if loop_record.source == data[:source] - } + end end create(data) end @@ -133,12 +133,12 @@ returns else where(name: data[:name]) end - records.each { |loop_record| + records.each do |loop_record| if loop_record.name == data[:name] loop_record.update!(data) return loop_record end - } + end record = new(data) record.save return record @@ -150,12 +150,12 @@ returns else where(login: data[:login]) end - records.each { |loop_record| + records.each do |loop_record| if loop_record.login.casecmp(data[:login]).zero? loop_record.update!(data) return loop_record end - } + end record = new(data) record.save return record @@ -167,12 +167,12 @@ returns else where(email: data[:email]) end - records.each { |loop_record| + records.each do |loop_record| if loop_record.email.casecmp(data[:email]).zero? loop_record.update!(data) return loop_record end - } + end record = new(data) record.save return record @@ -184,12 +184,12 @@ returns else where(locale: data[:locale]) end - records.each { |loop_record| + records.each do |loop_record| if loop_record.locale.casecmp(data[:locale]).zero? loop_record.update!(data) return loop_record end - } + end record = new(data) record.save return record diff --git a/app/models/application_model/can_lookup.rb b/app/models/application_model/can_lookup.rb index 9fdb097cf..b5f8e1ae4 100644 --- a/app/models/application_model/can_lookup.rb +++ b/app/models/application_model/can_lookup.rb @@ -38,12 +38,12 @@ returns else where(name: data[:name]) end - records.each { |loop_record| + records.each do |loop_record| if loop_record.name == data[:name] cache_set(data[:name], loop_record) return loop_record end - } + end return elsif data[:login] cache = cache_get(data[:login]) @@ -55,12 +55,12 @@ returns else where(login: data[:login]) end - records.each { |loop_record| + records.each do |loop_record| if loop_record.login == data[:login] cache_set(data[:login], loop_record) return loop_record end - } + end return elsif data[:email] cache = cache_get(data[:email]) @@ -72,12 +72,12 @@ returns else where(email: data[:email]) end - records.each { |loop_record| + records.each do |loop_record| if loop_record.email == data[:email] cache_set(data[:email], loop_record) return loop_record end - } + end return end diff --git a/app/models/application_model/can_lookup_search_index_attributes.rb b/app/models/application_model/can_lookup_search_index_attributes.rb index 96cff5e8f..5607bb005 100644 --- a/app/models/application_model/can_lookup_search_index_attributes.rb +++ b/app/models/application_model/can_lookup_search_index_attributes.rb @@ -18,7 +18,7 @@ returns def search_index_attribute_lookup attributes = self.attributes - self.attributes.each { |key, value| + self.attributes.each do |key, value| next if !value # get attribute name @@ -52,14 +52,14 @@ returns # save name of ref object attributes[ attribute_name ] = value - } + end ignored_attributes = self.class.instance_variable_get(:@search_index_attributes_ignored) || [] return attributes if ignored_attributes.blank? - ignored_attributes.each { |attribute| + ignored_attributes.each do |attribute| attributes.delete(attribute.to_s) - } + end attributes end diff --git a/app/models/application_model/checks_attribute_values_and_length.rb b/app/models/application_model/checks_attribute_values_and_length.rb index bedd15cca..d6739a14d 100644 --- a/app/models/application_model/checks_attribute_values_and_length.rb +++ b/app/models/application_model/checks_attribute_values_and_length.rb @@ -17,7 +17,7 @@ module ApplicationModel::ChecksAttributeValuesAndLength def check_attribute_values_and_length columns = self.class.columns_hash - attributes.each { |name, value| + attributes.each do |name, value| next if value.blank? next if !value.instance_of?(String) column = columns[name] @@ -52,7 +52,7 @@ module ApplicationModel::ChecksAttributeValuesAndLength # strip 4 bytes utf8 chars if needed (mysql/mariadb will complain it) next if self[name].blank? self[name] = self[name].utf8_to_3bytesutf8 - } + end true end end diff --git a/app/models/application_model/has_cache.rb b/app/models/application_model/has_cache.rb index 4ba51ddb3..892f4b2ca 100644 --- a/app/models/application_model/has_cache.rb +++ b/app/models/application_model/has_cache.rb @@ -36,9 +36,9 @@ module ApplicationModel::HasCache keys.push "#{self.class}::#{login}" end - keys.each { |key| + keys.each do |key| Cache.delete(key) - } + end # delete old name / login caches if saved_changes? diff --git a/app/models/calendar.rb b/app/models/calendar.rb index 6324e278c..93a23fea1 100644 --- a/app/models/calendar.rb +++ b/app/models/calendar.rb @@ -108,11 +108,11 @@ returns def self.timezones list = {} - TZInfo::Timezone.all_country_zone_identifiers.each { |timezone| + TZInfo::Timezone.all_country_zone_identifiers.each do |timezone| t = TZInfo::Timezone.get(timezone) diff = t.current_period.utc_total_offset / 60 / 60 list[ timezone ] = diff - } + end list end @@ -168,14 +168,14 @@ returns end # remove old ical entries if feed has changed - public_holidays.each { |day, meta| + public_holidays.each do |day, meta| next if !public_holidays[day]['feed'] next if meta['feed'] == Digest::MD5.hexdigest(ical_url) public_holidays.delete(day) - } + end # sync new ical feed dates - events.each { |day, summary| + events.each do |day, summary| if !public_holidays[day] public_holidays[day] = {} end @@ -189,7 +189,7 @@ returns summary: summary, feed: Digest::MD5.hexdigest(ical_url) } - } + end self.last_log = nil if id Cache.write( @@ -223,7 +223,7 @@ returns cals = Icalendar::Calendar.parse(cal_file) cal = cals.first events = {} - cal.events.each { |event| + cal.events.each do |event| if event.rrule # loop till days @@ -231,11 +231,11 @@ returns interval_frame_end = Date.parse("#{Time.zone.now + 3.years}-12-31") occurrences = event.occurrences_between(interval_frame_start, interval_frame_end) if occurrences.present? - occurrences.each { |occurrence| + occurrences.each do |occurrence| result = Calendar.day_and_comment_by_event(event, occurrence.start_time) next if !result events[result[0]] = result[1] - } + end end end next if event.dtstart < Time.zone.now - 1.year @@ -243,7 +243,7 @@ returns result = Calendar.day_and_comment_by_event(event, event.dtstart) next if !result events[result[0]] = result[1] - } + end events.sort.to_h end @@ -266,12 +266,12 @@ returns # if changed calendar is default, set all others default to false def sync_default return true if !default - Calendar.find_each { |calendar| + Calendar.find_each do |calendar| next if calendar.id == id next if !calendar.default calendar.default = false calendar.save - } + end true end @@ -286,7 +286,7 @@ returns # check if sla's are refer to an existing calendar default_calendar = Calendar.find_by(default: true) - Sla.find_each { |sla| + Sla.find_each do |sla| if !sla.calendar_id sla.calendar_id = default_calendar.id sla.save! @@ -296,7 +296,7 @@ returns sla.calendar_id = default_calendar.id sla.save! end - } + end true end @@ -311,7 +311,7 @@ returns # fillup feed info before = public_holidays_was - public_holidays.each { |day, meta| + public_holidays.each do |day, meta| if before && before[day] && before[day]['feed'] meta['feed'] = before[day]['feed'] end @@ -320,7 +320,7 @@ returns else false end - } + end true end end diff --git a/app/models/channel.rb b/app/models/channel.rb index 3a13312a6..00a872600 100644 --- a/app/models/channel.rb +++ b/app/models/channel.rb @@ -140,7 +140,7 @@ stream all accounts current_channels = [] channels = Channel.where('active = ? AND area LIKE ?', true, '%::Account') - channels.each { |channel| + channels.each do |channel| next if channel.options[:adapter] != 'twitter' channel_id = channel.id.to_s current_channels.push channel_id @@ -174,7 +174,7 @@ stream all accounts sleep @@channel_stream.count # start threads for each channel - @@channel_stream[channel_id][:thread] = Thread.new { + @@channel_stream[channel_id][:thread] = Thread.new do begin logger.info "Started stream channel for '#{channel.id}' (#{channel.area})..." @@channel_stream[channel_id] ||= {} @@ -192,11 +192,11 @@ stream all accounts channel.save @@channel_stream[channel_id] = false end - } - } + end + end # cleanup deleted channels - last_channels.each { |channel_id| + last_channels.each do |channel_id| next if !@@channel_stream[channel_id.to_s] next if current_channels.include?(channel_id) logger.info "channel (#{channel_id}) not longer active, stop thread" @@ -204,7 +204,7 @@ stream all accounts @@channel_stream[channel_id.to_s][:thread].join @@channel_stream[channel_id.to_s][:stream_instance].disconnect @@channel_stream[channel_id.to_s] = false - } + end last_channels = current_channels sleep 20 diff --git a/app/models/channel/assets.rb b/app/models/channel/assets.rb index a61019019..46c044fbd 100644 --- a/app/models/channel/assets.rb +++ b/app/models/channel/assets.rb @@ -40,24 +40,24 @@ returns end end if !access - %w(inbound outbound).each { |key| + %w(inbound outbound).each do |key| if attributes['options'] && attributes['options'][key] && attributes['options'][key]['options'] attributes['options'][key]['options'].delete('password') end - } + end end data[ self.class.to_app_model ][ id ] = attributes end return data if !self['created_by_id'] && !self['updated_by_id'] - %w(created_by_id updated_by_id).each { |local_user_id| + %w(created_by_id updated_by_id).each do |local_user_id| next if !self[ local_user_id ] next if data[ User.to_app_model ] && data[ User.to_app_model ][ self[ local_user_id ] ] user = User.lookup(id: self[ local_user_id ]) next if !user data = user.assets(data) - } + end data end diff --git a/app/models/channel/driver/facebook.rb b/app/models/channel/driver/facebook.rb index 4ec9447c3..910595bf6 100644 --- a/app/models/channel/driver/facebook.rb +++ b/app/models/channel/driver/facebook.rb @@ -31,10 +31,10 @@ class Channel::Driver::Facebook def send(options, fb_object_id, article, _notification = false) access_token = nil - options['pages'].each { |page| + options['pages'].each do |page| next if page['id'].to_s != fb_object_id.to_s access_token = page['access_token'] - } + end if !access_token raise "No access_token found for fb_object_id: #{fb_object_id}" end @@ -66,9 +66,9 @@ class Channel::Driver::Facebook private def get_page(page_id) - @pages.each { |page| + @pages.each do |page| return page if page['id'].to_s == page_id.to_s - } + end nil end @@ -79,14 +79,14 @@ class Channel::Driver::Facebook older_import = 0 older_import_max = 12 - @sync['pages'].each { |page_to_sync_id, page_to_sync_params| + @sync['pages'].each do |page_to_sync_id, page_to_sync_params| page = get_page(page_to_sync_id) next if !page next if page_to_sync_params['group_id'].blank? page_client = Facebook.new(page['access_token']) posts = page_client.client.get_connection('me', 'feed', fields: 'id,from,to,message,created_time,permalink_url,comments{id,from,to,message,created_time}') - posts.each { |post| + posts.each do |post| # ignore older messages if (@channel.created_at - 15.days) > Time.zone.parse(post['created_time']) || older_import >= older_import_max @@ -96,8 +96,8 @@ class Channel::Driver::Facebook end page_client.to_group(post, page_to_sync_params['group_id'], @channel, page) - } - } + end + end true end diff --git a/app/models/channel/driver/twitter.rb b/app/models/channel/driver/twitter.rb index dbb6b2ee2..2a3f60447 100644 --- a/app/models/channel/driver/twitter.rb +++ b/app/models/channel/driver/twitter.rb @@ -184,7 +184,7 @@ returns def stream sleep_on_unauthorized = 61 - 2.times { |loop_count| + 2.times do |loop_count| begin stream_start rescue Twitter::Error::Unauthorized => e @@ -196,7 +196,7 @@ returns raise "Unable to stream, try #{loop_count}, error #{e.inspect}" end end - } + end end def stream_start @@ -207,9 +207,9 @@ returns filter = {} if sync['search'] hashtags = [] - sync['search'].each { |item| + sync['search'].each do |item| hashtags.push item['term'] - } + end filter[:track] = hashtags.join(',') end if sync['mentions'] && sync['mentions']['group_id'] != '' @@ -242,11 +242,11 @@ returns if sync['mentions'] && sync['mentions']['group_id'] != '' hit = false if tweet.user_mentions - tweet.user_mentions.each { |user| + tweet.user_mentions.each do |user| if user.id.to_s == @channel.options['user']['id'].to_s hit = true end - } + end end if hit @stream_client.to_group(tweet, sync['mentions']['group_id'], @channel) @@ -257,14 +257,14 @@ returns # check hashtags if sync['search'] && tweet.hashtags hit = false - sync['search'].each { |item| - tweet.hashtags.each { |hashtag| + sync['search'].each do |item| + tweet.hashtags.each do |hashtag| next if item['term'] !~ /^#/ if item['term'].sub(/^#/, '') == hashtag.text hit = item end - } - } + end + end if hit @stream_client.to_group(tweet, hit['group_id'], @channel) next @@ -275,12 +275,12 @@ returns if sync['search'] hit = false body = tweet.text - sync['search'].each { |item| + sync['search'].each do |item| next if item['term'] =~ /^#/ if body =~ /#{item['term']}/ hit = item end - } + end if hit @stream_client.to_group(tweet, hit['group_id'], @channel) end @@ -293,14 +293,14 @@ returns def fetch_search return if @sync[:search].blank? - @sync[:search].each { |search| + @sync[:search].each do |search| next if search[:term].blank? next if search[:group_id].blank? result_type = search[:type] || 'mixed' Rails.logger.debug " - searching for '#{search[:term]}'" older_import = 0 older_import_max = 20 - @rest_client.client.search(search[:term], result_type: result_type).collect { |tweet| + @rest_client.client.search(search[:term], result_type: result_type).collect do |tweet| next if !track_retweets? && tweet.retweet? # ignore older messages @@ -314,8 +314,8 @@ returns next if Ticket::Article.find_by(message_id: tweet.id) break if @rest_client.tweet_limit_reached(tweet) @rest_client.to_group(tweet, search[:group_id], @channel) - } - } + end + end end def fetch_mentions @@ -324,7 +324,7 @@ returns Rails.logger.debug ' - searching for mentions' older_import = 0 older_import_max = 20 - @rest_client.client.mentions_timeline.each { |tweet| + @rest_client.client.mentions_timeline.each do |tweet| next if !track_retweets? && tweet.retweet? # ignore older messages @@ -336,7 +336,7 @@ returns next if Ticket::Article.find_by(message_id: tweet.id) break if @rest_client.tweet_limit_reached(tweet) @rest_client.to_group(tweet, @sync[:mentions][:group_id], @channel) - } + end end def fetch_direct_messages @@ -345,7 +345,7 @@ returns Rails.logger.debug ' - searching for direct_messages' older_import = 0 older_import_max = 20 - @rest_client.client.direct_messages(full_text: 'true').each { |tweet| + @rest_client.client.direct_messages(full_text: 'true').each do |tweet| # ignore older messages if (@channel.created_at - 15.days) > tweet.created_at.dup.utc || older_import >= older_import_max @@ -356,7 +356,7 @@ returns next if Ticket::Article.find_by(message_id: tweet.id) break if @rest_client.direct_message_limit_reached(tweet) @rest_client.to_group(tweet, @sync[:direct_messages][:group_id], @channel) - } + end end def check_external_credential(options) @@ -376,7 +376,7 @@ returns def own_tweet_already_imported?(tweet) event_time = Time.zone.now sleep 4 - 12.times { |loop_count| + 12.times do |loop_count| if Ticket::Article.find_by(message_id: tweet.id) Rails.logger.debug "Own tweet already imported, skipping tweet #{tweet.id}" return true @@ -387,7 +387,7 @@ returns sleep_time = 5 if sleep_time > 5 Rails.logger.debug "Delay importing own tweets - sleep #{sleep_time} (loop #{loop_count})" sleep sleep_time - } + end if Ticket::Article.find_by(message_id: tweet.id) Rails.logger.debug "Own tweet already imported, skipping tweet #{tweet.id}" diff --git a/app/models/channel/email_parser.rb b/app/models/channel/email_parser.rb index 9b59f8c21..1e24c38d3 100644 --- a/app/models/channel/email_parser.rb +++ b/app/models/channel/email_parser.rb @@ -74,7 +74,7 @@ class Channel::EmailParser mail = Mail.new(msg) # set all headers - mail.header.fields.each { |field| + mail.header.fields.each do |field| # full line, encode, ready for storage begin @@ -89,42 +89,42 @@ class Channel::EmailParser # if we need to access the lines by objects later again data["raw-#{field.name.downcase}".to_sym] = field - } + end # verify content, ignore recipients with non email address - ['to', 'cc', 'delivered-to', 'x-original-to', 'envelope-to'].each { |field| + ['to', 'cc', 'delivered-to', 'x-original-to', 'envelope-to'].each do |field| next if data[field.to_sym].blank? next if data[field.to_sym] =~ /@/ data[field.to_sym] = '' - } + end # get sender with @ / email address from = nil - ['from', 'reply-to', 'return-path'].each { |item| + ['from', 'reply-to', 'return-path'].each do |item| next if data[item.to_sym].blank? next if data[item.to_sym] !~ /@/ from = data[item.to_sym] break if from - } + end # in case of no sender with email address - get sender if !from - ['from', 'reply-to', 'return-path'].each { |item| + ['from', 'reply-to', 'return-path'].each do |item| next if data[item.to_sym].blank? from = data[item.to_sym] break if from - } + end end # set x-any-recipient data['x-any-recipient'.to_sym] = '' - ['to', 'cc', 'delivered-to', 'x-original-to', 'envelope-to'].each { |item| + ['to', 'cc', 'delivered-to', 'x-original-to', 'envelope-to'].each do |item| next if data[item.to_sym].blank? if data['x-any-recipient'.to_sym] != '' data['x-any-recipient'.to_sym] += ', ' end data['x-any-recipient'.to_sym] += mail[item.to_sym].to_s - } + end # set extra headers data = data.merge(Channel::EmailParser.sender_properties(from)) @@ -197,7 +197,7 @@ class Channel::EmailParser # get attachments if mail.parts - mail.parts.each { |part| + mail.parts.each do |part| # protect process to work fine with spam emails, see test/fixtures/mail15.box begin @@ -207,7 +207,7 @@ class Channel::EmailParser attachs = _get_attachment(part, data[:attachments], mail) data[:attachments].concat(attachs) end - } + end end # not multipart email @@ -298,10 +298,10 @@ class Channel::EmailParser # check if sub parts are available if !file.parts.empty? a = [] - file.parts.each { |p| + file.parts.each do |p| attachment = _get_attachment(p, attachments, mail) a.concat(attachment) - } + end return a end @@ -313,7 +313,7 @@ class Channel::EmailParser # get file preferences headers_store = {} - file.header.fields.each { |field| + file.header.fields.each do |field| # full line, encode, ready for storage begin @@ -325,7 +325,7 @@ class Channel::EmailParser rescue => e headers_store[field.name.to_s] = field.raw_value end - } + end # get filename from content-disposition filename = nil @@ -364,16 +364,16 @@ class Channel::EmailParser # generate file name if filename.blank? attachment_count = 0 - (1..1000).each { |count| + (1..1000).each do |count| filename_exists = false filename = 'file-' + count.to_s - attachments.each { |attachment| + attachments.each do |attachment| if attachment[:filename] == filename filename_exists = true end - } + end break if filename_exists == false - } + end end # get mime type @@ -443,9 +443,9 @@ returns p 'ERROR: ' + e.inspect # rubocop:disable Rails/Output Rails.logger.error message Rails.logger.error e - File.open(filename, 'wb') { |file| + File.open(filename, 'wb') do |file| file.write msg - } + end return false if exception == false raise e.inspect + e.backtrace.inspect end @@ -458,10 +458,10 @@ returns # run postmaster pre filter UserInfo.current_user_id = 1 filters = {} - Setting.where(area: 'Postmaster::PreFilter').order(:name).each { |setting| + Setting.where(area: 'Postmaster::PreFilter').order(:name).each do |setting| filters[setting.name] = Kernel.const_get(Setting.get(setting.name)) - } - filters.each { |_prio, backend| + end + filters.each do |_prio, backend| Rails.logger.debug "run postmaster pre filter #{backend}" begin backend.run(channel, mail) @@ -470,7 +470,7 @@ returns Rails.logger.error e.inspect raise e end - } + end # check ignore header if mail['x-zammad-ignore'.to_sym] == 'true' || mail['x-zammad-ignore'.to_sym] == true @@ -608,10 +608,10 @@ returns # run postmaster post filter filters = {} - Setting.where(area: 'Postmaster::PostFilter').order(:name).each { |setting| + Setting.where(area: 'Postmaster::PostFilter').order(:name).each do |setting| filters[setting.name] = Kernel.const_get(Setting.get(setting.name)) - } - filters.each { |_prio, backend| + end + filters.each do |_prio, backend| Rails.logger.debug "run postmaster post filter #{backend}" begin backend.run(channel, mail, ticket, article, session_user) @@ -619,7 +619,7 @@ returns Rails.logger.error "can't run postmaster post filter #{backend}" Rails.logger.error e.inspect end - } + end # return new objects [ticket, article, session_user, mail] @@ -653,14 +653,14 @@ returns return data if from.blank? begin list = Mail::AddressList.new(from) - list.addresses.each { |address| + list.addresses.each do |address| data[:from_email] = address.address data[:from_local] = address.local data[:from_domain] = address.domain data[:from_display_name] = address.display_name || (address.comments && address.comments[0]) break if data[:from_email].present? && data[:from_email] =~ /@/ - } + end rescue => e if from =~ /<>/ && from =~ /<.+?>/ data = sender_properties(from.gsub(/<>/, '')) @@ -694,7 +694,7 @@ returns def set_attributes_by_x_headers(item_object, header_name, mail, suffix = false) # loop all x-zammad-hedaer-* headers - item_object.attributes.each { |key, _value| + item_object.attributes.each do |key, _value| # ignore read only attributes next if key == 'updated_by_id' @@ -712,7 +712,7 @@ returns # only set value on _id if value/reference lookup exists if mail[ header.to_sym ] Rails.logger.info "header #{header} found #{mail[header.to_sym]}" - item_object.class.reflect_on_all_associations.map { |assoc| + item_object.class.reflect_on_all_associations.map do |assoc| next if assoc.name.to_s != key_short @@ -742,7 +742,7 @@ returns # no assoc exists, remove header mail.delete(header.to_sym) - } + end end end @@ -755,7 +755,7 @@ returns Rails.logger.info "header #{header} found #{mail[header.to_sym]}" item_object[key] = mail[header.to_sym] end - } + end end end diff --git a/app/models/channel/filter/bounce_delivery_permanent_failed.rb b/app/models/channel/filter/bounce_delivery_permanent_failed.rb index ecd75f39f..b7b535f90 100644 --- a/app/models/channel/filter/bounce_delivery_permanent_failed.rb +++ b/app/models/channel/filter/bounce_delivery_permanent_failed.rb @@ -9,7 +9,7 @@ module Channel::Filter::BounceDeliveryPermanentFailed return if !mail[:attachments] # remember, do not send notifications to certain recipients again if failed permanent - mail[:attachments].each { |attachment| + mail[:attachments].each do |attachment| next if !attachment[:preferences] next if attachment[:preferences]['Mime-Type'] != 'message/rfc822' next if !attachment[:data] @@ -28,19 +28,19 @@ module Channel::Filter::BounceDeliveryPermanentFailed # get recipient of origin article, if only one - mark this user to not sent notifications anymore recipients = [] if article.sender.name == 'System' || article.sender.name == 'Agent' - %w(to cc).each { |line| + %w(to cc).each do |line| next if article[line].blank? recipients = [] begin list = Mail::AddressList.new(article[line]) - list.addresses.each { |address| + list.addresses.each do |address| next if address.address.blank? recipients.push address.address.downcase - } + end rescue Rails.logger.info "Unable to parse email address in '#{article[line]}'" end - } + end if recipients.count > 1 recipients = [] end @@ -56,16 +56,16 @@ module Channel::Filter::BounceDeliveryPermanentFailed end # set user preferences - recipients.each { |recipient| + recipients.each do |recipient| users = User.where(email: recipient) - users.each { |user| + users.each do |user| next if !user user.preferences[:mail_delivery_failed] = true user.preferences[:mail_delivery_failed_data] = Time.zone.now user.save! - } - } - } + end + end + end true diff --git a/app/models/channel/filter/bounce_follow_up_check.rb b/app/models/channel/filter/bounce_follow_up_check.rb index 872053564..973c72922 100644 --- a/app/models/channel/filter/bounce_follow_up_check.rb +++ b/app/models/channel/filter/bounce_follow_up_check.rb @@ -9,7 +9,7 @@ module Channel::Filter::BounceFollowUpCheck return if !mail[:attachments] return if mail[ 'x-zammad-ticket-id'.to_sym ] - mail[:attachments].each { |attachment| + mail[:attachments].each do |attachment| next if !attachment[:preferences] next if attachment[:preferences]['Mime-Type'] != 'message/rfc822' next if !attachment[:data] @@ -25,7 +25,7 @@ module Channel::Filter::BounceFollowUpCheck mail[ 'x-zammad-is-auto-response'.to_sym ] = true return true - } + end end end diff --git a/app/models/channel/filter/database.rb b/app/models/channel/filter/database.rb index 06077abe7..7b13f8d5f 100644 --- a/app/models/channel/filter/database.rb +++ b/app/models/channel/filter/database.rb @@ -7,11 +7,11 @@ module Channel::Filter::Database # process postmaster filter filters = PostmasterFilter.where(active: true, channel: 'email').order(:name, :created_at) - filters.each { |filter| + filters.each do |filter| Rails.logger.info " process filter #{filter.name} ..." all_matches_ok = true min_one_rule_exists = false - filter[:match].each { |key, meta| + filter[:match].each do |key, meta| begin next if meta.blank? || meta['value'].blank? value = mail[ key.downcase.to_sym ] @@ -37,17 +37,17 @@ module Channel::Filter::Database Rails.logger.error "can't use match rule #{match_rule} on #{value}" Rails.logger.error e.inspect end - } + end next if !min_one_rule_exists next if !all_matches_ok - filter[:perform].each { |key, meta| + filter[:perform].each do |key, meta| next if !Channel::EmailParser.check_attributes_by_x_headers(key, meta['value']) Rails.logger.info " perform '#{key.downcase}' = '#{meta.inspect}'" mail[ key.downcase.to_sym ] = meta['value'] - } - } + end + end end diff --git a/app/models/channel/filter/follow_up_check.rb b/app/models/channel/filter/follow_up_check.rb index b568b6a04..179978187 100644 --- a/app/models/channel/filter/follow_up_check.rb +++ b/app/models/channel/filter/follow_up_check.rb @@ -28,14 +28,14 @@ module Channel::Filter::FollowUpCheck # get ticket# from attachment if setting.include?('attachment') && mail[:attachments] - mail[:attachments].each { |attachment| + mail[:attachments].each do |attachment| next if !attachment[:data] ticket = Ticket::Number.check(attachment[:data]) next if !ticket Rails.logger.debug "Follow up for '##{ticket.number}' in attachment." mail['x-zammad-ticket-id'.to_sym] = ticket.id return true - } + end end # get ticket# from references @@ -54,14 +54,14 @@ module Channel::Filter::FollowUpCheck end if references != '' message_ids = references.split(/\s+/) - message_ids.each { |message_id| + message_ids.each do |message_id| message_id_md5 = Digest::MD5.hexdigest(message_id) article = Ticket::Article.where(message_id_md5: message_id_md5).order('created_at DESC, id DESC').limit(1).first next if !article Rails.logger.debug "Follow up for '##{article.ticket.number}' in references." mail['x-zammad-ticket-id'.to_sym] = article.ticket_id return true - } + end end end @@ -81,7 +81,7 @@ module Channel::Filter::FollowUpCheck end if references != '' message_ids = references.split(/\s+/) - message_ids.each { |message_id| + message_ids.each do |message_id| message_id_md5 = Digest::MD5.hexdigest(message_id) article = Ticket::Article.where(message_id_md5: message_id_md5).order('created_at DESC, id DESC').limit(1).first next if !article @@ -100,7 +100,7 @@ module Channel::Filter::FollowUpCheck Rails.logger.debug "Follow up for '##{article.ticket.number}' in references with same subject as inital article." mail['x-zammad-ticket-id'.to_sym] = article_first.ticket_id return true - } + end end end diff --git a/app/models/channel/filter/follow_up_merged.rb b/app/models/channel/filter/follow_up_merged.rb index 14c273b49..834598ffd 100644 --- a/app/models/channel/filter/follow_up_merged.rb +++ b/app/models/channel/filter/follow_up_merged.rb @@ -25,7 +25,7 @@ module Channel::Filter::FollowUpMerged return if links.blank? merge_ticket = nil - links.each { |link| + links.each do |link| next if link['link_type'] != 'parent' next if link['link_object'] != 'Ticket' @@ -37,7 +37,7 @@ module Channel::Filter::FollowUpMerged merge_ticket = check_ticket break - } + end merge_ticket end end diff --git a/app/models/channel/filter/identify_sender.rb b/app/models/channel/filter/identify_sender.rb index 71634cffe..94cfd6139 100644 --- a/app/models/channel/filter/identify_sender.rb +++ b/app/models/channel/filter/identify_sender.rb @@ -32,7 +32,7 @@ module Channel::Filter::IdentifySender to = 'raw-to'.to_sym if mail[to] && mail[to].addrs items = mail[to].addrs - items.each { |item| + items.each do |item| # skip if recipient is system email next if EmailAddress.find_by(email: item.address.downcase) @@ -43,7 +43,7 @@ module Channel::Filter::IdentifySender email: item.address, ) break - } + end end rescue => e Rails.logger.error 'ERROR: SenderIsSystemAddress: ' + e.inspect @@ -89,12 +89,12 @@ module Channel::Filter::IdentifySender def self.create_recipients(mail) max_count = 40 current_count = 0 - ['raw-to', 'raw-cc'].each { |item| + ['raw-to', 'raw-cc'].each do |item| next if !mail[item.to_sym] begin next if !mail[item.to_sym].addrs items = mail[item.to_sym].addrs - items.each { |address_data| + items.each do |address_data| next if address_data.address.blank? user_create( firstname: address_data.display_name, @@ -103,7 +103,7 @@ module Channel::Filter::IdentifySender ) current_count += 1 return false if current_count == max_count - } + end rescue => e # parse not parseable fields by mail gem like # - Max Kohl | [example.com] @@ -111,7 +111,7 @@ module Channel::Filter::IdentifySender Rails.logger.error 'ERROR: ' + e.inspect Rails.logger.error "ERROR: try it by my self (#{item}): #{mail[item.to_sym]}" recipients = mail[item.to_sym].to_s.split(',') - recipients.each { |recipient| + recipients.each do |recipient| address = nil display_name = nil if recipient =~ /.*<(.+?)>/ @@ -128,9 +128,9 @@ module Channel::Filter::IdentifySender ) current_count += 1 return false if current_count == max_count - } + end end - } + end end def self.user_create(data) @@ -159,12 +159,12 @@ module Channel::Filter::IdentifySender role_ids = Role.signup_role_ids # fillup - %w(firstname lastname).each { |item| + %w(firstname lastname).each do |item| if data[item.to_sym].nil? data[item.to_sym] = '' end data[item.to_sym] = cleanup_name(data[item.to_sym]) - } + end data[:password] = '' data[:active] = true data[:role_ids] = role_ids diff --git a/app/models/channel/filter/monitoring_base.rb b/app/models/channel/filter/monitoring_base.rb index f06d5477e..db73a65e2 100644 --- a/app/models/channel/filter/monitoring_base.rb +++ b/app/models/channel/filter/monitoring_base.rb @@ -31,7 +31,7 @@ class Channel::Filter::MonitoringBase # get mail attibutes like host and state result = {} - mail[:body].gsub(%r{(Service|Host|State|Address|Date/Time|Additional\sInfo|Info):(.+?)\n}i) { |_match| + mail[:body].gsub(%r{(Service|Host|State|Address|Date/Time|Additional\sInfo|Info):(.+?)\n}i) do |_match| key = $1 if key key = key.downcase @@ -41,7 +41,7 @@ class Channel::Filter::MonitoringBase value.strip! end result[key] = value - } + end # check min. params return if result['host'].blank? @@ -68,7 +68,7 @@ class Channel::Filter::MonitoringBase # follow up detection by meta data open_states = Ticket::State.by_category(:open) ticket_ids = Ticket.where(state: open_states).order(created_at: :desc).limit(5000).pluck(:id) - ticket_ids.each { |ticket_id| + ticket_ids.each do |ticket_id| ticket = Ticket.find_by(id: ticket_id) next if !ticket next if !ticket.preferences @@ -89,7 +89,7 @@ class Channel::Filter::MonitoringBase end end return true - } + end # new ticket, set meta data if !mail[ 'x-zammad-ticket-id'.to_sym ] @@ -98,9 +98,9 @@ class Channel::Filter::MonitoringBase end preferences = {} preferences[integration] = result - preferences.each { |key, value| + preferences.each do |key, value| mail[ 'x-zammad-ticket-preferences'.to_sym ][key] = value - } + end end # ignorte states diff --git a/app/models/channel/filter/sender_is_system_address.rb b/app/models/channel/filter/sender_is_system_address.rb index 8e58fe51a..07efc2806 100644 --- a/app/models/channel/filter/sender_is_system_address.rb +++ b/app/models/channel/filter/sender_is_system_address.rb @@ -17,12 +17,12 @@ module Channel::Filter::SenderIsSystemAddress begin return if !mail[form].addrs items = mail[form].addrs - items.each { |item| + items.each do |item| next if !EmailAddress.find_by(email: item.address.downcase) mail['x-zammad-ticket-create-article-sender'.to_sym] = 'Agent' mail['x-zammad-article-sender'.to_sym] = 'Agent' return true - } + end rescue => e Rails.logger.error 'ERROR: SenderIsSystemAddress: ' + e.inspect end diff --git a/app/models/channel/filter/trusted.rb b/app/models/channel/filter/trusted.rb index 74fdf0515..812c4ac68 100644 --- a/app/models/channel/filter/trusted.rb +++ b/app/models/channel/filter/trusted.rb @@ -7,21 +7,21 @@ module Channel::Filter::Trusted # check if trust x-headers if !channel[:trusted] - mail.each { |key, _value| + mail.each do |key, _value| next if key !~ /^x-zammad/i mail.delete(key) - } + end return end # verify values - mail.each { |key, value| + mail.each do |key, value| next if key !~ /^x-zammad/i # no assoc exists, remove header next if Channel::EmailParser.check_attributes_by_x_headers(key, value) mail.delete(key.to_sym) - } + end end end diff --git a/app/models/chat.rb b/app/models/chat.rb index 91844d8e5..f1736329a 100644 --- a/app/models/chat.rb +++ b/app/models/chat.rb @@ -65,21 +65,21 @@ class Chat < ApplicationModel def self.agent_state(user_id) return { state: 'chat_disabled' } if !Setting.get('chat') assets = {} - Chat.where(active: true).each { |chat| + Chat.where(active: true).each do |chat| assets = chat.assets(assets) - } + end active_agent_ids = [] - active_agents.each { |user| + active_agents.each do |user| active_agent_ids.push user.id assets = user.assets(assets) - } + end runningchat_session_list_local = running_chat_session_list - runningchat_session_list_local.each { |session| + runningchat_session_list_local.each do |session| next if !session['user_id'] user = User.lookup(id: session['user_id']) next if !user assets = user.assets(assets) - } + end { waiting_chat_count: waiting_chat_count, waiting_chat_session_list: waiting_chat_session_list, @@ -107,9 +107,9 @@ class Chat < ApplicationModel def self.waiting_chat_session_list sessions = [] - Chat::Session.where(state: ['waiting']).each { |session| + Chat::Session.where(state: ['waiting']).each do |session| sessions.push session.attributes - } + end sessions end @@ -119,9 +119,9 @@ class Chat < ApplicationModel def self.running_chat_session_list sessions = [] - Chat::Session.where(state: ['running']).each { |session| + Chat::Session.where(state: ['running']).each do |session| sessions.push session.attributes - } + end sessions end @@ -131,9 +131,9 @@ class Chat < ApplicationModel def self.available_agents(diff = 2.minutes) agents = {} - Chat::Agent.where(active: true).where('updated_at > ?', Time.zone.now - diff).each { |record| + Chat::Agent.where(active: true).where('updated_at > ?', Time.zone.now - diff).each do |record| agents[record.updated_by_id] = record.concurrent - } + end agents end @@ -143,19 +143,19 @@ class Chat < ApplicationModel def self.active_agents(diff = 2.minutes) users = [] - Chat::Agent.where(active: true).where('updated_at > ?', Time.zone.now - diff).each { |record| + Chat::Agent.where(active: true).where('updated_at > ?', Time.zone.now - diff).each do |record| user = User.lookup(id: record.updated_by_id) next if !user users.push user - } + end users end def self.seads_total(diff = 2.minutes) total = 0 - available_agents(diff).each { |_user_id, concurrent| + available_agents(diff).each do |_user_id, concurrent| total += concurrent - } + end total end @@ -178,14 +178,14 @@ optional you can ignore it for dedecated user def self.broadcast_agent_state_update(ignore_user_id = nil) # send broadcast to agents - Chat::Agent.where('active = ? OR updated_at > ?', true, Time.zone.now - 8.hours).each { |item| + Chat::Agent.where('active = ? OR updated_at > ?', true, Time.zone.now - 8.hours).each do |item| next if item.updated_by_id == ignore_user_id data = { event: 'chat_status_agent', data: Chat.agent_state(item.updated_by_id), } Sessions.send_to(item.updated_by_id, data) - } + end end =begin @@ -200,7 +200,7 @@ broadcast new customer queue position to all waiting customers # send position update to other waiting sessions position = 0 - Chat::Session.where(state: 'waiting').order('created_at ASC').each { |local_chat_session| + Chat::Session.where(state: 'waiting').order('created_at ASC').each do |local_chat_session| position += 1 data = { event: 'chat_session_queue', @@ -211,7 +211,7 @@ broadcast new customer queue position to all waiting customers }, } local_chat_session.send_to_recipients(data) - } + end end =begin @@ -227,10 +227,10 @@ optional you can put the max oldest chat entries =end def self.cleanup(diff = 3.months) - Chat::Session.where(state: 'closed').where('updated_at < ?', Time.zone.now - diff).each { |chat_session| + Chat::Session.where(state: 'closed').where('updated_at < ?', Time.zone.now - diff).each do |chat_session| Chat::Message.where(chat_session_id: chat_session.id).delete_all chat_session.destroy - } + end true end @@ -248,7 +248,7 @@ optional you can put the max oldest chat sessions as argument =end def self.cleanup_close(diff = 5.minutes) - Chat::Session.where.not(state: 'closed').where('updated_at < ?', Time.zone.now - diff).each { |chat_session| + Chat::Session.where.not(state: 'closed').where('updated_at < ?', Time.zone.now - diff).each do |chat_session| next if chat_session.recipients_active? chat_session.state = 'closed' chat_session.save @@ -260,7 +260,7 @@ optional you can put the max oldest chat sessions as argument }, } chat_session.send_to_recipients(message) - } + end true end diff --git a/app/models/chat/session.rb b/app/models/chat/session.rb index 7f7b41e7b..70cd0d818 100644 --- a/app/models/chat/session.rb +++ b/app/models/chat/session.rb @@ -22,29 +22,29 @@ class Chat::Session < ApplicationModel return true if !preferences return true if !preferences[:participants] count = 0 - preferences[:participants].each { |client_id| + preferences[:participants].each do |client_id| next if !Sessions.session_exists?(client_id) count += 1 - } + end return true if count >= 2 false end def send_to_recipients(message, ignore_client_id = nil) - preferences[:participants].each { |local_client_id| + preferences[:participants].each do |local_client_id| next if local_client_id == ignore_client_id Sessions.send(local_client_id, message) - } + end true end def position return if state != 'waiting' position = 0 - Chat::Session.where(state: 'waiting').order(created_at: :asc).each { |chat_session| + Chat::Session.where(state: 'waiting').order(created_at: :asc).each do |chat_session| position += 1 break if chat_session.id == id - } + end position end @@ -52,22 +52,22 @@ class Chat::Session < ApplicationModel chat_session = Chat::Session.find_by(session_id: session_id) return if !chat_session session_attributes = [] - Chat::Message.where(chat_session_id: chat_session.id).order(created_at: :asc).each { |message| + Chat::Message.where(chat_session_id: chat_session.id).order(created_at: :asc).each do |message| session_attributes.push message.attributes - } + end session_attributes end def self.active_chats_by_user_id(user_id) actice_sessions = [] - Chat::Session.where(state: 'running', user_id: user_id).order(created_at: :asc).each { |session| + Chat::Session.where(state: 'running', user_id: user_id).order(created_at: :asc).each do |session| session_attributes = session.attributes session_attributes['messages'] = [] - Chat::Message.where(chat_session_id: session.id).order(created_at: :asc).each { |message| + Chat::Message.where(chat_session_id: session.id).order(created_at: :asc).each do |message| session_attributes['messages'].push message.attributes - } + end actice_sessions.push session_attributes - } + end actice_sessions end end diff --git a/app/models/concerns/can_uniq_name.rb b/app/models/concerns/can_uniq_name.rb index e00baf348..e3cd8cee8 100644 --- a/app/models/concerns/can_uniq_name.rb +++ b/app/models/concerns/can_uniq_name.rb @@ -21,10 +21,10 @@ returns def generate_uniq_name(name) return name if !exists?(name: name) - (1..100).each { |counter| + (1..100).each do |counter| name = "#{name}_#{counter}" break if !exists?(name: name) - } + end name end end diff --git a/app/models/concerns/has_activity_stream_log.rb b/app/models/concerns/has_activity_stream_log.rb index 95bd65c29..a4a4cdee6 100644 --- a/app/models/concerns/has_activity_stream_log.rb +++ b/app/models/concerns/has_activity_stream_log.rb @@ -38,11 +38,11 @@ log object update activity stream, if configured - will be executed automaticall ignored_attributes += %i(created_at updated_at created_by_id updated_by_id) log = false - saved_changes.each { |key, _value| + saved_changes.each do |key, _value| next if ignored_attributes.include?(key.to_sym) log = true - } + end return true if !log activity_stream_log('update', self['updated_by_id']) true diff --git a/app/models/concerns/has_history.rb b/app/models/concerns/has_history.rb index 4aa09a73c..a351fe16b 100644 --- a/app/models/concerns/has_history.rb +++ b/app/models/concerns/has_history.rb @@ -41,11 +41,11 @@ log object update history with all updated attributes, if configured - will be e # new record also triggers update, so ignore new records changes = saved_changes if history_changes_last_done - history_changes_last_done.each { |key, value| + history_changes_last_done.each do |key, value| if changes.key?(key) && changes[key] == value changes.delete(key) end - } + end end self.history_changes_last_done = changes #logger.info 'updated ' + self.changes.inspect @@ -55,7 +55,7 @@ log object update history with all updated attributes, if configured - will be e ignored_attributes = self.class.instance_variable_get(:@history_attributes_ignored) || [] ignored_attributes += %i(created_at updated_at created_by_id updated_by_id) - changes.each { |key, value| + changes.each do |key, value| next if ignored_attributes.include?(key.to_sym) @@ -104,7 +104,7 @@ log object update history with all updated attributes, if configured - will be e } #logger.info "HIST NEW #{self.class.to_s}.find(#{self.id}) #{data.inspect}" history_log('updated', updated_by_id, data) - } + end end =begin @@ -212,7 +212,7 @@ returns # get related objects history = History.list(self.class.name, self['id'], nil, true) - history[:list].each { |item| + history[:list].each do |item| record = Kernel.const_get(item['object']).find(item['o_id']) history[:assets] = record.assets(history[:assets]) @@ -221,7 +221,7 @@ returns record = Kernel.const_get(item['related_object']).find(item['related_o_id']) history[:assets] = record.assets(history[:assets]) end - } + end { history: history[:list], assets: history[:assets], diff --git a/app/models/concerns/has_search_index_backend.rb b/app/models/concerns/has_search_index_backend.rb index 038ceb0f6..7e4bb998b 100644 --- a/app/models/concerns/has_search_index_backend.rb +++ b/app/models/concerns/has_search_index_backend.rb @@ -84,11 +84,11 @@ returns def search_index_data attributes = {} - %w(name note).each { |key| + %w(name note).each do |key| next if !self[key] next if self[key].respond_to?('blank?') && self[key].blank? attributes[key] = self[key] - } + end return true if attributes.blank? attributes end @@ -127,7 +127,7 @@ reload search index with full data tolerance = 5 tolerance_count = 0 ids = all.order('created_at DESC').pluck(:id) - ids.each { |item_id| + ids.each do |item_id| item = find(item_id) next if item.ignore_search_indexing?(:destroy) begin @@ -137,7 +137,7 @@ reload search index with full data tolerance_count += 1 raise "Unable to send #{item.class}.find(#{item.id}).search_index_update_backend backend: #{e.inspect}" if tolerance_count == tolerance end - } + end end end end diff --git a/app/models/cti/caller_id.rb b/app/models/cti/caller_id.rb index 22e77afcc..ad8930044 100644 --- a/app/models/cti/caller_id.rb +++ b/app/models/cti/caller_id.rb @@ -44,7 +44,7 @@ returns def self.lookup(caller_id) result = [] - ['known', 'maybe', nil].each { |level| + ['known', 'maybe', nil].each do |level| search_params = { caller_id: caller_id, @@ -55,11 +55,11 @@ returns end caller_ids = Cti::CallerId.select('MAX(id) as caller_id').where(search_params).group(:user_id).order('caller_id DESC').limit(20).map(&:caller_id) - Cti::CallerId.where(id: caller_ids).order(id: :desc).each { |record| + Cti::CallerId.where(id: caller_ids).order(id: :desc).each do |record| result.push record - } + end break if result.present? - } + end result end @@ -73,11 +73,11 @@ returns map = config level = nil model = nil - map.each { |item| + map.each do |item| next if item[:model] != record.class level = item[:level] model = item[:model] - } + end return if !level || !model build_item(record, model, level) end @@ -108,17 +108,17 @@ returns # get caller ids caller_ids = [] attributes = record.attributes - attributes.each { |_attribute, value| + attributes.each do |_attribute, value| next if value.class != String next if value.empty? local_caller_ids = Cti::CallerId.extract_numbers(value) next if local_caller_ids.empty? caller_ids = caller_ids.concat(local_caller_ids) - } + end # store caller ids Cti::CallerId.where(object: model.to_s, o_id: record.id).destroy_all - caller_ids.each { |caller_id| + caller_ids.each do |caller_id| Cti::CallerId.maybe_add( caller_id: caller_id, level: level, @@ -126,7 +126,7 @@ returns o_id: record.id, user_id: user_id, ) - } + end true end @@ -139,13 +139,13 @@ returns def self.rebuild transaction do delete_all - config.each { |item| + config.each do |item| level = item[:level] model = item[:model] item[:model].find_each(batch_size: 500) do |record| build_item(record, model, level) end - } + end end end @@ -221,7 +221,7 @@ returns preferences_maybe = {} preferences_maybe[direction] = [] - lookup(extract_numbers(caller_id)).each { |record| + lookup(extract_numbers(caller_id)).each do |record| if record.level == 'known' preferences_known[direction].push record.attributes else @@ -247,7 +247,7 @@ returns end from_comment_maybe += comment end - } + end return [from_comment_known, preferences_known] if !from_comment_known.empty? return ["maybe #{from_comment_maybe}", preferences_maybe] if !from_comment_maybe.empty? nil diff --git a/app/models/cti/log.rb b/app/models/cti/log.rb index d151d3d11..4f03057b4 100644 --- a/app/models/cti/log.rb +++ b/app/models/cti/log.rb @@ -247,18 +247,18 @@ returns # add assets assets = {} - list.each { |item| + list.each do |item| next if !item.preferences - %w(from to).each { |direction| + %w(from to).each do |direction| next if !item.preferences[direction] - item.preferences[direction].each { |caller_id| + item.preferences[direction].each do |caller_id| next if !caller_id['user_id'] user = User.lookup(id: caller_id['user_id']) next if !user assets = user.assets(assets) - } - } - } + end + end + end { list: list, @@ -344,7 +344,7 @@ Cti::Log.process( def push_event users = User.with_permissions('cti.agent') - users.each { |user| + users.each do |user| # send notify about event Sessions.send_to( @@ -354,14 +354,14 @@ Cti::Log.process( data: self, }, ) - } + end end def push_caller_list list = Cti::Log.log users = User.with_permissions('cti.agent') - users.each { |user| + users.each do |user| # send notify on create/update/delete Sessions.send_to( @@ -371,7 +371,7 @@ Cti::Log.process( data: list, }, ) - } + end end =begin diff --git a/app/models/email_address.rb b/app/models/email_address.rb index 59dee0acd..dc2affea8 100644 --- a/app/models/email_address.rb +++ b/app/models/email_address.rb @@ -24,7 +24,7 @@ check and if channel not exists reset configured channels for email addresses =end def self.channel_cleanup - EmailAddress.all.each { |email_address| + EmailAddress.all.each do |email_address| # set to active if channel exists if email_address.channel_id && Channel.find_by(id: email_address.channel_id) @@ -37,7 +37,7 @@ check and if channel not exists reset configured channels for email addresses # set in inactive if channel not longer exists next if !email_address.active email_address.save! - } + end end private @@ -68,9 +68,9 @@ check and if channel not exists reset configured channels for email addresses # delete group.email_address_id reference if email address get's deleted def delete_group_reference - Group.where(email_address_id: id).each { |group| + Group.where(email_address_id: id).each do |group| group.update!(email_address_id: nil) - } + end end # keep email email address is of inital group filled diff --git a/app/models/external_sync.rb b/app/models/external_sync.rb index 88413f96a..b43bbe5c5 100644 --- a/app/models/external_sync.rb +++ b/app/models/external_sync.rb @@ -8,7 +8,7 @@ class ExternalSync < ApplicationModel def changed?(object:, previous_changes: {}, current_changes:) changed = false previous_changes ||= {} - current_changes.each { |attribute, value| + current_changes.each do |attribute, value| next if !object.attributes.key?(attribute.to_s) next if object[attribute] == value next if object[attribute].present? && object[attribute] != previous_changes[attribute] @@ -19,7 +19,7 @@ class ExternalSync < ApplicationModel rescue => e Rails.logger.error "ERROR: Unable to assign attribute #{attribute} to object #{object.class.name}: #{e.inspect}" end - } + end changed end @@ -32,7 +32,7 @@ class ExternalSync < ApplicationModel end result = {} - mapping.each { |remote_key, local_key| + mapping.each do |remote_key, local_key| local_key_sym = local_key.to_sym @@ -40,7 +40,7 @@ class ExternalSync < ApplicationModel value = extract(remote_key, information_source) next if value.blank? result[local_key_sym] = value - } + end result end diff --git a/app/models/job/assets.rb b/app/models/job/assets.rb index b02178ba3..fbfd4a15f 100644 --- a/app/models/job/assets.rb +++ b/app/models/job/assets.rb @@ -36,13 +36,13 @@ returns data = assets_of_selector('condition', data) data = assets_of_selector('perform', data) end - %w(created_by_id updated_by_id).each { |local_user_id| + %w(created_by_id updated_by_id).each do |local_user_id| next if !self[ local_user_id ] next if data[ User.to_app_model ][ self[ local_user_id ] ] user = User.lookup(id: self[ local_user_id ]) next if !user data = user.assets(data) - } + end data end end diff --git a/app/models/karma/activity_log.rb b/app/models/karma/activity_log.rb index a97a379e8..f36f97f7a 100644 --- a/app/models/karma/activity_log.rb +++ b/app/models/karma/activity_log.rb @@ -74,7 +74,7 @@ remove whole karma activity log of an object def self.latest(user, limit = 12) result = [] logs = Karma::ActivityLog.where(user_id: user.id).order(id: :desc).limit(limit) - logs.each { |log| + logs.each do |log| last = result.last if last && last[:object_id] == log.object_id && last[:o_id] == log.o_id && last[:created_at] == log.created_at comment = { @@ -97,7 +97,7 @@ remove whole karma activity log of an object created_at: log.created_at, } result.push data - } + end result end diff --git a/app/models/karma/user.rb b/app/models/karma/user.rb index cb971373a..627984492 100644 --- a/app/models/karma/user.rb +++ b/app/models/karma/user.rb @@ -30,14 +30,14 @@ class Karma::User < ApplicationModel def self.level_by_score(score) level = nil karma_levels = Setting.get('karma_levels') - karma_levels.each { |local_level| + karma_levels.each do |local_level| if !level level = local_level[:name] end next if local_level[:start] && score < local_level[:start] next if local_level[:end] && score > local_level[:end] level = local_level[:name] - } + end level end diff --git a/app/models/link.rb b/app/models/link.rb index 01186d59e..0eca0cac6 100644 --- a/app/models/link.rb +++ b/app/models/link.rb @@ -31,25 +31,25 @@ class Link < ApplicationModel 'link_object_source_id = ? AND link_object_source_value = ?', linkobject.id, data[:link_object_value] ) - list.each { |item| + list.each do |item| link = {} link['link_type'] = @map[ Link::Type.find( item.link_type_id ).name ] link['link_object'] = Link::Object.find( item.link_object_target_id ).name link['link_object_value'] = item.link_object_target_value items.push link - } + end # get links for the other site list = Link.where( 'link_object_target_id = ? AND link_object_target_value = ?', linkobject.id, data[:link_object_value] ) - list.each { |item| + list.each do |item| link = {} link['link_type'] = Link::Type.find( item.link_type_id ).name link['link_object'] = Link::Object.find( item.link_object_source_id ).name link['link_object_value'] = item.link_object_source_value items.push link - } + end items end diff --git a/app/models/locale.rb b/app/models/locale.rb index 9381ba46a..4ce319646 100644 --- a/app/models/locale.rb +++ b/app/models/locale.rb @@ -116,14 +116,14 @@ all: private_class_method def self.to_database(data) ActiveRecord::Base.transaction do - data.each { |locale| + data.each do |locale| exists = Locale.find_by(locale: locale['locale']) if exists exists.update!(locale.symbolize_keys!) else Locale.create!(locale.symbolize_keys!) end - } + end end end diff --git a/app/models/object_manager/attribute.rb b/app/models/object_manager/attribute.rb index 3985f9f7e..97183e5c1 100644 --- a/app/models/object_manager/attribute.rb +++ b/app/models/object_manager/attribute.rb @@ -29,12 +29,12 @@ list of all attributes result = ObjectManager::Attribute.all.order('position ASC, name ASC') attributes = [] assets = {} - result.each { |item| + result.each do |item| attribute = item.attributes attribute[:object] = ObjectLookup.by_id(item.object_lookup_id) attribute.delete('object_lookup_id') attributes.push attribute - } + end attributes end @@ -279,11 +279,11 @@ possible types # if data_option has changed, store it for next migration if !force - [:name, :display, :data_type, :position, :active].each { |key| + [:name, :display, :data_type, :position, :active].each do |key| next if record[key] == data[key] data[:to_config] = true break - } + end if record[:data_option] != data[:data_option] # do we need a database migration? @@ -298,9 +298,9 @@ possible types end # update attributes - data.each { |key, value| + data.each do |key, value| record[key.to_sym] = value - } + end # check editable & name if !force @@ -434,7 +434,7 @@ returns: to_delete: false, ).order('position ASC, name ASC') attributes = [] - result.each { |item| + result.each do |item| data = { name: item.name, display: item.display, @@ -444,32 +444,32 @@ returns: if item.data_option[:permission] && item.data_option[:permission].any? next if !user hint = false - item.data_option[:permission].each { |permission| + item.data_option[:permission].each do |permission| next if !user.permissions?(permission) hint = true break - } + end next if !hint end if item.screens data[:screen] = {} - item.screens.each { |screen, permission_options| + item.screens.each do |screen, permission_options| data[:screen][screen] = {} - permission_options.each { |permission, options| + permission_options.each do |permission, options| if permission == '-all-' data[:screen][screen] = options elsif user && user.permissions?(permission) data[:screen][screen] = options end - } - } + end + end end if item.data_option data = data.merge(item.data_option.symbolize_keys) end attributes.push data - } + end attributes end @@ -492,9 +492,9 @@ returns: def self.by_object_as_hash(object, user) list = by_object(object, user) hash = {} - list.each { |item| + list.each do |item| hash[ item[:name] ] = item - } + end hash end @@ -512,13 +512,13 @@ returns def self.discard_changes ObjectManager::Attribute.where('to_create = ?', true).each(&:destroy) - ObjectManager::Attribute.where('to_delete = ? OR to_config = ?', true, true).each { |attribute| + ObjectManager::Attribute.where('to_delete = ? OR to_config = ?', true, true).each do |attribute| attribute.to_migrate = false attribute.to_delete = false attribute.to_config = false attribute.data_option_new = {} attribute.save - } + end true end @@ -576,7 +576,7 @@ to send no browser reload event, pass false # check if field already exists execute_db_count = 0 execute_config_count = 0 - migrations.each { |attribute| + migrations.each do |attribute| model = Kernel.const_get(attribute.object_lookup.name) # remove field @@ -698,7 +698,7 @@ to send no browser reload event, pass false reset_database_info(model) execute_db_count += 1 - } + end # sent maintenance message to clients if send_event @@ -783,10 +783,10 @@ to send no browser reload event, pass false end if data_type == 'integer' - [:min, :max].each { |item| + [:min, :max].each do |item| raise "Need data_option[#{item.inspect}] param" if !data_option[item] raise "Invalid data_option[#{item.inspect}] param #{data_option[item]}" if data_option[item].to_s !~ /^\d+?$/ - } + end end if data_type == 'select' || data_type == 'tree_select' || data_type == 'checkbox' diff --git a/app/models/observer/organization/ref_object_touch.rb b/app/models/observer/organization/ref_object_touch.rb index e48ab63c6..3571ae50b 100644 --- a/app/models/observer/organization/ref_object_touch.rb +++ b/app/models/observer/organization/ref_object_touch.rb @@ -24,20 +24,20 @@ class Observer::Organization::RefObjectTouch < ActiveRecord::Observer return true if User.where(organization_id: record.id).count > 100 # touch organizations tickets - Ticket.select('id').where(organization_id: record.id).pluck(:id).each { |ticket_id| + Ticket.select('id').where(organization_id: record.id).pluck(:id).each do |ticket_id| ticket = Ticket.find(ticket_id) ticket.with_lock do ticket.touch end - } + end # touch current members - User.select('id').where(organization_id: record.id).pluck(:id).each { |user_id| + User.select('id').where(organization_id: record.id).pluck(:id).each do |user_id| user = User.find(user_id) user.with_lock do user.touch end - } + end true end end diff --git a/app/models/observer/sla/ticket_rebuild_escalation.rb b/app/models/observer/sla/ticket_rebuild_escalation.rb index c267718ec..37503fc11 100644 --- a/app/models/observer/sla/ticket_rebuild_escalation.rb +++ b/app/models/observer/sla/ticket_rebuild_escalation.rb @@ -37,11 +37,11 @@ class Observer::Sla::TicketRebuildEscalation < ActiveRecord::Observer else %w(timezone business_hours default ical_url public_holidays) end - fields_to_check.each { |item| + fields_to_check.each do |item| next if !record.saved_change_to_attribute(item) next if record.saved_change_to_attribute(item)[0] == record.saved_change_to_attribute(item)[1] changed = true - } + end return true if !changed _rebuild(record) diff --git a/app/models/observer/ticket/article/communicate_email/background_job.rb b/app/models/observer/ticket/article/communicate_email/background_job.rb index 6e3c51454..15d4d6d97 100644 --- a/app/models/observer/ticket/article/communicate_email/background_job.rb +++ b/app/models/observer/ticket/article/communicate_email/background_job.rb @@ -90,7 +90,7 @@ class Observer::Ticket::Article::CommunicateEmail::BackgroundJob # add history record recipient_list = '' - [:to, :cc].each { |key| + [:to, :cc].each do |key| next if !record[key] next if record[key] == '' @@ -99,7 +99,7 @@ class Observer::Ticket::Article::CommunicateEmail::BackgroundJob recipient_list += ',' end recipient_list += record[key] - } + end Rails.logger.info "Send email to: '#{recipient_list}' (from #{record.from})" @@ -130,7 +130,7 @@ class Observer::Ticket::Article::CommunicateEmail::BackgroundJob if local_record.preferences['delivery_retry'] > 3 recipient_list = '' - [:to, :cc].each { |key| + [:to, :cc].each do |key| next if !local_record[key] next if local_record[key] == '' @@ -139,7 +139,7 @@ class Observer::Ticket::Article::CommunicateEmail::BackgroundJob recipient_list += ',' end recipient_list += local_record[key] - } + end # reopen ticket and notify agent Observer::Transaction.reset diff --git a/app/models/observer/ticket/article/communicate_telegram/background_job.rb b/app/models/observer/ticket/article/communicate_telegram/background_job.rb index 0922b639a..48791ee50 100644 --- a/app/models/observer/ticket/article/communicate_telegram/background_job.rb +++ b/app/models/observer/ticket/article/communicate_telegram/background_job.rb @@ -30,14 +30,14 @@ class Observer::Ticket::Article::CommunicateTelegram::BackgroundJob api = TelegramAPI.new(channel.options[:api_token]) chat_id = ticket.preferences[:telegram][:chat_id] result = api.sendMessage(chat_id, article.body) - article.attachments.each { |file| + article.attachments.each do |file| parts = file.filename.split(/^(.*)(\..+?)$/) t = Tempfile.new([parts[1], parts[2]]) t.binmode t.write(file.content) t.rewind api.sendDocument(chat_id, t.path.to_s) - } + end rescue => e log_error(article, e.message) return diff --git a/app/models/observer/ticket/article/communicate_twitter/background_job.rb b/app/models/observer/ticket/article/communicate_twitter/background_job.rb index 55e752aaf..fbd77f341 100644 --- a/app/models/observer/ticket/article/communicate_twitter/background_job.rb +++ b/app/models/observer/ticket/article/communicate_twitter/background_job.rb @@ -56,13 +56,13 @@ class Observer::Ticket::Article::CommunicateTwitter::BackgroundJob if tweet.user_mentions to = '' mention_ids = [] - tweet.user_mentions.each { |user| + tweet.user_mentions.each do |user| if to != '' to += ' ' end to += "@#{user.screen_name}" mention_ids.push user.id - } + end article.to = to article.preferences['twitter'] = { mention_ids: mention_ids, diff --git a/app/models/observer/ticket/online_notification_seen/background_job.rb b/app/models/observer/ticket/online_notification_seen/background_job.rb index 237c3adf9..43e3542b8 100644 --- a/app/models/observer/ticket/online_notification_seen/background_job.rb +++ b/app/models/observer/ticket/online_notification_seen/background_job.rb @@ -9,7 +9,7 @@ class Observer::Ticket::OnlineNotificationSeen::BackgroundJob # set all online notifications to seen Transaction.execute do ticket = Ticket.lookup(id: @ticket_id) - OnlineNotification.list_by_object('Ticket', @ticket_id).each { |notification| + OnlineNotification.list_by_object('Ticket', @ticket_id).each do |notification| next if notification.seen seen = ticket.online_notification_seen_state(notification.user_id) next if !seen @@ -17,7 +17,7 @@ class Observer::Ticket::OnlineNotificationSeen::BackgroundJob notification.seen = true notification.updated_by_id = @user_id notification.save! - } + end end end end diff --git a/app/models/observer/transaction.rb b/app/models/observer/transaction.rb index 74754a4b8..15254620b 100644 --- a/app/models/observer/transaction.rb +++ b/app/models/observer/transaction.rb @@ -31,26 +31,26 @@ class Observer::Transaction < ActiveRecord::Observer # get asyn backends sync_backends = [] - Setting.where(area: 'Transaction::Backend::Sync').order(:name).each { |setting| + Setting.where(area: 'Transaction::Backend::Sync').order(:name).each do |setting| backend = Setting.get(setting.name) next if params[:disable] && params[:disable].include?(backend) sync_backends.push Kernel.const_get(backend) - } + end # get uniq objects list_objects = get_uniq_changes(list) - list_objects.each { |_object, objects| - objects.each { |_id, item| + list_objects.each do |_object, objects| + objects.each do |_id, item| # execute sync backends - sync_backends.each { |backend| + sync_backends.each do |backend| execute_singel_backend(backend, item, params) - } + end # execute async backends Delayed::Job.enqueue(Transaction::BackgroundJob.new(item, params)) - } - } + end + end end def self.execute_singel_backend(backend, item, params) @@ -115,7 +115,7 @@ class Observer::Transaction < ActiveRecord::Observer def self.get_uniq_changes(events) list_objects = {} - events.each { |event| + events.each do |event| # simulate article create as ticket update article = nil @@ -159,13 +159,13 @@ class Observer::Transaction < ActiveRecord::Observer if !store[:changes] store[:changes] = event[:changes] else - event[:changes].each { |key, value| + event[:changes].each do |key, value| if !store[:changes][key] store[:changes][key] = value else store[:changes][key][1] = value[1] end - } + end end end @@ -173,7 +173,7 @@ class Observer::Transaction < ActiveRecord::Observer if article store[:article_id] = article.id end - } + end list_objects end @@ -201,7 +201,7 @@ class Observer::Transaction < ActiveRecord::Observer # ignore certain attributes real_changes = {} - record.changes_to_save.each { |key, value| + record.changes_to_save.each do |key, value| next if key == 'updated_at' next if key == 'first_response_at' next if key == 'close_at' @@ -212,7 +212,7 @@ class Observer::Transaction < ActiveRecord::Observer next if key == 'create_article_type_id' next if key == 'create_article_sender_id' real_changes[key] = value - } + end # do not send anything if nothing has changed return true if real_changes.empty? diff --git a/app/models/observer/user/geo.rb b/app/models/observer/user/geo.rb index b4bbd97c3..c65c00923 100644 --- a/app/models/observer/user/geo.rb +++ b/app/models/observer/user/geo.rb @@ -24,16 +24,16 @@ class Observer::User::Geo < ActiveRecord::Observer return if !current current_location = {} - location.each { |item| + location.each do |item| current_location[item] = current[item] - } + end end # get full address next_location = {} - location.each { |item| + location.each do |item| next_location[item] = record[item] - } + end # return if address hasn't changed and geo data is already available return if (current_location == next_location) && record.preferences['lat'] && record.preferences['lng'] @@ -46,13 +46,13 @@ class Observer::User::Geo < ActiveRecord::Observer def geo_update(record) address = '' location = %w(address street zip city country) - location.each { |item| + location.each do |item| next if record[item].blank? if address.present? address += ', ' end address += record[item] - } + end # return if no address is given return if address.blank? diff --git a/app/models/observer/user/ref_object_touch.rb b/app/models/observer/user/ref_object_touch.rb index 53352b677..3c828cb5d 100644 --- a/app/models/observer/user/ref_object_touch.rb +++ b/app/models/observer/user/ref_object_touch.rb @@ -46,10 +46,10 @@ class Observer::User::RefObjectTouch < ActiveRecord::Observer end # touch old/current customer - member_ids.uniq.each { |user_id| + member_ids.uniq.each do |user_id| next if user_id == record.id User.find(user_id).touch - } + end true end end diff --git a/app/models/observer/user/ticket_organization.rb b/app/models/observer/user/ticket_organization.rb index fe3d155da..dc60f967d 100644 --- a/app/models/observer/user/ticket_organization.rb +++ b/app/models/observer/user/ticket_organization.rb @@ -19,12 +19,12 @@ class Observer::User::TicketOrganization < ActiveRecord::Observer # update last 100 tickets of user tickets = Ticket.where(customer_id: record.id).limit(100) - tickets.each { |ticket| + tickets.each do |ticket| if ticket.organization_id != record.organization_id ticket.organization_id = record.organization_id ticket.save end - } + end end end diff --git a/app/models/online_notification.rb b/app/models/online_notification.rb index b46c62107..e50229c50 100644 --- a/app/models/online_notification.rb +++ b/app/models/online_notification.rb @@ -218,9 +218,9 @@ returns: def self.all_seen?(object, o_id) notifications = OnlineNotification.list_by_object(object, o_id) - notifications.each { |onine_notification| + notifications.each do |onine_notification| return false if !onine_notification['seen'] - } + end true end @@ -240,14 +240,14 @@ returns: def self.exists?(user, object, o_id, type, created_by_user, seen) # rubocop:enable Metrics/ParameterLists notifications = OnlineNotification.list(user, 10) - notifications.each { |notification| + notifications.each do |notification| next if notification['o_id'] != o_id next if notification['object'] != object next if notification['type'] != type next if notification['created_by_id'] != created_by_user.id next if notification['seen'] != seen return true - } + end false end @@ -269,7 +269,7 @@ with dedicated times def self.cleanup(max_age = Time.zone.now - 9.months, max_own_seen = Time.zone.now - 10.minutes, max_auto_seen = Time.zone.now - 8.hours) OnlineNotification.where('created_at < ?', max_age).delete_all - OnlineNotification.where('seen = ? AND updated_at < ?', true, max_own_seen).each { |notification| + OnlineNotification.where('seen = ? AND updated_at < ?', true, max_own_seen).each do |notification| # delete own "seen" notificatons after 1 hour next if notification.user_id == notification.updated_by_id && notification.updated_at > max_own_seen @@ -278,10 +278,10 @@ with dedicated times next if notification.user_id != notification.updated_by_id && notification.updated_at > max_auto_seen notification.delete - } + end # notify all agents - User.with_permissions('ticket.agent').each { |user| + User.with_permissions('ticket.agent').each do |user| Sessions.send_to( user.id, { @@ -290,7 +290,7 @@ with dedicated times } ) sleep 2 # slow down client requests - } + end true end diff --git a/app/models/organization/assets.rb b/app/models/organization/assets.rb index d0108676f..d500a5392 100644 --- a/app/models/organization/assets.rb +++ b/app/models/organization/assets.rb @@ -45,23 +45,23 @@ returns if local_attributes['member_ids'].count > 100 local_attributes['member_ids'] = local_attributes['member_ids'].sort[0, 100] end - local_attributes['member_ids'].each { |local_user_id| + local_attributes['member_ids'].each do |local_user_id| next if data[ app_model_user ][ local_user_id ] user = User.lookup(id: local_user_id) next if !user data = user.assets(data) - } + end end data[ app_model_organization ][ id ] = local_attributes end - %w(created_by_id updated_by_id).each { |local_user_id| + %w(created_by_id updated_by_id).each do |local_user_id| next if !self[ local_user_id ] next if data[ app_model_user ][ self[ local_user_id ] ] user = User.lookup(id: self[ local_user_id ]) next if !user data = user.assets(data) - } + end data end end diff --git a/app/models/organization/search.rb b/app/models/organization/search.rb index 42a8dd1ac..a87c1969c 100644 --- a/app/models/organization/search.rb +++ b/app/models/organization/search.rb @@ -60,11 +60,11 @@ returns if SearchIndexBackend.enabled? items = SearchIndexBackend.search(query, limit, 'Organization') organizations = [] - items.each { |item| + items.each do |item| organization = Organization.lookup(id: item[:id]) next if !organization organizations.push organization - } + end return organizations end @@ -80,19 +80,19 @@ returns organizations_by_user = Organization.select('DISTINCT(organizations.id), organizations.name').joins('LEFT OUTER JOIN users ON users.organization_id = organizations.id').where( 'users.firstname LIKE ? or users.lastname LIKE ? or users.email LIKE ?', "%#{query}%", "%#{query}%", "%#{query}%" ).order('organizations.name').limit(limit) - organizations_by_user.each { |organization_by_user| + organizations_by_user.each do |organization_by_user| organization_exists = false - organizations.each { |organization| + organizations.each do |organization| if organization.id == organization_by_user.id organization_exists = true end - } + end # get model with full data if !organization_exists organizations.push Organization.find(organization_by_user.id) end - } + end end organizations end diff --git a/app/models/organization/search_index.rb b/app/models/organization/search_index.rb index d614a02ec..d52df059f 100644 --- a/app/models/organization/search_index.rb +++ b/app/models/organization/search_index.rb @@ -22,9 +22,9 @@ returns # add org members for search index data attributes['members'] = [] users = User.where(organization_id: id) - users.each { |user| + users.each do |user| attributes['members'].push user.search_index_data - } + end attributes end diff --git a/app/models/overview/assets.rb b/app/models/overview/assets.rb index 6a9083a2f..9698a07f3 100644 --- a/app/models/overview/assets.rb +++ b/app/models/overview/assets.rb @@ -35,24 +35,24 @@ returns if !data[ app_model_overview ][ id ] data[ app_model_overview ][ id ] = attributes_with_association_ids if user_ids - user_ids.each { |local_user_id| + user_ids.each do |local_user_id| next if data[ app_model_user ][ local_user_id ] user = User.lookup(id: local_user_id) next if !user data = user.assets(data) - } + end end data = assets_of_selector('condition', data) end - %w(created_by_id updated_by_id).each { |local_user_id| + %w(created_by_id updated_by_id).each do |local_user_id| next if !self[ local_user_id ] next if data[ app_model_user ][ self[ local_user_id ] ] user = User.lookup(id: self[ local_user_id ]) next if !user data = user.assets(data) - } + end data end end diff --git a/app/models/package.rb b/app/models/package.rb index cf8253384..f76c30326 100644 --- a/app/models/package.rb +++ b/app/models/package.rb @@ -32,7 +32,7 @@ returns: # verify installed files issues = {} - package['files'].each { |file| + package['files'].each do |file| if !File.exist?(file['location']) logger.error "File #{file['location']} is missing" issues[file['location']] = 'missing' @@ -43,7 +43,7 @@ returns: next if content_package == content_fs logger.error "File #{file['location']} is different" issues[file['location']] = 'changed' - } + end return nil if issues.empty? issues end @@ -65,9 +65,9 @@ install all packages located under auto_install/*.zpm data.push entry end end - data.each { |file| + data.each do |file| install(file: "#{path}/#{file}") - } + end data end @@ -273,11 +273,11 @@ returns end # write files - package['files'].each { |file| + package['files'].each do |file| permission = file['permission'] || '644' content = Base64.decode64(file['content']) _write_file(file['location'], permission, content) - } + end # update package state package_db.state = 'installed' @@ -343,11 +343,11 @@ returns Package::Migration.migrate(package['name'], 'reverse') end - package['files'].each { |file| + package['files'].each do |file| permission = file['permission'] || '644' content = Base64.decode64(file['content']) _delete_file(file['location'], permission, content) - } + end # delete package if !data[:reinstall] @@ -370,11 +370,11 @@ execute all pending package migrations at once =end def self.migration_execute - Package.all.each { |package| + Package.all.each do |package| json_file = Package._get_bin(package.name, package.version) package = JSON.parse(json_file) Package::Migration.migrate(package['name']) - } + end end def self._get_bin(name, version) @@ -435,17 +435,17 @@ execute all pending package migrations at once # check if directories need to be created directories = location.split '/' - (0..(directories.length - 2) ).each { |position| + (0..(directories.length - 2) ).each do |position| tmp_path = '' - (1..position).each { |count| + (1..position).each do |count| tmp_path = "#{tmp_path}/#{directories[count]}" - } + end next if tmp_path == '' next if File.exist?(tmp_path) Dir.mkdir(tmp_path, 0o755) - } + end # install file begin @@ -501,11 +501,11 @@ execute all pending package migrations at once # get existing migrations migrations_existing = [] - Dir.foreach(location) { |entry| + Dir.foreach(location) do |entry| next if entry == '.' next if entry == '..' migrations_existing.push entry - } + end # up migrations_existing = migrations_existing.sort @@ -515,7 +515,7 @@ execute all pending package migrations at once migrations_existing = migrations_existing.reverse end - migrations_existing.each { |migration| + migrations_existing.each do |migration| next if migration !~ /\.rb$/ version = nil name = nil @@ -550,7 +550,7 @@ execute all pending package migrations at once classname.constantize.up Package::Migration.create(name: package.underscore, version: version) end - } + end end def self.root diff --git a/app/models/permission.rb b/app/models/permission.rb index b43b1e35a..02dff074e 100644 --- a/app/models/permission.rb +++ b/app/models/permission.rb @@ -21,13 +21,13 @@ returns def self.with_parents(key) names = [] part = '' - key.split('.').each { |local_part| + key.split('.').each do |local_part| if part != '' part += '.' end part += local_part names.push part - } + end names end diff --git a/app/models/postmaster_filter.rb b/app/models/postmaster_filter.rb index 51ffff1df..e0d2ac04d 100644 --- a/app/models/postmaster_filter.rb +++ b/app/models/postmaster_filter.rb @@ -10,7 +10,7 @@ class PostmasterFilter < ApplicationModel def validate_condition raise Exceptions::UnprocessableEntity, 'Min. one match rule needed!' if match.blank? - match.each { |_key, meta| + match.each do |_key, meta| raise Exceptions::UnprocessableEntity, 'operator invalid, ony "contains" and "contains not" is supported' if meta['operator'].blank? || meta['operator'] !~ /^(contains|contains not)$/ raise Exceptions::UnprocessableEntity, 'value invalid/empty' if meta['value'].blank? begin @@ -22,7 +22,7 @@ class PostmasterFilter < ApplicationModel rescue => e raise Exceptions::UnprocessableEntity, e.message end - } + end true end diff --git a/app/models/recent_view.rb b/app/models/recent_view.rb index 3e44d79f9..b8db53d8b 100644 --- a/app/models/recent_view.rb +++ b/app/models/recent_view.rb @@ -57,7 +57,7 @@ class RecentView < ApplicationModel end list = [] - recent_views.each { |item| + recent_views.each do |item| data = item.attributes data['object'] = ObjectLookup.by_id(data['recent_view_object_id']) data.delete('recent_view_object_id') @@ -67,7 +67,7 @@ class RecentView < ApplicationModel # add to result list list.push data - } + end list end diff --git a/app/models/report.rb b/app/models/report.rb index 1af2cb58f..d969b8342 100644 --- a/app/models/report.rb +++ b/app/models/report.rb @@ -306,11 +306,11 @@ class Report ] config[:metric][:communication][:backend] = backend - config[:metric].each { |metric_key, metric_value| - metric_value[:backend].each { |metric_backend| + config[:metric].each do |metric_key, metric_value| + metric_value[:backend].each do |metric_backend| metric_backend[:name] = "#{metric_key}::#{metric_backend[:name]}" - } - } + end + end config end diff --git a/app/models/role.rb b/app/models/role.rb index 319b8868a..864fbd8d2 100644 --- a/app/models/role.rb +++ b/app/models/role.rb @@ -107,17 +107,17 @@ returns end roles = [] permission_ids = [] - keys.each { |key| - Object.const_get('Permission').with_parents(key).each { |local_key| + keys.each do |key| + Object.const_get('Permission').with_parents(key).each do |local_key| permission = Object.const_get('Permission').lookup(name: local_key) next if !permission permission_ids.push permission.id - } + end next if permission_ids.empty? - Role.joins(:roles_permissions).joins(:permissions).where('permissions_roles.permission_id IN (?) AND roles.active = ? AND permissions.active = ?', permission_ids, true, true).distinct().each { |role| + Role.joins(:roles_permissions).joins(:permissions).where('permissions_roles.permission_id IN (?) AND roles.active = ? AND permissions.active = ?', permission_ids, true, true).distinct().each do |role| roles.push role - } - } + end + end return [] if roles.empty? roles end @@ -126,17 +126,17 @@ returns def validate_permissions return true if !self.permission_ids - permission_ids.each { |permission_id| + permission_ids.each do |permission_id| permission = Permission.lookup(id: permission_id) raise "Unable to find permission for id #{permission_id}" if !permission raise "Permission #{permission.name} is disabled" if permission.preferences[:disabled] == true next unless permission.preferences[:not] - permission.preferences[:not].each { |local_permission_name| + permission.preferences[:not].each do |local_permission_name| local_permission = Permission.lookup(name: local_permission_name) next if !local_permission raise "Permission #{permission.name} conflicts with #{local_permission.name}" if permission_ids.include?(local_permission.id) - } - } + end + end true end diff --git a/app/models/role/assets.rb b/app/models/role/assets.rb index 8b023a303..f046d12c7 100644 --- a/app/models/role/assets.rb +++ b/app/models/role/assets.rb @@ -35,22 +35,22 @@ returns # loops, will be updated with lookup attributes later data[ app_model ][ id ] = local_attributes - local_attributes['group_ids'].each { |group_id, _access| + local_attributes['group_ids'].each do |group_id, _access| group = Group.lookup(id: group_id) next if !group data = group.assets(data) - } + end end return data if !self['created_by_id'] && !self['updated_by_id'] app_model_user = User.to_app_model - %w(created_by_id updated_by_id).each { |local_user_id| + %w(created_by_id updated_by_id).each do |local_user_id| next if !self[ local_user_id ] next if data[ app_model_user ] && data[ app_model_user ][ self[ local_user_id ] ] user = User.lookup(id: self[ local_user_id ]) next if !user data = user.assets(data) - } + end data end end diff --git a/app/models/scheduler.rb b/app/models/scheduler.rb index 0c5db3386..2ed876d12 100644 --- a/app/models/scheduler.rb +++ b/app/models/scheduler.rb @@ -37,7 +37,7 @@ class Scheduler < ApplicationModel # read/load jobs and check if it is alredy started jobs = Scheduler.where('active = ?', true).order('prio ASC') - jobs.each { |job| + jobs.each do |job| # ignore job is still running next if @@jobs_started[ job.id ] @@ -49,7 +49,7 @@ class Scheduler < ApplicationModel @@jobs_started[ job.id ] = true start_job(job) sleep 10 - } + end sleep 60 end end @@ -130,7 +130,7 @@ class Scheduler < ApplicationModel def self.start_job(job) - Thread.new { + Thread.new do ApplicationHandleInfo.current = 'scheduler' logger.info "Started job thread for '#{job.name}' (#{job.method})..." @@ -163,7 +163,7 @@ class Scheduler < ApplicationModel # release thread lock @@jobs_started[ job.id ] = false - } + end end def self._start_job(job, try_count = 0, try_run_time = Time.zone.now) @@ -235,7 +235,7 @@ class Scheduler < ApplicationModel # used for production wait = 8 - Thread.new { + Thread.new do sleep wait logger.info "Starting worker thread #{Delayed::Job}" @@ -261,7 +261,7 @@ class Scheduler < ApplicationModel logger.info ' ...stopped worker thread' ActiveRecord::Base.connection.close - } + end end diff --git a/app/models/setting.rb b/app/models/setting.rb index 3734cb848..1b14e840d 100644 --- a/app/models/setting.rb +++ b/app/models/setting.rb @@ -108,18 +108,18 @@ reload config settings end if settings.present? - settings.each { |setting| + settings.each do |setting| @@raw[setting[0]] = setting[1]['value'] - } - @@raw.each { |key, value| + end + @@raw.each do |key, value| if value.class != String @@current[key] = value next end - @@current[key] = value.gsub(/\#\{config\.(.+?)\}/) { + @@current[key] = value.gsub(/\#\{config\.(.+?)\}/) do @@raw[$1].to_s - } - } + end + end end @@change_id = Cache.get('Setting::ChangeId') # rubocop:disable Style/ClassVars diff --git a/app/models/sla/assets.rb b/app/models/sla/assets.rb index 736e38594..796eb9e5c 100644 --- a/app/models/sla/assets.rb +++ b/app/models/sla/assets.rb @@ -42,13 +42,13 @@ returns end end end - %w(created_by_id updated_by_id).each { |local_user_id| + %w(created_by_id updated_by_id).each do |local_user_id| next if !self[ local_user_id ] next if data[ app_model_user ][ self[ local_user_id ] ] user = User.lookup(id: self[ local_user_id ]) next if !user data = user.assets(data) - } + end data end end diff --git a/app/models/store.rb b/app/models/store.rb index 51a84ed5b..de3548358 100644 --- a/app/models/store.rb +++ b/app/models/store.rb @@ -179,9 +179,9 @@ returns if !path path = "#{Rails.root}/tmp/#{filename}" end - ::File.open(path, 'wb') { |handle| + ::File.open(path, 'wb') do |handle| handle.write file.content - } + end path end diff --git a/app/models/store/file.rb b/app/models/store/file.rb index 1488c7264..9c6ae18bf 100644 --- a/app/models/store/file.rb +++ b/app/models/store/file.rb @@ -79,7 +79,7 @@ in case of fixing sha hash use: def self.verify(fix_it = nil) success = true file_ids = Store::File.all.pluck(:id) - file_ids.each { |item_id| + file_ids.each do |item_id| item = Store::File.find(item_id) content = item.content sha = Digest::SHA256.hexdigest(content) @@ -92,7 +92,7 @@ in case of fixing sha hash use: if fix_it item.update_attribute(:sha, sha) end - } + end success end @@ -119,7 +119,7 @@ nice move to keep system responsive adapter_target = load_adapter("Store::Provider::#{target}") file_ids = Store::File.all.pluck(:id) - file_ids.each { |item_id| + file_ids.each do |item_id| item = Store::File.find(item_id) next if item.provider == target content = item.content @@ -136,7 +136,7 @@ nice move to keep system responsive logger.info "Moved file #{item.sha} from #{source} to #{target}" sleep delay if delay - } + end true end diff --git a/app/models/store/provider/file.rb b/app/models/store/provider/file.rb index feb1410f1..82b1a48ec 100644 --- a/app/models/store/provider/file.rb +++ b/app/models/store/provider/file.rb @@ -53,12 +53,12 @@ class Store::Provider::File # check if dir need to be removed base = "#{Rails.root}/storage/fs" locations = location.split('/') - (0..locations.count).reverse_each { |count| + (0..locations.count).reverse_each do |count| local_location = locations[0, count].join('/') break if local_location =~ %r{storage/fs/{0,4}$} break if !Dir["#{local_location}/*"].empty? FileUtils.rmdir(local_location) - } + end end # generate file location @@ -71,21 +71,21 @@ class Store::Provider::File length2 = 5 length3 = 7 last_position = 0 - (0..1).each { |_count| + (0..1).each do |_count| end_position = last_position + length1 parts.push sha[last_position, length1] last_position = end_position - } - (0..1).each { |_count| + end + (0..1).each do |_count| end_position = last_position + length2 parts.push sha[last_position, length2] last_position = end_position - } - (0..1).each { |_count| + end + (0..1).each do |_count| end_position = last_position + length3 parts.push sha[last_position, length3] last_position = end_position - } + end path = parts[ 0..6 ].join('/') + '/' file = sha[last_position, sha.length] location = "#{base}/#{path}" diff --git a/app/models/tag.rb b/app/models/tag.rb index 79606689f..1e977df2f 100644 --- a/app/models/tag.rb +++ b/app/models/tag.rb @@ -146,11 +146,11 @@ returns o_id: data[:o_id], ) tags = [] - tag_search.each { |tag| + tag_search.each do |tag| tag_item = Tag::Item.lookup(id: tag.tag_item_id) next if !tag_item tags.push tag_item.name - } + end tags end @@ -222,7 +222,7 @@ rename tag items if already_existing_tag # re-assign old tag to already existing tag - Tag.where(tag_item_id: old_tag_item.id).each { |tag| + Tag.where(tag_item_id: old_tag_item.id).each do |tag| # check if tag already exists on object if Tag.find_by(tag_object_id: tag.tag_object_id, o_id: tag.o_id, tag_item_id: already_existing_tag.id) @@ -244,7 +244,7 @@ rename tag items object: tag_object.name, o_id: tag.o_id, ) - } + end # delete not longer used tag old_tag_item.destroy @@ -256,13 +256,13 @@ rename tag items old_tag_item.save # touch reference objects - Tag.where(tag_item_id: old_tag_item.id).each { |tag| + Tag.where(tag_item_id: old_tag_item.id).each do |tag| tag_object = Tag::Object.lookup(id: tag.tag_object_id) Tag.touch_reference_by_params( object: tag_object.name, o_id: tag.o_id, ) - } + end true end @@ -278,14 +278,14 @@ remove tag item (destroy with reverences) def self.remove(id) # search for references, destroy and touch - Tag.where(tag_item_id: id).each { |tag| + Tag.where(tag_item_id: id).each do |tag| tag_object = Tag::Object.lookup(id: tag.tag_object_id) tag.destroy Tag.touch_reference_by_params( object: tag_object.name, o_id: tag.o_id, ) - } + end Tag::Item.find(id).destroy true end diff --git a/app/models/taskbar.rb b/app/models/taskbar.rb index 120abaf12..8aac94cee 100644 --- a/app/models/taskbar.rb +++ b/app/models/taskbar.rb @@ -14,17 +14,17 @@ class Taskbar < ApplicationModel def state_changed? return false if state.blank? - state.each { |_key, value| + state.each do |_key, value| if value.is_a? Hash - value.each { |_key1, value1| + value.each do |_key1, value1| next if value1.blank? return true - } + end else next if value.blank? return true end - } + end false end @@ -35,11 +35,11 @@ class Taskbar < ApplicationModel return true if changes.empty? if changes['notify'] count = 0 - changes.each { |attribute, _value| + changes.each do |attribute, _value| next if attribute == 'updated_at' next if attribute == 'created_at' count += 1 - } + end return true if count <= 1 end self.last_contact = Time.zone.now @@ -59,7 +59,7 @@ class Taskbar < ApplicationModel self.preferences = {} end preferences[:tasks] = [] - Taskbar.where(key: key).order(:created_at, :id).each { |taskbar| + Taskbar.where(key: key).order(:created_at, :id).each do |taskbar| if taskbar.id == id local_changed = state_changed? local_last_contact = last_contact @@ -74,7 +74,7 @@ class Taskbar < ApplicationModel changed: local_changed, } preferences[:tasks].push task - } + end if !id changed = state_changed? task = { @@ -86,14 +86,14 @@ class Taskbar < ApplicationModel end # update other taskbars - Taskbar.where(key: key).order(:created_at, :id).each { |taskbar| + Taskbar.where(key: key).order(:created_at, :id).each do |taskbar| next if taskbar.id == id taskbar.with_lock do taskbar.preferences = preferences taskbar.local_update = true taskbar.save! end - } + end return true if destroyed? diff --git a/app/models/text_module.rb b/app/models/text_module.rb index b006d459b..b01d3a037 100644 --- a/app/models/text_module.rb +++ b/app/models/text_module.rb @@ -34,7 +34,7 @@ load text modules from online raise "Can't load text modules from #{url}: #{result.error}" if !result.success? ActiveRecord::Base.transaction do - result.data.each { |text_module| + result.data.each do |text_module| exists = TextModule.find_by(foreign_id: text_module['foreign_id']) if exists next if !overwrite_existing_item @@ -44,7 +44,7 @@ load text modules from online text_module[:created_by_id] = 1 TextModule.create(text_module.symbolize_keys!) end - } + end end true end @@ -62,10 +62,10 @@ push text_modules to online # only push changed text_modules text_modules = TextModule.all #where(locale: locale) text_modules_to_push = [] - text_modules.each { |text_module| + text_modules.each do |text_module| next if !text_module.active text_modules_to_push.push text_module - } + end return true if text_modules_to_push.empty? diff --git a/app/models/ticket.rb b/app/models/ticket.rb index 2389b0b91..c6e028dad 100644 --- a/app/models/ticket.rb +++ b/app/models/ticket.rb @@ -116,14 +116,14 @@ returns .where.not(next_state_id: nil) if ticket_states_pending_action.present? next_state_map = {} - ticket_states_pending_action.each { |state| + ticket_states_pending_action.each do |state| next_state_map[state.id] = state.next_state_id - } + end tickets = where(state_id: next_state_map.keys) .where('pending_time <= ?', Time.zone.now) - tickets.each { |ticket| + tickets.each do |ticket| Transaction.execute do ticket.state_id = next_state_map[ticket.state_id] ticket.updated_at = Time.zone.now @@ -131,7 +131,7 @@ returns ticket.save! end result.push ticket - } + end end # process pending reminder tickets @@ -140,14 +140,14 @@ returns if ticket_states_pending_reminder.present? reminder_state_map = {} - ticket_states_pending_reminder.each { |state| + ticket_states_pending_reminder.each do |state| reminder_state_map[state.id] = state.next_state_id - } + end tickets = where(state_id: reminder_state_map.keys) .where('pending_time <= ?', Time.zone.now) - tickets.each { |ticket| + tickets.each do |ticket| article_id = nil article = Ticket::Article.last_customer_agent_article(ticket.id) @@ -165,7 +165,7 @@ returns ) result.push ticket - } + end end result @@ -190,7 +190,7 @@ returns tickets = where('escalation_at <= ?', Time.zone.now + 15.minutes) - tickets.each { |ticket| + tickets.each do |ticket| # get sla sla = ticket.escalation_calculation_get_sla @@ -223,7 +223,7 @@ returns user_id: 1, ) result.push ticket - } + end result end @@ -247,10 +247,10 @@ returns result = [] groups = Group.where(active: true).where('assignment_timeout IS NOT NULL AND groups.assignment_timeout != 0') return [] if groups.blank? - groups.each { |group| + groups.each do |group| next if group.assignment_timeout.blank? ticket_ids = Ticket.where('state_id IN (?) AND owner_id != 1 AND group_id = ?', state_ids, group.id).limit(600).pluck(:id) - ticket_ids.each { |ticket_id| + ticket_ids.each do |ticket_id| ticket = Ticket.find_by(id: ticket_id) next if !ticket minutes_since_last_assignment = Time.zone.now - ticket.last_owner_update_at @@ -262,8 +262,8 @@ returns ticket.save! end result.push ticket - } - } + end + end result end @@ -502,7 +502,7 @@ condition example # get tables to join tables = '' - selectors.each { |attribute, selector| + selectors.each do |attribute, selector| selector = attribute.split(/\./) next if !selector[1] next if selector[0] == 'ticket' @@ -525,10 +525,10 @@ condition example else raise "invalid selector #{attribute.inspect}->#{selector.inspect}" end - } + end # add conditions - selectors.each { |attribute, selector_raw| + selectors.each do |attribute, selector_raw| # validation raise "Invalid selector #{selector_raw.inspect}" if !selector_raw @@ -787,7 +787,7 @@ condition example else raise "Invalid operator '#{selector['operator']}' for '#{selector['value'].inspect}'" end - } + end [query, bind_params, tables] end @@ -830,7 +830,7 @@ perform changes on ticket end recipients_raw = [] - value_recipient.each { |recipient| + value_recipient.each do |recipient| if recipient == 'article_last_sender' if item && item[:article_id] article = Ticket::Article.lookup(id: item[:article_id]) @@ -860,14 +860,14 @@ perform changes on ticket logger.error "Unknown email notification recipient '#{recipient}'" next end - } + end recipients_checked = [] - recipients_raw.each { |recipient_email| + recipients_raw.each do |recipient_email| skip_user = false users = User.where(email: recipient_email) - users.each { |user| + users.each do |user| next if user.preferences[:mail_delivery_failed] != true next if !user.preferences[:mail_delivery_failed_data] till_blocked = ((user.preferences[:mail_delivery_failed_data] - Time.zone.now - 60.days) / 60 / 60 / 24).round @@ -875,7 +875,7 @@ perform changes on ticket logger.info "Send no trigger based notification to #{recipient_email} because email is marked as mail_delivery_failed for #{till_blocked} days" skip_user = true break - } + end next if skip_user # send notifications only to email adresses @@ -917,7 +917,7 @@ perform changes on ticket 600 => 100, } skip = false - map.each { |minutes, count| + map.each do |minutes, count| already_sent = Ticket::Article.where( ticket_id: id, sender: Ticket::Article::Sender.find_by(name: 'System'), @@ -927,7 +927,7 @@ perform changes on ticket logger.info "Send no trigger based notification to #{recipient_email} because already sent #{count} for this ticket within last #{minutes} minutes (loop protection)" skip = true break - } + end next if skip map = { 10 => 30, @@ -937,7 +937,7 @@ perform changes on ticket 600 => 360, } skip = false - map.each { |minutes, count| + map.each do |minutes, count| already_sent = Ticket::Article.where( sender: Ticket::Article::Sender.find_by(name: 'System'), type: Ticket::Article::Type.find_by(name: 'email'), @@ -946,13 +946,13 @@ perform changes on ticket logger.info "Send no trigger based notification to #{recipient_email} because already sent #{count} in total within last #{minutes} minutes (loop protection)" skip = true break - } + end next if skip email = recipient_email.downcase.strip next if recipients_checked.include?(email) recipients_checked.push(email) - } + end next if recipients_checked.blank? recipient_string = recipients_checked.join(', ') @@ -1014,13 +1014,13 @@ perform changes on ticket next if value['value'].blank? tags = value['value'].split(/,/) if value['operator'] == 'add' - tags.each { |tag| + tags.each do |tag| tag_add(tag) - } + end elsif value['operator'] == 'remove' - tags.each { |tag| + tags.each do |tag| tag_remove(tag) - } + end else logger.error "Unknown #{attribute} operator #{value['operator']}" end @@ -1080,17 +1080,17 @@ result def get_references(ignore = []) references = [] - Ticket::Article.select('in_reply_to, message_id').where(ticket_id: id).each { |article| + Ticket::Article.select('in_reply_to, message_id').where(ticket_id: id).each do |article| if !article.in_reply_to.empty? references.push article.in_reply_to end next if !article.message_id next if article.message_id.empty? references.push article.message_id - } - ignore.each { |item| + end + ignore.each do |item| references.delete(item) - } + end references end @@ -1116,7 +1116,7 @@ result # get related objects assets = {} - list.each { |item| + list.each do |item| record = Kernel.const_get(item['object']).find(item['o_id']) assets = record.assets(assets) @@ -1124,7 +1124,7 @@ result record = Kernel.const_get(item['related_object']).find( item['related_o_id']) assets = record.assets(assets) end - } + end { history: list, assets: assets, diff --git a/app/models/ticket/article.rb b/app/models/ticket/article.rb index 372e83ff9..6a5e2cf5d 100644 --- a/app/models/ticket/article.rb +++ b/app/models/ticket/article.rb @@ -59,26 +59,26 @@ returns return article if article['body'] !~ //im ) { |item| + article['body'].gsub!( /(/im ) do |item| tag_start = $1 cid = $3 tag_end = $4 replace = item # look for attachment - article['attachments'].each { |file| + article['attachments'].each do |file| next if !file[:preferences] || !file[:preferences]['Content-ID'] || (file[:preferences]['Content-ID'] != cid && file[:preferences]['Content-ID'] != "<#{cid}>" ) replace = "#{tag_start}/api/v1/ticket_attachment/#{article['ticket_id']}/#{article['id']}/#{file[:id]}\"#{tag_end}>" inline_attachments[file[:id]] = true break - } + end replace - } + end new_attachments = [] - article['attachments'].each { |file| + article['attachments'].each do |file| next if inline_attachments[file[:id]] new_attachments.push file - } + end article['attachments'] = new_attachments article end @@ -98,21 +98,21 @@ returns def attachments_inline inline_attachments = {} - body.gsub( //im ) { |_item| + body.gsub( //im ) do |_item| cid = $2 # look for attachment - attachments.each { |file| + attachments.each do |file| next if !file.preferences['Content-ID'] || (file.preferences['Content-ID'] != cid && file.preferences['Content-ID'] != "<#{cid}>" ) inline_attachments[file.id] = true break - } - } + end + end new_attachments = [] - attachments.each { |file| + attachments.each do |file| next if !inline_attachments[file.id] new_attachments.push file - } + end new_attachments end @@ -232,7 +232,7 @@ returns def attributes_with_association_names attributes = super attributes['attachments'] = [] - attachments.each { |attachment| + attachments.each do |attachment| item = { id: attachment['id'], filename: attachment['filename'], @@ -240,7 +240,7 @@ returns preferences: attachment['preferences'], } attributes['attachments'].push item - } + end Ticket::Article.insert_urls(attributes) end @@ -260,7 +260,7 @@ returns def attributes_with_association_ids attributes = super attributes['attachments'] = [] - attachments.each { |attachment| + attachments.each do |attachment| item = { id: attachment['id'], filename: attachment['filename'], @@ -268,7 +268,7 @@ returns preferences: attachment['preferences'], } attributes['attachments'].push item - } + end if attributes['body'] && attributes['content_type'] =~ %r{text/html}i attributes['body'] = HtmlSanitizer.dynamic_image_size(attributes['body']) end diff --git a/app/models/ticket/article/assets.rb b/app/models/ticket/article/assets.rb index 82b266648..88c6e2fe1 100644 --- a/app/models/ticket/article/assets.rb +++ b/app/models/ticket/article/assets.rb @@ -42,13 +42,13 @@ returns data[ app_model_article ][ id ] = attributes_with_association_ids end - %w(created_by_id updated_by_id origin_by_id).each { |local_user_id| + %w(created_by_id updated_by_id origin_by_id).each do |local_user_id| next if !self[ local_user_id ] next if data[ app_model_user ] && data[ app_model_user ][ self[ local_user_id ] ] user = User.lookup(id: self[ local_user_id ]) next if !user data = user.assets(data) - } + end data end end diff --git a/app/models/ticket/assets.rb b/app/models/ticket/assets.rb index 73e6b3be6..4fdd1424d 100644 --- a/app/models/ticket/assets.rb +++ b/app/models/ticket/assets.rb @@ -31,13 +31,13 @@ returns if !data[ app_model_ticket ][ id ] data[ app_model_ticket ][ id ] = attributes_with_association_ids end - %w(created_by_id updated_by_id owner_id customer_id).each { |local_user_id| + %w(created_by_id updated_by_id owner_id customer_id).each do |local_user_id| next if !self[ local_user_id ] next if data[ app_model_user ] && data[ app_model_user ][ self[ local_user_id ] ] user = User.lookup(id: self[ local_user_id ]) next if !user data = user.assets(data) - } + end data end end diff --git a/app/models/ticket/escalation.rb b/app/models/ticket/escalation.rb index 810d72e3b..66152a6a4 100644 --- a/app/models/ticket/escalation.rb +++ b/app/models/ticket/escalation.rb @@ -17,9 +17,9 @@ returns state_list_open = Ticket::State.by_category(:open) ticket_ids = Ticket.where(state_id: state_list_open).pluck(:id) - ticket_ids.each { |ticket_id| + ticket_ids.each do |ticket_id| Ticket.find(ticket_id).escalation_calculation(true) - } + end end =begin @@ -152,16 +152,16 @@ returns # get business hours hours = {} - calendar.business_hours.each { |day, meta| + calendar.business_hours.each do |day, meta| next if !meta[:active] next if !meta[:timeframes] hours[day.to_sym] = {} - meta[:timeframes].each { |frame| + meta[:timeframes].each do |frame| next if !frame[0] next if !frame[1] hours[day.to_sym][frame[0]] = frame[1] - } - } + end + end config.hours = hours if hours.blank? raise "No configured hours found in calendar #{calendar.inspect}" @@ -170,12 +170,12 @@ returns # get holidays holidays = [] if calendar.public_holidays - calendar.public_holidays.each { |day, meta| + calendar.public_holidays.each do |day, meta| next if !meta next if !meta['active'] next if meta['removed'] holidays.push Date.parse(day) - } + end end config.holidays = holidays config.time_zone = calendar.timezone @@ -293,7 +293,7 @@ returns sla_list = Sla.all.order(:name, :created_at) Cache.write('SLA::List::Active', sla_list, { expires_in: 1.hour }) end - sla_list.each { |sla| + sla_list.each do |sla| if !sla.condition || sla.condition.empty? sla_selected = sla elsif sla.condition @@ -303,7 +303,7 @@ returns sla_selected = sla break end - } + end sla_selected end @@ -325,7 +325,7 @@ returns local_destination_time = biz.time(move_minutes, :minutes).after(start_time) # go step by step to end of move_minutes until move_minutes is 0 - 200.times.each { |_count| + 200.times.each do |_count| # check if we have pending time in the range to the destination time working_minutes = period_working_minutes(start_time, local_destination_time, biz, history_data, true) @@ -337,7 +337,7 @@ returns # set pending destination to start time and add pending time to destination time start_time = local_destination_time local_destination_time = biz.time(move_minutes, :minutes).after(start_time) - } + end local_destination_time end @@ -354,12 +354,12 @@ returns # add state changes till now if add_current && saved_change_to_attribute('state_id') && saved_change_to_attribute('state_id')[0] && saved_change_to_attribute('state_id')[1] last_history_state = nil - history_list.each { |history_item| + history_list.each do |history_item| next if !history_item['attribute'] next if history_item['attribute'] != 'state' next if history_item['id'] last_history_state = history_item - } + end local_updated_at = updated_at if saved_change_to_attribute('updated_at') && saved_change_to_attribute('updated_at')[1] local_updated_at = saved_change_to_attribute('updated_at')[1] @@ -377,7 +377,7 @@ returns end end - history_list.each { |history| + history_list.each do |history| # ignore if it isn't a state change next if !history['attribute'] @@ -416,7 +416,7 @@ returns # remember for next loop last state last_state = history['value_to'] last_state_change = created_at - } + end # if we have time to count after history entries has finished if last_state_change && last_state_change < end_time diff --git a/app/models/ticket/number.rb b/app/models/ticket/number.rb index 6617da1b0..e751c7b0c 100644 --- a/app/models/ticket/number.rb +++ b/app/models/ticket/number.rb @@ -18,11 +18,11 @@ returns def self.generate # generate number - 49_999.times { + 49_999.times do number = adapter.generate ticket = Ticket.find_by(number: number) return number if !ticket - } + end raise "Can't generate new ticket number!" end diff --git a/app/models/ticket/number/date.rb b/app/models/ticket/number/date.rb index 9db958c4b..5dc97969c 100644 --- a/app/models/ticket/number/date.rb +++ b/app/models/ticket/number/date.rb @@ -82,15 +82,15 @@ module Ticket::Number::Date ticket = nil # probe format - string.scan(/#{Regexp.quote(ticket_hook)}#{Regexp.quote(ticket_hook_divider)}(\d{4,10}#{system_id}\d{2,40})/i) { + string.scan(/#{Regexp.quote(ticket_hook)}#{Regexp.quote(ticket_hook_divider)}(\d{4,10}#{system_id}\d{2,40})/i) do ticket = Ticket.find_by(number: $1) break if ticket - } + end if !ticket - string.scan(/#{Regexp.quote(ticket_hook)}\s{0,2}(\d{4,10}#{system_id}\d{2,40})/i) { + string.scan(/#{Regexp.quote(ticket_hook)}\s{0,2}(\d{4,10}#{system_id}\d{2,40})/i) do ticket = Ticket.find_by(number: $1) break if ticket - } + end end ticket end diff --git a/app/models/ticket/number/increment.rb b/app/models/ticket/number/increment.rb index e02dfc824..68da1f450 100644 --- a/app/models/ticket/number/increment.rb +++ b/app/models/ticket/number/increment.rb @@ -31,12 +31,12 @@ module Ticket::Number::Increment min_digs = min_digs.to_i - 1 end fillup = Setting.get('system_id').to_s || '1' - 99.times { + 99.times do next if (fillup.length.to_i + counter_increment.to_s.length.to_i) >= min_digs.to_i fillup = fillup + '0' - } + end number = fillup.to_s + counter_increment.to_s # calculate a checksum @@ -79,15 +79,15 @@ module Ticket::Number::Increment ticket = nil # probe format - string.scan(/#{Regexp.quote(ticket_hook)}#{Regexp.quote(ticket_hook_divider)}(#{system_id}\d{2,48})/i) { + string.scan(/#{Regexp.quote(ticket_hook)}#{Regexp.quote(ticket_hook_divider)}(#{system_id}\d{2,48})/i) do ticket = Ticket.find_by(number: $1) break if ticket - } + end if !ticket - string.scan(/#{Regexp.quote(ticket_hook)}\s{0,2}(#{system_id}\d{2,48})/i) { + string.scan(/#{Regexp.quote(ticket_hook)}\s{0,2}(#{system_id}\d{2,48})/i) do ticket = Ticket.find_by(number: $1) break if ticket - } + end end ticket end diff --git a/app/models/ticket/overviews.rb b/app/models/ticket/overviews.rb index 51e894643..664a09046 100644 --- a/app/models/ticket/overviews.rb +++ b/app/models/ticket/overviews.rb @@ -25,11 +25,11 @@ returns end overviews = Overview.joins(:roles).where(overviews_roles: { role_id: role_ids }, overviews: overview_filter).distinct('overview.id').order(:prio) overviews_list = [] - overviews.each { |overview| + overviews.each do |overview| user_ids = overview.user_ids next if !user_ids.empty? && !user_ids.include?(current_user.id) overviews_list.push overview - } + end return overviews_list end @@ -42,11 +42,11 @@ returns end overviews = Overview.joins(:roles).where(overviews_roles: { role_id: role_ids }, overviews: overview_filter).where.not(overview_filter_not).distinct('overview.id').order(:prio) overviews_list = [] - overviews.each { |overview| + overviews.each do |overview| user_ids = overview.user_ids next if !user_ids.empty? && !user_ids.include?(current_user.id) overviews_list.push overview - } + end overviews_list end @@ -96,7 +96,7 @@ returns ticket_attributes = Ticket.new.attributes list = [] - overviews.each { |overview| + overviews.each do |overview| query_condition, bind_condition, tables = Ticket.selector2sql(overview.condition, user) # validate direction @@ -135,13 +135,13 @@ returns .pluck(:id, :updated_at) tickets = [] - ticket_result.each { |ticket| + ticket_result.each do |ticket| ticket_item = { id: ticket[0], updated_at: ticket[1], } tickets.push ticket_item - } + end count = Ticket.where(access_condition).where(query_condition, *bind_condition).joins(tables).count() item = { overview: { @@ -155,7 +155,7 @@ returns } list.push item - } + end list end diff --git a/app/models/ticket/priority.rb b/app/models/ticket/priority.rb index fc6cfd19f..be3a780b5 100644 --- a/app/models/ticket/priority.rb +++ b/app/models/ticket/priority.rb @@ -23,12 +23,12 @@ class Ticket::Priority < ApplicationModel end if priorities_with_default.count > 1 - Ticket::Priority.all.each { |local_priority| + Ticket::Priority.all.each do |local_priority| next if local_priority.id == id local_priority.default_create = false local_priority.callback_loop = true local_priority.save! - } + end end end end diff --git a/app/models/ticket/screen_options.rb b/app/models/ticket/screen_options.rb index 40053bb72..f490b4dda 100644 --- a/app/models/ticket/screen_options.rb +++ b/app/models/ticket/screen_options.rb @@ -148,20 +148,20 @@ returns ).limit( data[:limit] || 15 ).order('created_at DESC') assets = {} ticket_ids_open = [] - tickets_open.each { |ticket| + tickets_open.each do |ticket| ticket_ids_open.push ticket.id assets = ticket.assets(assets) - } + end tickets_closed = Ticket.where( customer_id: data[:customer_id], state_id: state_list_closed ).limit( data[:limit] || 15 ).order('created_at DESC') ticket_ids_closed = [] - tickets_closed.each { |ticket| + tickets_closed.each do |ticket| ticket_ids_closed.push ticket.id assets = ticket.assets(assets) - } + end { ticket_ids_open: ticket_ids_open, diff --git a/app/models/ticket/search.rb b/app/models/ticket/search.rb index 5979da11c..aa1bea338 100644 --- a/app/models/ticket/search.rb +++ b/app/models/ticket/search.rb @@ -130,17 +130,17 @@ returns items = SearchIndexBackend.search(query, limit, 'Ticket', query_extention) if !full ids = [] - items.each { |item| + items.each do |item| ids.push item[:id] - } + end return ids end tickets = [] - items.each { |item| + items.each do |item| ticket = Ticket.lookup(id: item[:id]) next if !ticket tickets.push ticket - } + end return tickets end @@ -170,16 +170,16 @@ returns # build result list if !full ids = [] - tickets_all.each { |ticket| + tickets_all.each do |ticket| ids.push ticket.id - } + end return ids end tickets = [] - tickets_all.each { |ticket| + tickets_all.each do |ticket| tickets.push Ticket.lookup(id: ticket.id) - } + end tickets end end diff --git a/app/models/ticket/search_index.rb b/app/models/ticket/search_index.rb index bd0980066..0113823fe 100644 --- a/app/models/ticket/search_index.rb +++ b/app/models/ticket/search_index.rb @@ -34,14 +34,14 @@ returns # collect article data articles = Ticket::Article.where(ticket_id: id) attributes['article'] = [] - articles.each { |article| + articles.each do |article| article_attributes = article.attributes # remove note needed attributes ignore = %w(message_id_md5) - ignore.each { |attribute| + ignore.each do |attribute| article_attributes.delete(attribute) - } + end # lookup attributes of ref. objects (normally name and note) article_attributes = article.search_index_attribute_lookup @@ -52,7 +52,7 @@ returns end # lookup attachments - article.attachments.each { |attachment| + article.attachments.each do |attachment| if !article_attributes['attachment'] article_attributes['attachment'] = [] end @@ -74,9 +74,9 @@ returns '_content' => Base64.encode64(attachment.content) } article_attributes['attachment'].push data - } + end attributes['article'].push article_attributes - } + end attributes end diff --git a/app/models/ticket/state.rb b/app/models/ticket/state.rb index 285a65eae..7adb18dd4 100644 --- a/app/models/ticket/state.rb +++ b/app/models/ticket/state.rb @@ -96,14 +96,14 @@ returns: next end - Ticket::State.all.each { |local_state| + Ticket::State.all.each do |local_state| next if local_state.id == id next if local_state[default_field] == false local_state[default_field] = false local_state.callback_loop = true local_state.save! next - } + end end end diff --git a/app/models/ticket/time_accounting.rb b/app/models/ticket/time_accounting.rb index b2ac5d2b0..6e2a73d3c 100644 --- a/app/models/ticket/time_accounting.rb +++ b/app/models/ticket/time_accounting.rb @@ -10,10 +10,10 @@ class Ticket::TimeAccounting < ApplicationModel def ticket_time_unit_update exists = false time_units = 0 - Ticket::TimeAccounting.where(ticket_id: ticket_id).each { |record| + Ticket::TimeAccounting.where(ticket_id: ticket_id).each do |record| time_units += record.time_unit exists = true - } + end return false if exists == false ticket = Ticket.lookup(id: ticket_id) return false if !ticket diff --git a/app/models/token.rb b/app/models/token.rb index edd83bd6c..d9d12accc 100644 --- a/app/models/token.rb +++ b/app/models/token.rb @@ -86,16 +86,16 @@ returns local_permissions = [data[:permission]] end match = false - local_permissions.each { |local_permission| + local_permissions.each do |local_permission| local_permissions = Permission.with_parents(local_permission) - local_permissions.each { |local_permission_name| + local_permissions.each do |local_permission_name| next if !token.preferences[:permission].include?(local_permission_name) match = true break - } + end next if !match break - } + end return if !match end diff --git a/app/models/transaction/background_job.rb b/app/models/transaction/background_job.rb index 57a649b1a..f37c99846 100644 --- a/app/models/transaction/background_job.rb +++ b/app/models/transaction/background_job.rb @@ -23,12 +23,12 @@ class Transaction::BackgroundJob end def perform - Setting.where(area: 'Transaction::Backend::Async').order(:name).each { |setting| + Setting.where(area: 'Transaction::Backend::Async').order(:name).each do |setting| backend = Setting.get(setting.name) next if @params[:disable] && @params[:disable].include?(backend) backend = Kernel.const_get(backend) Observer::Transaction.execute_singel_backend(backend, @item, @params) - } + end end def self.run(item, params = {}) diff --git a/app/models/transaction/karma.rb b/app/models/transaction/karma.rb index ef32bdf2b..07a43b73f 100644 --- a/app/models/transaction/karma.rb +++ b/app/models/transaction/karma.rb @@ -76,7 +76,7 @@ class Transaction::Karma # did user send a response to customer before? current_time = @item[:created_at] - ticket.articles.reverse.each { |local_article| + ticket.articles.reverse.each do |local_article| next if local_article.created_at > current_time next if local_article.created_by_id != @item[:user_id] next if local_article.internal @@ -90,7 +90,7 @@ class Transaction::Karma Karma::ActivityLog.add('ticket close', user, 'Ticket', ticket.id) break - } + end end # pending state @@ -120,7 +120,7 @@ class Transaction::Karma if articles.count > 1 last_sender_customer = nil last_customer_contact = nil - articles.each { |local_article| + articles.each do |local_article| next if local_article.id == article.id next if local_article.internal @@ -140,7 +140,7 @@ class Transaction::Karma next if local_sender.name != 'Customer' last_customer_contact = local_article.created_at - } + end if last_sender_customer && last_customer_contact diff = article.created_at - last_customer_contact if diff >= 0 diff --git a/app/models/transaction/notification.rb b/app/models/transaction/notification.rb index 1893a28b6..398426e0b 100644 --- a/app/models/transaction/notification.rb +++ b/app/models/transaction/notification.rb @@ -59,13 +59,13 @@ class Transaction::Notification # apply out of office agents possible_recipients_additions = Set.new - possible_recipients.each { |user| + possible_recipients.each do |user| recursive_ooo_replacements( user: user, replacements: possible_recipients_additions, reasons: recipients_reason, ) - } + end if possible_recipients_additions.present? # join unique entries @@ -73,7 +73,7 @@ class Transaction::Notification end already_checked_recipient_ids = {} - possible_recipients.each { |user| + possible_recipients.each do |user| result = NotificationFactory::Mailer.notification_settings(user, ticket, @item[:type]) next if !result next if already_checked_recipient_ids[user.id] @@ -81,7 +81,7 @@ class Transaction::Notification recipients_and_channels.push result next if recipients_reason[user.id] recipients_reason[user.id] = 'are in group' - } + end # send notifications recipient_list = '' @@ -109,13 +109,13 @@ class Transaction::Notification identifier = user.login end already_notified = false - History.list('Ticket', ticket.id).each { |history| + History.list('Ticket', ticket.id).each do |history| next if history['type'] != 'notification' next if history['value_to'] !~ /\(#{Regexp.escape(@item[:type])}:/ next if history['value_to'] !~ /#{Regexp.escape(identifier)}\(/ next if !history['created_at'].today? already_notified = true - } + end next if already_notified end @@ -237,7 +237,7 @@ class Transaction::Notification attribute_list = ObjectManager::Attribute.by_object_as_hash('Ticket', user) #puts "AL #{attribute_list.inspect}" user_related_changes = {} - @item[:changes].each { |key, value| + @item[:changes].each do |key, value| # if no config exists, use all attributes if !attribute_list || attribute_list.empty? @@ -247,10 +247,10 @@ class Transaction::Notification elsif attribute_list[key.to_s] user_related_changes[key] = value end - } + end changes = {} - user_related_changes.each { |key, value| + user_related_changes.each do |key, value| # get attribute name attribute_name = key.to_s @@ -313,7 +313,7 @@ class Transaction::Notification else [value_str[0].to_s, value_str[1].to_s] end - } + end changes end diff --git a/app/models/transaction/slack.rb b/app/models/transaction/slack.rb index 459b94c05..124685618 100644 --- a/app/models/transaction/slack.rb +++ b/app/models/transaction/slack.rb @@ -107,7 +107,7 @@ class Transaction::Slack color = '#38ad69' end - config['items'].each { |local_config| + config['items'].each do |local_config| next if local_config['webhook'].empty? # check if reminder_reached/escalation/escalation_warning is already sent today @@ -131,11 +131,11 @@ class Transaction::Slack # check action if local_config['types'].class == Array hit = false - local_config['types'].each { |type| + local_config['types'].each do |type| next if type.to_s != @item[:type].to_s hit = true break - } + end next if !hit elsif local_config['types'] next if local_config['types'].to_s != @item[:type].to_s @@ -144,11 +144,11 @@ class Transaction::Slack # check group if local_config['group_ids'].class == Array hit = false - local_config['group_ids'].each { |group_id| + local_config['group_ids'].each do |group_id| next if group_id.to_s != ticket.group_id.to_s hit = true break - } + end next if !hit elsif local_config['group_ids'] next if local_config['group_ids'].to_s != ticket.group_id.to_s @@ -189,7 +189,7 @@ class Transaction::Slack next end Rails.logger.debug "sent webhook (#{@item[:type]}/#{ticket.id}/#{local_config['webhook']})" - } + end end @@ -203,7 +203,7 @@ class Transaction::Slack attribute_list = ObjectManager::Attribute.by_object_as_hash('Ticket', user) #puts "AL #{attribute_list.inspect}" user_related_changes = {} - @item[:changes].each { |key, value| + @item[:changes].each do |key, value| # if no config exists, use all attributes if !attribute_list || attribute_list.empty? @@ -213,10 +213,10 @@ class Transaction::Slack elsif attribute_list[key.to_s] user_related_changes[key] = value end - } + end changes = {} - user_related_changes.each { |key, value| + user_related_changes.each do |key, value| # get attribute name attribute_name = key.to_s @@ -279,7 +279,7 @@ class Transaction::Slack else [value_str[0].to_s, value_str[1].to_s] end - } + end changes end diff --git a/app/models/transaction/trigger.rb b/app/models/transaction/trigger.rb index a2be8c673..24322ceb8 100644 --- a/app/models/transaction/trigger.rb +++ b/app/models/transaction/trigger.rb @@ -45,7 +45,7 @@ class Transaction::Trigger original_user_id = UserInfo.current_user_id Transaction.execute(reset_user_id: true, disable: ['Transaction::Trigger', 'Transaction::Notification']) do - triggers.each { |trigger| + triggers.each do |trigger| condition = trigger.condition # check if one article attribute is used @@ -138,7 +138,7 @@ class Transaction::Trigger user_id = article.updated_by_id end ticket.perform_changes(trigger.perform, 'trigger', @item, user_id) - } + end end UserInfo.current_user_id = original_user_id end diff --git a/app/models/translation.rb b/app/models/translation.rb index dde80442a..5a406a21a 100644 --- a/app/models/translation.rb +++ b/app/models/translation.rb @@ -39,10 +39,10 @@ dedicated: =end def self.load(dedicated_locale = nil) - locals_to_sync(dedicated_locale).each { |locale| + locals_to_sync(dedicated_locale).each do |locale| fetch(locale) load_from_file(locale) - } + end true end @@ -59,11 +59,11 @@ push translations to online # only push changed translations translations = Translation.where(locale: locale) translations_to_push = [] - translations.each { |translation| + translations.each do |translation| if translation.target != translation.target_initial translations_to_push.push translation end - } + end return true if translations_to_push.empty? @@ -107,14 +107,14 @@ reset translations to origin # only push changed translations translations = Translation.where(locale: locale) - translations.each { |translation| + translations.each do |translation| if !translation.target_initial || translation.target_initial.empty? translation.destroy elsif translation.target != translation.target_initial translation.target = translation.target_initial translation.save end - } + end true end @@ -145,7 +145,7 @@ get list of translations else Translation.where(locale: locale.downcase).where.not(target: '').order(:source) end - translations.each { |item| + translations.each do |item| translation_item = [] translation_item = if admin [ @@ -164,18 +164,18 @@ get list of translations ] end list.push translation_item - } + end # add presorted on top presorted_list = [] - %w(yes no or Year Years Month Months Day Days Hour Hours Minute Minutes Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec January February March April May June July August September October November December Mon Tue Wed Thu Fri Sat Sun Monday Tuesday Wednesday Thursday Friday Saturday Sunday).each { |presort| - list.each { |item| + %w(yes no or Year Years Month Months Day Days Hour Hours Minute Minutes Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec January February March April May June July August September October November December Mon Tue Wed Thu Fri Sat Sun Monday Tuesday Wednesday Thursday Friday Saturday Sunday).each do |presort| + list.each do |item| next if item[1] != presort presorted_list.push item list.delete item #list.unshift presort - } - } + end + end data['list'] = presorted_list.concat list # set cache @@ -198,15 +198,15 @@ translate strings in ruby context, e. g. for notifications # translate string records = Translation.where(locale: locale, source: string) - records.each { |record| + records.each do |record| return record.target if record.source == string - } + end # fallback lookup in en records = Translation.where(locale: 'en', source: string) - records.each { |record| + records.each do |record| return record.target if record.source == string - } + end string end @@ -228,12 +228,12 @@ all: def self.load_from_file(dedicated_locale = nil) version = Version.get directory = Rails.root.join('config/translations') - locals_to_sync(dedicated_locale).each { |locale| + locals_to_sync(dedicated_locale).each do |locale| file = Rails.root.join("#{directory}/#{locale}-#{version}.yml") return false if !File.exist?(file) data = YAML.load_file(file) to_database(locale, data) - } + end true end @@ -253,7 +253,7 @@ all: def self.fetch(dedicated_locale = nil) version = Version.get - locals_to_sync(dedicated_locale).each { |locale| + locals_to_sync(dedicated_locale).each do |locale| url = "https://i18n.zammad.com/api/v1/translations/#{locale}" if !UserInfo.current_user_id UserInfo.current_user_id = 1 @@ -279,7 +279,7 @@ all: File.open(file, 'w') do |out| YAML.dump(result.data, out) end - } + end true end @@ -321,7 +321,7 @@ Get source file at https://i18n.zammad.com/api/v1/translations_empty_translation header = rows.shift translation_raw = [] - rows.each { |row| + rows.each do |row| raise "Can't import translation, source is missing" if row[0].blank? if row[1].blank? warn "Skipped #{row[0]}, because translation is blank" @@ -337,7 +337,7 @@ Get source file at https://i18n.zammad.com/api/v1/translations_empty_translation 'format' => row[2], } translation_raw.push item - } + end to_database(locale.name, translation_raw) true end @@ -345,21 +345,21 @@ Get source file at https://i18n.zammad.com/api/v1/translations_empty_translation private_class_method def self.to_database(locale, data) translations = Translation.where(locale: locale).all ActiveRecord::Base.transaction do - data.each { |translation_raw| + data.each do |translation_raw| # handle case insensitive sql translation = nil - translations.each { |item| + translations.each do |item| next if item.format != translation_raw['format'] next if item.source != translation_raw['source'] translation = item break - } + end if translation # verify if update is needed update_needed = false - translation_raw.each { |key, _value| + translation_raw.each do |key, _value| # if translation target has changes next unless translation_raw[key] != translation.target @@ -369,7 +369,7 @@ Get source file at https://i18n.zammad.com/api/v1/translations_empty_translation update_needed = true break end - } + end if update_needed translation.update!(translation_raw.symbolize_keys!) translation.save @@ -381,7 +381,7 @@ Get source file at https://i18n.zammad.com/api/v1/translations_empty_translation end Translation.create(translation_raw.symbolize_keys!) end - } + end end end @@ -389,9 +389,9 @@ Get source file at https://i18n.zammad.com/api/v1/translations_empty_translation locales_list = [] if !dedicated_locale locales = Locale.to_sync - locales.each { |locale| + locales.each do |locale| locales_list.push locale.locale - } + end else locales_list = [dedicated_locale] end diff --git a/app/models/user.rb b/app/models/user.rb index 0a2cc5dfd..a0749bed8 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -369,11 +369,11 @@ returns role_ids = Role.signup_role_ids url = '' if hash['info']['urls'] - hash['info']['urls'].each { |_name, local_url| + hash['info']['urls'].each do |_name, local_url| next if !local_url next if local_url.empty? url = local_url - } + end end create( login: hash['info']['nickname'] || hash['uid'], @@ -408,10 +408,10 @@ returns def permissions list = {} - Object.const_get('Permission').select('permissions.name, permissions.preferences').joins(:roles).where('roles.id IN (?) AND permissions.active = ?', role_ids, true).pluck(:name, :preferences).each { |permission| + Object.const_get('Permission').select('permissions.name, permissions.preferences').joins(:roles).where('roles.id IN (?) AND permissions.active = ?', role_ids, true).pluck(:name, :preferences).each do |permission| next if permission[1]['selectable'] == false list[permission[0]] = true - } + end list end @@ -439,7 +439,7 @@ returns if key.class == String keys = [key] end - keys.each { |local_key| + keys.each do |local_key| cache_key = "User::permissions?:local_key:::#{id}" if Rails.env.production? cache = Cache.get(cache_key) @@ -456,12 +456,12 @@ returns permissions = Object.const_get('Permission').with_parents(local_key) list = Object.const_get('Permission').select('preferences').joins(:roles).where('roles.id IN (?) AND roles.active = ? AND permissions.name IN (?) AND permissions.active = ?', role_ids, true, permissions, true).pluck(:preferences) end - list.each { |preferences| + list.each do |preferences| next if preferences[:selectable] == false Cache.write(key, true, expires_in: 10.seconds) return true - } - } + end + end Cache.write(key, false, expires_in: 10.seconds) false end @@ -482,12 +482,12 @@ returns def permissions_with_child_ids where = '' where_bind = [true] - permissions.each { |permission_name, _value| + permissions.each do |permission_name, _value| where += ' OR ' if where != '' where += 'permissions.name = ? OR permissions.name LIKE ?' where_bind.push permission_name where_bind.push "#{permission_name}.%" - } + end return [] if where == '' Object.const_get('Permission').where("permissions.active = ? AND (#{where})", *where_bind).pluck(:id) end @@ -514,27 +514,27 @@ returns end total_role_ids = [] permission_ids = [] - keys.each { |key| + keys.each do |key| role_ids = [] - Object.const_get('Permission').with_parents(key).each { |local_key| + Object.const_get('Permission').with_parents(key).each do |local_key| permission = Object.const_get('Permission').lookup(name: local_key) next if !permission permission_ids.push permission.id - } + end next if permission_ids.empty? - Role.joins(:roles_permissions).joins(:permissions).where('permissions_roles.permission_id IN (?) AND roles.active = ? AND permissions.active = ?', permission_ids, true, true).distinct().pluck(:id).each { |role_id| + Role.joins(:roles_permissions).joins(:permissions).where('permissions_roles.permission_id IN (?) AND roles.active = ? AND permissions.active = ?', permission_ids, true, true).distinct().pluck(:id).each do |role_id| role_ids.push role_id - } + end total_role_ids.push role_ids - } + end return [] if total_role_ids.empty? condition = '' - total_role_ids.each { |_role_ids| + total_role_ids.each do |_role_ids| if condition != '' condition += ' OR ' end condition += 'roles_users.role_id IN (?)' - } + end User.joins(:users_roles).where("(#{condition}) AND users.active = ?", *total_role_ids, true).distinct.order(:id) end @@ -763,18 +763,18 @@ returns default = Rails.configuration.preferences_default_by_permission return false if !default default.deep_stringify_keys! - User.with_permissions(permission.name).each { |user| + User.with_permissions(permission.name).each do |user| next if !default[permission.name] has_changed = false - default[permission.name].each { |key, value| + default[permission.name].each do |key, value| next if !force && user.preferences[key] has_changed = true user.preferences[key] = value - } + end if has_changed user.save! end - } + end true end @@ -796,9 +796,9 @@ returns default = Rails.configuration.preferences_default_by_permission return false if !default default.deep_stringify_keys! - role.permissions.each { |permission| + role.permissions.each do |permission| User.update_default_preferences_by_permission(permission.name, force) - } + end true end @@ -807,14 +807,14 @@ returns return if !default default.deep_stringify_keys! has_changed = false - o.permissions.each { |permission| + o.permissions.each do |permission| next if !default[permission.name] - default[permission.name].each { |key, value| + default[permission.name].each do |key, value| next if preferences[key] preferences[key] = value has_changed = true - } - } + end + end return true if !has_changed @@ -830,9 +830,9 @@ returns def check_preferences_default if @preferences_default.blank? if id - roles.each { |role| + roles.each do |role| check_notifications(role, false) - } + end end end return if @preferences_default.blank? @@ -965,16 +965,16 @@ returns def validate_roles return true if !role_ids - role_ids.each { |role_id| + role_ids.each do |role_id| role = Role.lookup(id: role_id) raise "Unable to find role for id #{role_id}" if !role next if !role.preferences[:not] - role.preferences[:not].each { |local_role_name| + role.preferences[:not].each do |local_role_name| local_role = Role.lookup(name: local_role_name) next if !local_role raise "Role #{role.name} conflicts with #{local_role.name}" if role_ids.include?(local_role.id) - } - } + end + end true end diff --git a/app/models/user/assets.rb b/app/models/user/assets.rb index 1d64c4f8b..a494eaacd 100644 --- a/app/models/user/assets.rb +++ b/app/models/user/assets.rb @@ -57,28 +57,28 @@ returns # get roles if local_attributes['role_ids'] - local_attributes['role_ids'].each { |role_id| + local_attributes['role_ids'].each do |role_id| role = Role.lookup(id: role_id) data = role.assets(data) - } + end end # get groups if local_attributes['group_ids'] - local_attributes['group_ids'].each { |group_id, _access| + local_attributes['group_ids'].each do |group_id, _access| group = Group.lookup(id: group_id) next if !group data = group.assets(data) - } + end end # get organizations if local_attributes['organization_ids'] - local_attributes['organization_ids'].each { |organization_id| + local_attributes['organization_ids'].each do |organization_id| organization = Organization.lookup(id: organization_id) next if !organization data = organization.assets(data) - } + end end data[ app_model ][ id ] = local_attributes @@ -93,13 +93,13 @@ returns end end end - %w(created_by_id updated_by_id).each { |local_user_id| + %w(created_by_id updated_by_id).each do |local_user_id| next if !self[ local_user_id ] next if data[ app_model ][ self[ local_user_id ] ] user = User.lookup(id: self[ local_user_id ]) next if !user data = user.assets(data) - } + end data end end diff --git a/app/models/user/search.rb b/app/models/user/search.rb index 4d11b9fc5..3a23d2775 100644 --- a/app/models/user/search.rb +++ b/app/models/user/search.rb @@ -89,11 +89,11 @@ returns end items = SearchIndexBackend.search(query, limit, 'User', query_extention) users = [] - items.each { |item| + items.each do |item| user = User.lookup(id: item[:id]) next if !user users.push user - } + end return users end diff --git a/app/models/user/search_index.rb b/app/models/user/search_index.rb index 745a10314..c28485f17 100644 --- a/app/models/user/search_index.rb +++ b/app/models/user/search_index.rb @@ -49,7 +49,7 @@ returns def search_index_data attributes = {} - self.attributes.each { |key, value| + self.attributes.each do |key, value| next if key == 'created_at' next if key == 'updated_at' next if key == 'created_by_id' @@ -59,7 +59,7 @@ returns next if !value next if value.respond_to?('blank?') && value.blank? attributes[key] = value - } + end return if attributes.blank? if attributes['organization_id'].present? diff --git a/app/models/user_device.rb b/app/models/user_device.rb index 3085fe24b..cecc0cc1c 100644 --- a/app/models/user_device.rb +++ b/app/models/user_device.rb @@ -39,11 +39,11 @@ store new device for user if device not already known user_id: user_id, fingerprint: fingerprint, ) - user_devices.each { |local_user_device| + user_devices.each do |local_user_device| device_exists_by_fingerprint = true next if local_user_device.location != location return action(local_user_device.id, user_agent, ip, user_id, type) if local_user_device - } + end end # for basic_auth|token_auth search for user agent @@ -53,11 +53,11 @@ store new device for user if device not already known user_id: user_id, user_agent: user_agent, ) - user_devices.each { |local_user_device| + user_devices.each do |local_user_device| device_exists_by_user_agent = true next if local_user_device.location != location return action(local_user_device.id, user_agent, ip, user_id, type) if local_user_device - } + end end # get browser details diff --git a/config/initializers/core_ext.rb b/config/initializers/core_ext.rb index ee21f0f77..86258f99e 100644 --- a/config/initializers/core_ext.rb +++ b/config/initializers/core_ext.rb @@ -1,6 +1,6 @@ # load all core_ext extentions -Dir.glob("#{Rails.root}/lib/core_ext/**/*").each { |file| +Dir.glob("#{Rails.root}/lib/core_ext/**/*").each do |file| if File.file?(file) require file end -} +end diff --git a/config/initializers/vendor_lib.rb b/config/initializers/vendor_lib.rb index 6a3780365..9367719f8 100644 --- a/config/initializers/vendor_lib.rb +++ b/config/initializers/vendor_lib.rb @@ -1,6 +1,6 @@ # load all vendor/lib extentions -Dir["#{Rails.root}/vendor/lib/*"].each { |file| +Dir["#{Rails.root}/vendor/lib/*"].each do |file| if File.file?(file) require file end -} +end diff --git a/config/routes.rb b/config/routes.rb index dd7fbc34c..93f9a8a50 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -10,13 +10,13 @@ Rails.application.routes.draw do # load routes from external files dir = File.expand_path('../', __FILE__) files = Dir.glob( "#{dir}/routes/*.rb" ) - files.each { |file| + files.each do |file| if Rails.configuration.cache_classes require file else load file end - } + end match '*a', to: 'errors#routing', via: [:get, :post, :put, :delete] diff --git a/contrib/packager.io/fetch_locales.rb b/contrib/packager.io/fetch_locales.rb index 0c7eba657..b6b13a9b8 100755 --- a/contrib/packager.io/fetch_locales.rb +++ b/contrib/packager.io/fetch_locales.rb @@ -33,7 +33,7 @@ end if !File.directory?(directory_translations) Dir.mkdir(directory_translations, 0o755) end -data.each { |locale| +data.each do |locale| url = "#{url_translations}#{locale['locale']}?version=#{version}" uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) @@ -46,5 +46,5 @@ data.each { |locale| File.open(file, 'w') do |out| YAML.dump(data, out) end -} +end puts 'done' diff --git a/db/migrate/20150979000001_update_timestamps.rb b/db/migrate/20150979000001_update_timestamps.rb index 4eae2c73b..075a73528 100644 --- a/db/migrate/20150979000001_update_timestamps.rb +++ b/db/migrate/20150979000001_update_timestamps.rb @@ -1,7 +1,7 @@ class UpdateTimestamps < ActiveRecord::Migration[4.2] def up # get all models - Models.all.each { |_model, value| + Models.all.each do |_model, value| next if !value next if !value[:attributes] if value[:attributes].include?('changed_at') @@ -10,6 +10,6 @@ class UpdateTimestamps < ActiveRecord::Migration[4.2] if value[:attributes].include?('created_at') ActiveRecord::Migration.change_column value[:table].to_sym, :created_at, :datetime, null: false end - } + end end end diff --git a/db/migrate/20170113000001_object_manager_attribute_create_middle.rb b/db/migrate/20170113000001_object_manager_attribute_create_middle.rb index 8e40c22f1..ede9e01dd 100644 --- a/db/migrate/20170113000001_object_manager_attribute_create_middle.rb +++ b/db/migrate/20170113000001_object_manager_attribute_create_middle.rb @@ -3,14 +3,14 @@ class ObjectManagerAttributeCreateMiddle < ActiveRecord::Migration[4.2] # return if it's a new setup return if !Setting.find_by(name: 'system_init_done') - ObjectManager::Attribute.all.each { |attribute| + ObjectManager::Attribute.all.each do |attribute| next if attribute.name == 'tags' next if !attribute.screens next if !attribute.screens['create_bottom'] attribute.screens['create_middle'] = attribute.screens['create_bottom'] attribute.screens.delete('create_bottom') attribute.save! - } + end attribute = ObjectManager::Attribute.find_by(name: 'priority_id') attribute.data_option['nulloption'] = false diff --git a/db/migrate/20170116000002_fixed_typos_622.rb b/db/migrate/20170116000002_fixed_typos_622.rb index 45af0bb51..57425f858 100644 --- a/db/migrate/20170116000002_fixed_typos_622.rb +++ b/db/migrate/20170116000002_fixed_typos_622.rb @@ -18,12 +18,12 @@ class FixedTypos622 < ActiveRecord::Migration[4.2] 'postmaster_follow_up_search_in' => 'In default the follow up check is done via the subject of an email. With this setting you can add more fields where the follow up check is executed.', } - setting_map.each { |key, description| + setting_map.each do |key, description| local_setting = Setting.find_by(name: key) next if !local_setting local_setting.description = description local_setting.save! - } + end Translation.sync diff --git a/db/migrate/20170123000002_fixed_translation.rb b/db/migrate/20170123000002_fixed_translation.rb index b11b72eb8..3397f0f56 100644 --- a/db/migrate/20170123000002_fixed_translation.rb +++ b/db/migrate/20170123000002_fixed_translation.rb @@ -410,7 +410,7 @@ class FixedTranslation < ActiveRecord::Migration[4.2] }, ] - settings_update.each { |setting| + settings_update.each do |setting| fetched_setting = Setting.find_by(name: setting['name'] ) next if !fetched_setting @@ -423,7 +423,7 @@ class FixedTranslation < ActiveRecord::Migration[4.2] end fetched_setting.save! - } + end Translation.sync diff --git a/db/migrate/20170314000001_fixed_translation2.rb b/db/migrate/20170314000001_fixed_translation2.rb index 91d28c758..e3b5eaaa8 100644 --- a/db/migrate/20170314000001_fixed_translation2.rb +++ b/db/migrate/20170314000001_fixed_translation2.rb @@ -12,7 +12,7 @@ class FixedTranslation2 < ActiveRecord::Migration[4.2] }, ] - settings_update.each { |setting| + settings_update.each do |setting| fetched_setting = Setting.find_by(name: setting['name']) next if !fetched_setting @@ -25,7 +25,7 @@ class FixedTranslation2 < ActiveRecord::Migration[4.2] end fetched_setting.save! - } + end Translation.load diff --git a/db/migrate/20170403000001_fixed_admin_user_permission_920.rb b/db/migrate/20170403000001_fixed_admin_user_permission_920.rb index d132ae953..8209aaeb3 100644 --- a/db/migrate/20170403000001_fixed_admin_user_permission_920.rb +++ b/db/migrate/20170403000001_fixed_admin_user_permission_920.rb @@ -741,26 +741,26 @@ class FixedAdminUserPermission920 < ActiveRecord::Migration[4.2] Agent: 'ticket.agent', Customer: 'ticket.customer', } - ObjectManager::Attribute.all.each { |attribute| + ObjectManager::Attribute.all.each do |attribute| next if attribute.screens.blank? screens = {} - attribute.screens.each { |screen, role_value| + attribute.screens.each do |screen, role_value| if role_value.blank? screens[screen] = role_value else screens[screen] = {} - role_value.each { |role, value| + role_value.each do |role, value| if map[role.to_sym] screens[screen][map[role.to_sym]] = value else screens[screen][role] = value end - } + end end - } + end attribute.screens = screens attribute.save! - } + end end diff --git a/db/migrate/20170419000002_overview_role_ids.rb b/db/migrate/20170419000002_overview_role_ids.rb index a78d18492..5c2a2cd4c 100644 --- a/db/migrate/20170419000002_overview_role_ids.rb +++ b/db/migrate/20170419000002_overview_role_ids.rb @@ -12,11 +12,11 @@ class OverviewRoleIds < ActiveRecord::Migration[4.2] add_index :overviews_roles, [:role_id] Overview.connection.schema_cache.clear! Overview.reset_column_information - Overview.all.each { |overview| + Overview.all.each do |overview| next if overview.role_id.blank? overview.role_ids = [overview.role_id] overview.save! - } + end remove_column :overviews, :role_id Cache.clear diff --git a/db/migrate/20170516000001_trigger_recipient_update.rb b/db/migrate/20170516000001_trigger_recipient_update.rb index bdeb18a96..e35bd4ad5 100644 --- a/db/migrate/20170516000001_trigger_recipient_update.rb +++ b/db/migrate/20170516000001_trigger_recipient_update.rb @@ -4,7 +4,7 @@ class TriggerRecipientUpdate < ActiveRecord::Migration[4.2] # return if it's a new setup return if !Setting.find_by(name: 'system_init_done') - ['auto reply (on new tickets)', 'auto reply (on follow up of tickets)'].each { |name| + ['auto reply (on new tickets)', 'auto reply (on follow up of tickets)'].each do |name| begin trigger = Trigger.find_by(name: name) next if trigger.blank? @@ -17,7 +17,7 @@ class TriggerRecipientUpdate < ActiveRecord::Migration[4.2] rescue => e Rails.logger.error "Unable to update Trigger.find(#{trigger.id}) '#{trigger.inspect}': #{e.message}" end - } + end end end diff --git a/db/migrate/20170822000001_agend_based_sender_issue_1351.rb b/db/migrate/20170822000001_agend_based_sender_issue_1351.rb index 94c47d4a6..12d9fc743 100644 --- a/db/migrate/20170822000001_agend_based_sender_issue_1351.rb +++ b/db/migrate/20170822000001_agend_based_sender_issue_1351.rb @@ -3,12 +3,12 @@ class AgendBasedSenderIssue1351 < ActiveRecord::Migration[4.2] # return if it's a new setup return if !Setting.find_by(name: 'system_init_done') - EmailAddress.all.each { |email_address| + EmailAddress.all.each do |email_address| begin email_address.save! rescue => e Rails.logger.error "Unable to update EmailAddress.find(#{email_address.id}) '#{email_address.inspect}': #{e.message}" end - } + end end end diff --git a/db/migrate/20170830000001_last_owner_update.rb b/db/migrate/20170830000001_last_owner_update.rb index 58c633fea..c3115dc96 100644 --- a/db/migrate/20170830000001_last_owner_update.rb +++ b/db/migrate/20170830000001_last_owner_update.rb @@ -5,10 +5,10 @@ class LastOwnerUpdate < ActiveRecord::Migration[4.2] return if !Setting.find_by(name: 'system_init_done') # reset assignment_timeout to prevent unwanted things happen - Group.all.each { |group| + Group.all.each do |group| group.assignment_timeout = nil group.save! - } + end add_column :tickets, :last_owner_update_at, :timestamp, limit: 3, null: true add_index :tickets, [:last_owner_update_at] @@ -27,12 +27,12 @@ class LastOwnerUpdate < ActiveRecord::Migration[4.2] state_ids = Ticket::State.by_category(:work_on).pluck(:id) if state_ids.present? ticket_ids = Ticket.where('tickets.state_id IN (?) AND tickets.owner_id != 1', state_ids).order(created_at: :desc).limit(1000).pluck(:id) - ticket_ids.each { |ticket_id| + ticket_ids.each do |ticket_id| ticket = Ticket.find_by(id: ticket_id) next if !ticket ticket.last_owner_update_at = last_owner_update_at(ticket) ticket.save! - } + end end end diff --git a/db/seeds/settings.rb b/db/seeds/settings.rb index 58745877e..e4dd649f9 100644 --- a/db/seeds/settings.rb +++ b/db/seeds/settings.rb @@ -184,9 +184,9 @@ Setting.create_or_update( frontend: true ) options = {} -(10..99).each { |item| +(10..99).each do |item| options[item] = item -} +end system_id = rand(10..99) Setting.create_if_not_exists( title: 'SystemID', diff --git a/lib/auto_wizard.rb b/lib/auto_wizard.rb index 9e71fbeed..116679552 100644 --- a/lib/auto_wizard.rb +++ b/lib/auto_wizard.rb @@ -83,27 +83,27 @@ returns # set Settings if auto_wizard_hash['Settings'] - auto_wizard_hash['Settings'].each { |setting_data| + auto_wizard_hash['Settings'].each do |setting_data| Setting.set(setting_data['name'], setting_data['value']) - } + end end # create EmailAddresses/Channels/Signatures model_map = { 'Organizations' => 'Organization', } - model_map.each { |map_name, model| + model_map.each do |map_name, model| next if !auto_wizard_hash[map_name] - auto_wizard_hash[map_name].each { |data| + auto_wizard_hash[map_name].each do |data| generic_object = Kernel.const_get(model) data.symbolize_keys! generic_object.create_or_update_with_ref(data) - } - } + end + end # create Users if auto_wizard_hash['Users'] - auto_wizard_hash['Users'].each { |user_data| + auto_wizard_hash['Users'].each do |user_data| user_data.symbolize_keys! if admin_user.id == 1 @@ -127,7 +127,7 @@ returns if admin_user.email Service::Image.organization_suggest(admin_user.email) end - } + end end # create EmailAddresses/Channels/Signatures @@ -137,14 +137,14 @@ returns 'Signatures' => 'Signature', 'Groups' => 'Group', } - model_map.each { |map_name, model| + model_map.each do |map_name, model| next if !auto_wizard_hash[map_name] - auto_wizard_hash[map_name].each { |data| + auto_wizard_hash[map_name].each do |data| generic_object = Kernel.const_get(model) data.symbolize_keys! generic_object.create_or_update_with_ref(data) - } - } + end + end # reset primary key sequences DbHelper.import_post diff --git a/lib/calendar_subscriptions.rb b/lib/calendar_subscriptions.rb index efb20ce81..fe7686064 100644 --- a/lib/calendar_subscriptions.rb +++ b/lib/calendar_subscriptions.rb @@ -7,13 +7,13 @@ class CalendarSubscriptions @preferences = {} default_preferences = Setting.where(area: 'Defaults::CalendarSubscriptions') - default_preferences.each { |calendar_subscription| + default_preferences.each do |calendar_subscription| next if calendar_subscription.name !~ /\Adefaults_calendar_subscriptions_(.*)\z/ object_name = $1 @preferences[ object_name ] = calendar_subscription.state_current[:value] - } + end return if !@user.preferences[:calendar_subscriptions] return if @user.preferences[:calendar_subscriptions].empty? @@ -22,10 +22,10 @@ class CalendarSubscriptions def all events_data = [] - @preferences.each { |object_name, _sub_structure| + @preferences.each do |object_name, _sub_structure| result = generic_call(object_name) events_data = events_data + result - } + end to_ical(events_data) end diff --git a/lib/core_ext/active_record/connection_adapters/postgresql/schema_statements.rb b/lib/core_ext/active_record/connection_adapters/postgresql/schema_statements.rb index da62e838c..245eda1aa 100644 --- a/lib/core_ext/active_record/connection_adapters/postgresql/schema_statements.rb +++ b/lib/core_ext/active_record/connection_adapters/postgresql/schema_statements.rb @@ -12,13 +12,13 @@ module ActiveRecord column_names = index_columns.split ', ' if column_names.class == Array index_columns_new = [] - column_names.each { |i| + column_names.each do |i| if i =~ /^"(name|login|locale|alias)"$/ || i =~ /name"$/ index_columns_new.push "LOWER(#{i})" else index_columns_new.push i end - } + end index_columns = index_columns_new.join ', ' end diff --git a/lib/core_ext/string.rb b/lib/core_ext/string.rb index 3db6fe1fb..bd94ab2f4 100644 --- a/lib/core_ext/string.rb +++ b/lib/core_ext/string.rb @@ -58,13 +58,13 @@ class String # More details: http://pjambet.github.io/blog/emojis-and-mysql/ def utf8_to_3bytesutf8 return self if Rails.application.config.db_4bytes_utf8 - each_char.select { |c| + each_char.select do |c| if c.bytes.count > 3 Rails.logger.warn "strip out 4 bytes utf8 chars '#{c}' of '#{self}'" next end c - } + end .join('') end @@ -95,14 +95,14 @@ class String link_list = '' counter = 0 if !string_only - string.gsub!(//ix) { + string.gsub!(//ix) do link = $2 counter = counter + 1 link_list += "[#{counter}] #{link}\n" "[#{counter}] " - } + end else - string.gsub!(%r{]*)>(.+?)<[[:space:]]*/a[[:space:]]*>}mxi) { |_placeholder| + string.gsub!(%r{]*)>(.+?)<[[:space:]]*/a[[:space:]]*>}mxi) do |_placeholder| link = $3 text = $6 text.gsub!(/\<.+?\>/, '') @@ -134,7 +134,7 @@ class String else "#{link} (######LINKRAW:#{text}######)" end - } + end end # remove style tags with content @@ -147,12 +147,12 @@ class String end # pre/code handling 1/2 - string.gsub!(%r{
(.+?)
}m) { |placeholder| + string.gsub!(%r{
(.+?)
}m) do |placeholder| placeholder = placeholder.gsub(/\n/, '###BR###') - } - string.gsub!(%r{(.+?)}m) { |placeholder| + end + string.gsub!(%r{(.+?)}m) do |placeholder| placeholder = placeholder.gsub(/\n/, '###BR###') - } + end # insert spaces on [A-z]\n[A-z] string.gsub!(/([A-z])[[:space:]]([A-z])/m, '\1 \2') @@ -161,9 +161,9 @@ class String string.gsub!(/(\n\r|\r\r\n|\r\n|\n)/, '') # blockquote handling - string.gsub!(%r{]*)>(.+?)}m) { + string.gsub!(%r{]*)>(.+?)}m) do "\n" + $2.html2text(true).gsub(/^(.*)$/, '> \1') + "\n" - } + end # pre/code handling 2/2 string.gsub!(/###BR###/, "\n") @@ -192,7 +192,7 @@ class String # add hyperlinks if strict - string.gsub!(%r{([[:space:]])((http|https|ftp|tel)://.+?|(www..+?))([[:space:]]|\.[[:space:]]|,[[:space:]])}mxi) { |_placeholder| + string.gsub!(%r{([[:space:]])((http|https|ftp|tel)://.+?|(www..+?))([[:space:]]|\.[[:space:]]|,[[:space:]])}mxi) do |_placeholder| pre = $1 content = $2 post = $5 @@ -204,7 +204,7 @@ class String else "#{pre}#{content}#{post}" end - } + end end # try HTMLEntities, if it fails on invalid signes, use manual way @@ -221,12 +221,12 @@ class String string.gsub!(' ', ' ') # encode html entities like "–" - string.gsub!(/(&\#(\d+);?)/x) { + string.gsub!(/(&\#(\d+);?)/x) do $2.chr - } + end # encode html entities like "d;" - string.gsub!(/(&\#[xX]([0-9a-fA-F]+);?)/x) { + string.gsub!(/(&\#[xX]([0-9a-fA-F]+);?)/x) do chr_orig = $1 hex = $2.hex if hex @@ -249,7 +249,7 @@ class String chr_orig = '?' end chr_orig - } + end end # remove tailing empty spaces @@ -341,11 +341,11 @@ class String '[[:space:]]*
[[:space:]]*(On|Am|Le|El|Den|Dňa|W dniu|Il|Op|Dne|Dana)[[:space:]]', '[[:space:]]*
[[:space:]]*(On|Am|Le|El|Den|Dňa|W dniu|Il|Op|Dne|Dana)[[:space:]].{1,500} e Rails.logger.error e diff --git a/lib/email_helper/probe.rb b/lib/email_helper/probe.rb index 7faa5373b..a62ca50cb 100644 --- a/lib/email_helper/probe.rb +++ b/lib/email_helper/probe.rb @@ -68,8 +68,8 @@ returns on fail # get mx records, try to find provider based on mx records mx_records = EmailHelper.mx_records(domain) domains = domains.concat(mx_records) - provider_map.each { |_provider, settings| - domains.each { |domain_to_check| + provider_map.each do |_provider, settings| + domains.each do |domain_to_check| next if domain_to_check !~ /#{settings[:domain]}/i @@ -95,8 +95,8 @@ returns on fail content_messages: result_inbound[:content_messages], setting: settings, } - } - } + end + end # probe guess settings @@ -109,7 +109,7 @@ returns on fail setting: {} } success = false - inbound_map.each { |config| + inbound_map.each do |config| # add folder to config if needed if !params[:folder].empty? && config[:options] @@ -127,7 +127,7 @@ returns on fail result[:content_messages] = result_inbound[:content_messages] break - } + end # give up, no possible inbound found if !success @@ -143,7 +143,7 @@ returns on fail outbound_map = outbound_mx + outbound_guess success = false - outbound_map.each { |config| + outbound_map.each do |config| Rails.logger.debug "OUTBOUND PROBE GUESS: #{config.inspect}" result_outbound = EmailHelper::Probe.outbound(config, params[:email]) Rails.logger.debug "OUTBOUND RESULT GUESS: #{result_outbound.inspect}" @@ -153,7 +153,7 @@ returns on fail success = true result[:setting][:outbound] = config break - } + end # give up, no possible outbound found if !success @@ -337,7 +337,7 @@ returns on fail white_map = { 'Recipient address rejected' => true, } - white_map.each { |key, _message| + white_map.each do |key, _message| next if e.message !~ /#{Regexp.escape(key)}/i @@ -346,7 +346,7 @@ returns on fail settings: params, notice: e.message, } - } + end end return { result: 'invalid', @@ -362,9 +362,9 @@ returns on fail end def self.invalid_field(message_backend) - invalid_fields.each { |key, fields| + invalid_fields.each do |key, fields| return fields if message_backend =~ /#{Regexp.escape(key)}/i - } + end {} end @@ -387,9 +387,9 @@ returns on fail end def self.translation(message_backend) - translations.each { |key, message_human| + translations.each do |key, message_human| return message_human if message_backend =~ /#{Regexp.escape(key)}/i - } + end nil end diff --git a/lib/email_helper/verify.rb b/lib/email_helper/verify.rb index 729b98027..933e522de 100644 --- a/lib/email_helper/verify.rb +++ b/lib/email_helper/verify.rb @@ -77,7 +77,7 @@ or end # looking for verify email - 9.times { + 9.times do sleep 5 # fetch mailbox @@ -105,7 +105,7 @@ or next if fetch_result[:result] != 'ok' return fetch_result - } + end { result: 'invalid', diff --git a/lib/enrichment/clearbit/user.rb b/lib/enrichment/clearbit/user.rb index 6a5669f70..392d19f6c 100644 --- a/lib/enrichment/clearbit/user.rb +++ b/lib/enrichment/clearbit/user.rb @@ -156,9 +156,9 @@ module Enrichment def all users = User.of_role(Role.signup_roles) - users.each { |user| + users.each do |user| new(user).synced? - } + end end end end diff --git a/lib/external_credential/facebook.rb b/lib/external_credential/facebook.rb index 750881b31..0c3afcc8d 100644 --- a/lib/external_credential/facebook.rb +++ b/lib/external_credential/facebook.rb @@ -43,17 +43,17 @@ class ExternalCredential::Facebook user = client.get_object('me') #p client.get_connections('me', 'accounts').inspect pages = [] - client.get_connections('me', 'accounts').each { |page| + client.get_connections('me', 'accounts').each do |page| pages.push( id: page['id'], name: page['name'], access_token: page['access_token'], perms: page['perms'], ) - } + end # check if account already exists - Channel.where(area: 'Facebook::Account').each { |channel| + Channel.where(area: 'Facebook::Account').each do |channel| next if !channel.options next if !channel.options['user'] next if !channel.options['user']['id'] @@ -62,7 +62,7 @@ class ExternalCredential::Facebook channel.options['pages'] = pages channel.save return channel - } + end # create channel Channel.create( diff --git a/lib/external_credential/twitter.rb b/lib/external_credential/twitter.rb index 7368a42f6..8b9cfc9ef 100644 --- a/lib/external_credential/twitter.rb +++ b/lib/external_credential/twitter.rb @@ -39,7 +39,7 @@ class ExternalCredential::Twitter user = client.user # check if account already exists - Channel.where(area: 'Twitter::Account').each { |channel| + Channel.where(area: 'Twitter::Account').each do |channel| next if !channel.options next if !channel.options['user'] next if !channel.options['user']['id'] @@ -51,7 +51,7 @@ class ExternalCredential::Twitter channel.options['auth']['oauth_token_secret'] = access_token.secret channel.save return channel - } + end # create channel Channel.create( diff --git a/lib/facebook.rb b/lib/facebook.rb index 4be668974..d082a3d37 100644 --- a/lib/facebook.rb +++ b/lib/facebook.rb @@ -61,13 +61,13 @@ result def pages pages = [] - @client.get_connections('me', 'accounts').each { |page| + @client.get_connections('me', 'accounts').each do |page| pages.push( id: page['id'], name: page['name'], access_token: page['access_token'], ) - } + end pages end @@ -141,12 +141,12 @@ result } # ignore if value is already set - map.each { |target, source| + map.each do |target, source| next if user[target] && !user[target].empty? new_value = tweet_user.send(source).to_s next if !new_value || new_value.empty? user_data[target] = new_value - } + end user.update!(user_data) else user_data[:login] = item_user['id'] @@ -237,14 +237,14 @@ result to = nil if post['to'] && post['to']['data'] - post['to']['data'].each { |to_entry| + post['to']['data'].each do |to_entry| if !to to = '' else to += ', ' end to += to_entry['name'] - } + end end feed_post = { @@ -267,7 +267,7 @@ result base_url = ticket.preferences['facebook']['permalink_url'] end - articles.each { |article| + articles.each do |article| next if Ticket::Article.find_by(message_id: article[:message_id]) # set ticket state to open if not new @@ -305,7 +305,7 @@ result }, }.merge(article) Ticket::Article.create(article) - } + end end def to_group(post, group_id, channel, page) @@ -360,13 +360,13 @@ result def access_token_for_page(lookup) access_token = nil - pages.each { |page| + pages.each do |page| next if !lookup[:page_id] && !lookup[:page] next if lookup[:page_id] && lookup[:page_id].to_s != page[:id] next if lookup[:page] && lookup[:page] != page[:name] access_token = page[:access_token] break - } + end access_token end @@ -378,7 +378,7 @@ result result = [] return result if comments.empty? - comments.each { |comment| + comments.each do |comment| user = to_user(comment) next if !user article_data = { @@ -392,7 +392,7 @@ result sub_comments = @client.get_object("#{comment['id']}/comments", fields: 'id,from,to,message,created_time') sub_articles = nested_comments(sub_comments, comment['id']) result += sub_articles - } + end result end diff --git a/lib/fill_db.rb b/lib/fill_db.rb index 32e8c593f..b36404278 100644 --- a/lib/fill_db.rb +++ b/lib/fill_db.rb @@ -30,10 +30,10 @@ e. g. ActiveRecord::Base.transaction do - (1..organizations).each { + (1..organizations).each do organization = Organization.create( name: 'FillOrganization::' + rand(999_999).to_s, active: true ) organization_pool.push organization - } + end end else @@ -49,7 +49,7 @@ e. g. ActiveRecord::Base.transaction do - (1..agents).each { + (1..agents).each do suffix = rand(99_999).to_s user = User.create_or_update( login: "filldb-agent-#{suffix}", @@ -62,7 +62,7 @@ e. g. groups: groups_all, ) agent_pool.push user - } + end end else @@ -78,7 +78,7 @@ e. g. ActiveRecord::Base.transaction do - (1..customers).each { + (1..customers).each do suffix = rand(99_999).to_s organization = nil if !organization_pool.empty? && rand(2) == 1 @@ -95,7 +95,7 @@ e. g. roles: roles, ) customer_pool.push user - } + end end else @@ -110,16 +110,16 @@ e. g. ActiveRecord::Base.transaction do - (1..groups).each { + (1..groups).each do group = Group.create( name: 'FillGroup::' + rand(999_999).to_s, active: true ) group_pool.push group - Role.where(name: 'Agent').first.users.where(active: true).each { |user| + Role.where(name: 'Agent').first.users.where(active: true).each do |user| user_groups = user.groups user_groups.push group user.groups = user_groups user.save - } - } + end + end end else @@ -135,7 +135,7 @@ e. g. ActiveRecord::Base.transaction do - (1..tickets).each { + (1..tickets).each do customer = customer_pool[ rand(customer_pool.length - 1) ] agent = agent_pool[ rand(agent_pool.length - 1) ] ticket = Ticket.create( @@ -162,7 +162,7 @@ e. g. updated_by_id: agent.id, created_by_id: agent.id, ) - } + end end end diff --git a/lib/html_sanitizer.rb b/lib/html_sanitizer.rb index 6882147f3..5abb5b979 100644 --- a/lib/html_sanitizer.rb +++ b/lib/html_sanitizer.rb @@ -54,16 +54,16 @@ satinize html string based on whiltelist if node && node.name != 'a' && node.parent && node.parent.name != 'a' && (!node.parent.parent || node.parent.parent.name != 'a') if node.class == Nokogiri::XML::Text urls = [] - node.content.scan(%r{((http|https|ftp|tel)://.+?)([[:space:]]|\.[[:space:]]|,[[:space:]]|\.$|,$|\)|\(|$)}mxi).each { |match| + node.content.scan(%r{((http|https|ftp|tel)://.+?)([[:space:]]|\.[[:space:]]|,[[:space:]]|\.$|,$|\)|\(|$)}mxi).each do |match| if match[0] urls.push match[0].to_s.strip end - } - node.content.scan(/(^|:|;|\s)(www\..+?)([[:space:]]|\.[[:space:]]|,[[:space:]]|\.$|,$|\)|\(|$)/mxi).each { |match| + end + node.content.scan(/(^|:|;|\s)(www\..+?)([[:space:]]|\.[[:space:]]|,[[:space:]]|\.$|,$|\)|\(|$)/mxi).each do |match| if match[1] urls.push match[1].to_s.strip end - } + end next if urls.empty? add_link(node.content, urls, node) end @@ -119,13 +119,13 @@ satinize html string based on whiltelist if node['class'] classes = node['class'].gsub(/\t|\n|\r/, '').split(' ') class_new = '' - classes.each { |local_class| + classes.each do |local_class| next if !classes_whitelist.include?(local_class.to_s.strip) if class_new != '' class_new += ' ' end class_new += local_class - } + end if class_new != '' node['class'] = class_new else @@ -134,7 +134,7 @@ satinize html string based on whiltelist end # move style attributes to css attributes - attributes_2_css.each { |key| + attributes_2_css.each do |key| next if !node[key] if node['style'].empty? node['style'] = '' @@ -148,20 +148,20 @@ satinize html string based on whiltelist value += 'px' end node['style'] += "#{key}:#{value}" - } + end # clean style / only use allowed style properties if node['style'] pears = node['style'].downcase.gsub(/\t|\n|\r/, '').split(';') style = '' - pears.each { |local_pear| + pears.each do |local_pear| prop = local_pear.split(':') next if !prop[0] key = prop[0].strip next if !css_properties_whitelist.include?(node.name) next if !css_properties_whitelist[node.name].include?(key) style += "#{local_pear};" - } + end node['style'] = style if style == '' node.delete('style') @@ -169,19 +169,19 @@ satinize html string based on whiltelist end # scan for invalid link content - %w(href style).each { |attribute_name| + %w(href style).each do |attribute_name| next if !node[attribute_name] href = cleanup_target(node[attribute_name]) next if href !~ /(javascript|livescript|vbscript):/i node.delete(attribute_name) - } + end # remove attributes if not whitelisted - node.each { |attribute, _value| + node.each do |attribute, _value| attribute_name = attribute.downcase next if attributes_whitelist[:all].include?(attribute_name) || (attributes_whitelist[node.name] && attributes_whitelist[node.name].include?(attribute_name)) node.delete(attribute) - } + end # remove mailto links if node['href'] @@ -243,7 +243,7 @@ cleanup html string: next if !tags_backlist.include?(node.name) hit = false local_node = nil - (1..5).each { |_count| + (1..5).each do |_count| local_node = if local_node local_node.parent else @@ -252,7 +252,7 @@ cleanup html string: break if !local_node next if local_node.name != 'td' hit = true - } + end next if hit && node.keys.count.positive? node.replace cleanup_replace_tags(node.children.to_s) Loofah::Scrubber::STOP @@ -449,7 +449,7 @@ satinize style of img tags style = 'max-width:100%;' if node['style'] pears = node['style'].downcase.gsub(/\t|\n|\r/, '').split(';') - pears.each { |local_pear| + pears.each do |local_pear| prop = local_pear.split(':') next if !prop[0] key = prop[0].strip @@ -457,7 +457,7 @@ satinize style of img tags key = 'max-height' end style += "#{key}:#{prop[1]};" - } + end end node['style'] = style end diff --git a/lib/idoit.rb b/lib/idoit.rb index 271211bf4..909bc14be 100644 --- a/lib/idoit.rb +++ b/lib/idoit.rb @@ -125,11 +125,11 @@ or with filter: # add link to idoit if result.data['result'].class == Array - result.data['result'].each { |item| + result.data['result'].each do |item| next if !item['id'] item['link'] = "#{_url_cleanup_baseurl(url)}/?objID=#{item['id']}" item['link'].gsub!(%r{([^:])//+}, '\\1/') - } + end end result.data end diff --git a/lib/import/helper.rb b/lib/import/helper.rb index 596508809..3a2d5f7f2 100644 --- a/lib/import/helper.rb +++ b/lib/import/helper.rb @@ -20,11 +20,11 @@ module Import end def utf8_encode(data) - data.each { |key, value| + data.each do |key, value| next if !value next if value.class != String data[key] = Encode.conv('utf8', value) - } + end end def reset_primary_key_sequence(table) diff --git a/lib/import/otrs.rb b/lib/import/otrs.rb index 9741a5de6..3223b7327 100644 --- a/lib/import/otrs.rb +++ b/lib/import/otrs.rb @@ -79,9 +79,9 @@ module Import Thread.abort_on_exception = true threads = {} - (1..thread_count).each { |thread| + (1..thread_count).each do |thread| - threads[thread] = Thread.new { + threads[thread] = Thread.new do # In some environments the Model.reset_column_information # is not reflected to threads. So an import error message appears. @@ -108,11 +108,11 @@ module Import Thread.current[:loop_count] += 1 end ActiveRecord::Base.connection.close - } - } - (1..thread_count).each { |thread| + end + end + (1..thread_count).each do |thread| threads[thread].join - } + end end def limit_import(remote_object, args = {}) diff --git a/lib/import/otrs/async.rb b/lib/import/otrs/async.rb index 0e7d22641..5b74a6e91 100644 --- a/lib/import/otrs/async.rb +++ b/lib/import/otrs/async.rb @@ -10,7 +10,7 @@ module Import Import::OTRS::Requester.connection_test # start thread to observe current state - status_update_thread = Thread.new { + status_update_thread = Thread.new do loop do result = { data: current_state, @@ -19,7 +19,7 @@ module Import Cache.write('import:state', result, expires_in: 10.minutes) sleep 8 end - } + end sleep 2 # start import data diff --git a/lib/import/otrs/helper.rb b/lib/import/otrs/helper.rb index 107b74956..784e7b247 100644 --- a/lib/import/otrs/helper.rb +++ b/lib/import/otrs/helper.rb @@ -10,11 +10,11 @@ module Import result = {} # use the mapping of the class in which # this module gets extended - self.class::MAPPING.each { |key_sym, value| + self.class::MAPPING.each do |key_sym, value| key = key_sym.to_s next if !record.key?(key) result[value] = record[key] - } + end result end diff --git a/lib/import/otrs/import_stats.rb b/lib/import/otrs/import_stats.rb index 59c7644bd..5929bcbee 100644 --- a/lib/import/otrs/import_stats.rb +++ b/lib/import/otrs/import_stats.rb @@ -64,9 +64,9 @@ module Import def sum_stat(objects) data = statistic sum = 0 - objects.each { |object| + objects.each do |object| sum += data[object] - } + end sum end end diff --git a/lib/import/otrs/state_factory.rb b/lib/import/otrs/state_factory.rb index dd40f914e..aaf59d66f 100644 --- a/lib/import/otrs/state_factory.rb +++ b/lib/import/otrs/state_factory.rb @@ -12,10 +12,10 @@ module Import def backup # rename states to handle not uniq issues - ::Ticket::State.all.each { |state| + ::Ticket::State.all.each do |state| state.name = state.name + '_tmp' state.save - } + end end def import_loop(records, *_args, &import_block) diff --git a/lib/import/otrs/ticket.rb b/lib/import/otrs/ticket.rb index 3c17fecef..45fdd35c0 100644 --- a/lib/import/otrs/ticket.rb +++ b/lib/import/otrs/ticket.rb @@ -87,7 +87,7 @@ module Import def dynamic_fields(ticket) result = {} - ticket.keys.each { |key| + ticket.keys.each do |key| key_string = key.to_s @@ -98,7 +98,7 @@ module Import dynamic_field_name = Import::OTRS::DynamicField.convert_name(dynamic_field_name) result[dynamic_field_name.to_sym] = ticket[key_string] - } + end result end @@ -142,14 +142,14 @@ module Import def first_customer_id(articles) user_id = nil - articles.each { |article| + articles.each do |article| next if article['SenderType'] != 'customer' next if article['From'].empty? user = Import::OTRS::ArticleCustomer.find(article) break if !user user_id = user.id break - } + end user_id end @@ -161,10 +161,10 @@ module Import end def fix_timestamps(ticket) - ticket.each { |key, value| + ticket.each do |key, value| next if value != '0000-00-00 00:00:00' ticket[key] = nil - } + end end # fix OTRS 3.1 bug, no close time if ticket is created diff --git a/lib/import/otrs/user.rb b/lib/import/otrs/user.rb index e1d40fd43..f52acdf53 100644 --- a/lib/import/otrs/user.rb +++ b/lib/import/otrs/user.rb @@ -92,7 +92,7 @@ module Import def group_ids(user) result = [] queues = Import::OTRS::Requester.load('Queue') - queues.each { |queue| + queues.each do |queue| permissions = user['GroupIDs'][ queue['GroupID'] ] @@ -100,7 +100,7 @@ module Import next if !permissions.include?('rw') result.push queue['QueueID'] - } + end # lookup by roles @@ -113,11 +113,11 @@ module Import def role_ids(user) local_role_ids = [] - roles(user).each { |role| + roles(user).each do |role| role_lookup = Role.lookup(name: role) next if !role_lookup local_role_ids.push role_lookup.id - } + end local_role_ids end @@ -135,9 +135,9 @@ module Import def groups_from_groups(role_object, groups) result = [] - groups.each { |group| + groups.each do |group| result += groups_from_otrs_group(role_object, group) - } + end result end @@ -162,10 +162,10 @@ module Import def groups_from_otrs_roles(user) result = [] roles = Import::OTRS::Requester.load('Role') - roles.each { |role| + roles.each do |role| next if !user['RoleIDs'].include?(role['ID']) result += groups_from_otrs_groups(role['GroupIDs']) - } + end result end end diff --git a/lib/import/zendesk/async.rb b/lib/import/zendesk/async.rb index 77b7bc3b6..7ae735bc8 100644 --- a/lib/import/zendesk/async.rb +++ b/lib/import/zendesk/async.rb @@ -13,7 +13,7 @@ module Import statistic # start thread to observe current state - status_update_thread = Thread.new { + status_update_thread = Thread.new do loop do result = { data: current_state, @@ -22,7 +22,7 @@ module Import Cache.write('import:state', result, expires_in: 10.minutes) sleep 8 end - } + end sleep 2 # start import data diff --git a/lib/import/zendesk/helper.rb b/lib/import/zendesk/helper.rb index bdd210f57..34c606b71 100644 --- a/lib/import/zendesk/helper.rb +++ b/lib/import/zendesk/helper.rb @@ -9,9 +9,9 @@ module Import def get_fields(zendesk_fields) return {} if !zendesk_fields fields = {} - zendesk_fields.each { |key, value| + zendesk_fields.each do |key, value| fields[key] = value - } + end fields end end diff --git a/lib/import/zendesk/import_stats.rb b/lib/import/zendesk/import_stats.rb index b60e30124..d32b084e0 100644 --- a/lib/import/zendesk/import_stats.rb +++ b/lib/import/zendesk/import_stats.rb @@ -49,9 +49,9 @@ module Import 'Automations' => 0, } - result.each { |object, _score| + result.each do |object, _score| result[ object ] = statistic_count(object) - } + end Cache.write('import_zendesk_stats', result) result diff --git a/lib/import/zendesk/object_attribute/select.rb b/lib/import/zendesk/object_attribute/select.rb index f557aca68..c041adec4 100644 --- a/lib/import/zendesk/object_attribute/select.rb +++ b/lib/import/zendesk/object_attribute/select.rb @@ -17,9 +17,9 @@ module Import def options(object_attribte) result = {} - object_attribte.custom_field_options.each { |entry| + object_attribte.custom_field_options.each do |entry| result[ entry['value'] ] = entry['name'] - } + end result end end diff --git a/lib/import/zendesk/ticket_factory.rb b/lib/import/zendesk/ticket_factory.rb index fbba1fb22..ebc313724 100644 --- a/lib/import/zendesk/ticket_factory.rb +++ b/lib/import/zendesk/ticket_factory.rb @@ -10,10 +10,10 @@ module Import def import_loop(records, *args) - count_update_hook = proc { |record| + count_update_hook = proc do |record| yield(record) update_ticket_count(records) - } + end super(records, *args, &count_update_hook) end diff --git a/lib/import/zendesk/user/group.rb b/lib/import/zendesk/user/group.rb index 0fe82e247..afeb8fe7a 100644 --- a/lib/import/zendesk/user/group.rb +++ b/lib/import/zendesk/user/group.rb @@ -16,7 +16,7 @@ module Import groups = [] return groups if mapping[user.id].empty? - mapping[user.id].each { |zendesk_group_id| + mapping[user.id].each do |zendesk_group_id| local_group_id = Import::Zendesk::GroupFactory.local_id(zendesk_group_id) @@ -25,7 +25,7 @@ module Import group = ::Group.find( local_group_id ) groups.push(group) - } + end groups end @@ -37,11 +37,11 @@ module Import @mapping = {} - Import::Zendesk::Requester.client.group_memberships.all! { |group_membership| + Import::Zendesk::Requester.client.group_memberships.all! do |group_membership| @mapping[ group_membership.user_id ] ||= [] @mapping[ group_membership.user_id ].push( group_membership.group_id ) - } + end @mapping end diff --git a/lib/ldap/group.rb b/lib/ldap/group.rb index 87bd051ea..39bfef153 100644 --- a/lib/ldap/group.rb +++ b/lib/ldap/group.rb @@ -58,9 +58,9 @@ class Ldap return {} if filter.blank? groups = {} - @ldap.search(filter, base: base_dn, attributes: %w(dn)) { |entry| + @ldap.search(filter, base: base_dn, attributes: %w(dn)) do |entry| groups[entry.dn.downcase] = entry.dn.downcase - } + end groups end diff --git a/lib/ldap/user.rb b/lib/ldap/user.rb index 681fe9028..c10cae694 100644 --- a/lib/ldap/user.rb +++ b/lib/ldap/user.rb @@ -61,11 +61,11 @@ class Ldap # @return [String] The uid attribute. def self.uid_attribute(attributes) result = nil - %i(samaccountname userprincipalname uid dn).each { |attribute| + %i(samaccountname userprincipalname uid dn).each do |attribute| next if attributes[attribute].blank? result = attribute.to_s break - } + end result end diff --git a/lib/mixin/instance_wrapper.rb b/lib/mixin/instance_wrapper.rb index 96e8ff8e3..a7d8d2903 100644 --- a/lib/mixin/instance_wrapper.rb +++ b/lib/mixin/instance_wrapper.rb @@ -16,9 +16,9 @@ module Mixin # # @return [nil] def wrap(variable) - define_method(:instance) { + define_method(:instance) do instance_variable_get(variable) - } + end end end diff --git a/lib/models.rb b/lib/models.rb index a7a1140fa..f51965948 100644 --- a/lib/models.rb +++ b/lib/models.rb @@ -69,11 +69,11 @@ returns def self.searchable models = [] - all.each { |model_class, _options| + all.each do |model_class, _options| next if !model_class next if !model_class.respond_to? :search_preferences models.push model_class - } + end models end @@ -117,13 +117,13 @@ returns ref_attributes.push 'created_by_id' ref_attributes.push 'updated_by_id' end - list.each { |model_class, model_attributes| + list.each do |model_class, model_attributes| if !references[model_class.to_s] references[model_class.to_s] = {} end next if !model_attributes[:attributes] - ref_attributes.each { |item| + ref_attributes.each do |item| next if !model_attributes[:attributes].include?(item) count = model_class.where("#{item} = ?", object_id).count @@ -133,13 +133,13 @@ returns end Rails.logger.debug "FOUND (by id) #{model_class}->#{item} #{count}!" references[model_class.to_s][item] += count - } - } + end + end # find relations via reflections - list.each { |model_class, model_attributes| + list.each do |model_class, model_attributes| next if !model_attributes[:reflections] - model_attributes[:reflections].each { |_reflection_key, reflection_value| + model_attributes[:reflections].each do |_reflection_key, reflection_value| next if reflection_value.macro != :belongs_to col_name = "#{reflection_value.name}_id" @@ -165,14 +165,14 @@ returns end Rails.logger.debug "FOUND (by ref with class) #{model_class}->#{col_name} #{count}!" references[model_class.to_s][col_name] += count - } - } + end + end # cleanup, remove models with empty references - references.each { |k, v| + references.each do |k, v| next if !v.empty? references.delete(k) - } + end references end @@ -192,11 +192,11 @@ returns def self.references_total(object_name, object_id) references = references(object_name, object_id) total = 0 - references.each { |_model, model_references| - model_references.each { |_col, count| + references.each do |_model, model_references| + model_references.each do |_col, count| total += count - } - } + end + end total end @@ -224,28 +224,28 @@ returns # update references references = references(object_name, object_id_to_merge) - references.each { |model, attributes| + references.each do |model, attributes| model_object = Object.const_get(model) # collect items and attributes to update items_to_update = {} - attributes.each { |attribute, _count| + attributes.each do |attribute, _count| Rails.logger.debug "#{object_name}: #{model}.#{attribute}->#{object_id_to_merge}->#{object_id_primary}" - model_object.where("#{attribute} = ?", object_id_to_merge).each { |item| + model_object.where("#{attribute} = ?", object_id_to_merge).each do |item| if !items_to_update[item.id] items_to_update[item.id] = item end items_to_update[item.id][attribute.to_sym] = object_id_primary - } - } + end + end # update items ActiveRecord::Base.transaction do - items_to_update.each { |_id, item| + items_to_update.each do |_id, item| item.save! - } + end end - } + end true end end diff --git a/lib/notification_factory/mailer.rb b/lib/notification_factory/mailer.rb index 12f810e12..68dec4cf8 100644 --- a/lib/notification_factory/mailer.rb +++ b/lib/notification_factory/mailer.rb @@ -68,12 +68,12 @@ returns hit = true else hit = false - selected_group_ids.each { |selected_group_id| + selected_group_ids.each do |selected_group_id| if selected_group_id.to_s == ticket.group_id.to_s hit = true break end - } + end end return if !hit # no group access end @@ -207,13 +207,13 @@ retunes def self.already_sent?(ticket, recipient, type) result = ticket.history_get() count = 0 - result.each { |item| + result.each do |item| next if item['type'] != 'notification' next if item['object'] != 'Ticket' next if item['value_to'] !~ /#{recipient.email}/i next if item['value_to'] !~ /#{type}/i count += 1 - } + end count end diff --git a/lib/notification_factory/renderer.rb b/lib/notification_factory/renderer.rb index e0c9f1229..680200f5e 100644 --- a/lib/notification_factory/renderer.rb +++ b/lib/notification_factory/renderer.rb @@ -76,7 +76,7 @@ examples how to use return "\#{#{key} / no such method}" end object_methods_s = '' - object_methods.each { |method_raw| + object_methods.each do |method_raw| method = method_raw.strip @@ -100,7 +100,7 @@ examples how to use rescue => e object_refs = "\#{#{object_name}.#{object_methods_s} / e.message}" end - } + end placeholder = if !value object_refs else diff --git a/lib/push_messages.rb b/lib/push_messages.rb index 2edeeda4b..b1b2a8ff1 100644 --- a/lib/push_messages.rb +++ b/lib/push_messages.rb @@ -34,7 +34,7 @@ module PushMessages def self.finish return false if !enabled? - Thread.current[:push_messages].each { |message| + Thread.current[:push_messages].each do |message| if message[:type] == 'send_to' Sessions.send_to(message[:user_id], message[:data]) else @@ -44,7 +44,7 @@ module PushMessages message[:data][:current_user_id], ) end - } + end Thread.current[:push_messages] = nil true end diff --git a/lib/report/article_by_type_sender.rb b/lib/report/article_by_type_sender.rb index 575146769..85f1660c0 100644 --- a/lib/report/article_by_type_sender.rb +++ b/lib/report/article_by_type_sender.rb @@ -43,7 +43,7 @@ returns start = Time.zone.parse(params[:range_start]) stop_interval = 60 end - (1..stop_interval).each { |_counter| + (1..stop_interval).each do |_counter| if params[:interval] == 'month' stop = start.next_month elsif params[:interval] == 'week' @@ -69,7 +69,7 @@ returns ).count result.push count start = stop - } + end result end diff --git a/lib/report/base.rb b/lib/report/base.rb index 98ffe2e1e..ada98a0f1 100644 --- a/lib/report/base.rb +++ b/lib/report/base.rb @@ -129,10 +129,10 @@ class Report::Base 'histories.created_at >= ? AND histories.created_at <= ? AND histories.history_object_id = ? AND histories.history_type_id = ?', data[:start], data[:end], history_object.id, history_type.id ) .where(query, *bind_params).joins(tables) - histories.each { |history| + histories.each do |history| count += 1 ticket_ids.push history.o_id - } + end return { count: count, ticket_ids: ticket_ids, @@ -210,10 +210,10 @@ class Report::Base data[:id_to], ) end - histories.each { |history| + histories.each do |history| count += 1 ticket_ids.push history.o_id - } + end end return { count: count, @@ -233,7 +233,7 @@ class Report::Base .where(query, *bind_params).joins(tables) tickets = 0 time_total = 0 - ticket_list.each { |ticket| + ticket_list.each do |ticket| timestamp = ticket[ data[:type].to_sym ] next if !timestamp # puts 'FR:' + first_response.to_s @@ -242,7 +242,7 @@ class Report::Base #puts 'DIFF:' + diff.to_s time_total = time_total + diff tickets += 1 - } + end if time_total.zero? || tickets.zero? tickets = -0.001 else @@ -265,7 +265,7 @@ class Report::Base tickets = 0 time_min = 0 ticket_ids = [] - ticket_list.each { |ticket| + ticket_list.each do |ticket| timestamp = ticket[ data[:type].to_sym ] next if !timestamp ticket_ids.push ticket.id @@ -279,7 +279,7 @@ class Report::Base if diff < time_min time_min = diff end - } + end tickets = if time_min.zero? -0.001 else @@ -302,7 +302,7 @@ class Report::Base tickets = 0 time_max = 0 ticket_ids = [] - ticket_list.each { |ticket| + ticket_list.each do |ticket| timestamp = ticket[ data[:type].to_sym ] next if !timestamp ticket_ids.push ticket.id @@ -317,7 +317,7 @@ class Report::Base if diff > time_max time_max = diff end - } + end tickets = if time_max.zero? -0.001 else @@ -332,11 +332,11 @@ class Report::Base def self.ticket_condition(ticket_id, condition) ticket = Ticket.lookup( id: ticket_id ) match = true - condition.each { |key, value| + condition.each do |key, value| if ticket[key.to_sym] != value return false end - } + end true end diff --git a/lib/report/ticket_backlog.rb b/lib/report/ticket_backlog.rb index 5948ae0a3..f2aabe284 100644 --- a/lib/report/ticket_backlog.rb +++ b/lib/report/ticket_backlog.rb @@ -27,10 +27,10 @@ returns closed = Report::TicketGenericTime.aggs(local_params) result = [] - (0..created.length - 1).each { |position| + (0..created.length - 1).each do |position| count = created[position] - closed[position] result.push count - } + end result end diff --git a/lib/report/ticket_first_solution.rb b/lib/report/ticket_first_solution.rb index fde96db8f..91302a94d 100644 --- a/lib/report/ticket_first_solution.rb +++ b/lib/report/ticket_first_solution.rb @@ -38,7 +38,7 @@ returns start = Time.zone.parse(params[:range_start]) stop_interval = 60 end - (1..stop_interval).each { |_counter| + (1..stop_interval).each do |_counter| if params[:interval] == 'month' stop = start.next_month elsif params[:interval] == 'week' @@ -57,16 +57,16 @@ returns stop, ).where(query, *bind_params).joins(tables) count = 0 - ticket_list.each { |ticket| + ticket_list.each do |ticket| closed_at = ticket.close_at created_at = ticket.created_at if (closed_at - (60 * 15) ) < created_at count += 1 end - } + end result.push count start = stop - } + end result end @@ -98,7 +98,7 @@ returns count = 0 assets = {} ticket_ids = [] - ticket_list.each { |ticket| + ticket_list.each do |ticket| closed_at = ticket.close_at created_at = ticket.created_at if (closed_at - (60 * 15) ) < created_at @@ -107,7 +107,7 @@ returns end ticket_full = Ticket.find(ticket.id) assets = ticket_full.assets(assets) - } + end { count: count, ticket_ids: ticket_ids, diff --git a/lib/report/ticket_generic_time.rb b/lib/report/ticket_generic_time.rb index 71cb6a992..0eaba33e2 100644 --- a/lib/report/ticket_generic_time.rb +++ b/lib/report/ticket_generic_time.rb @@ -53,7 +53,7 @@ returns stop_interval = 60 end result = [] - (1..stop_interval).each { |_counter| + (1..stop_interval).each do |_counter| match = false if !result_es raise "Invalid es result #{result_es.inspect}" @@ -67,7 +67,7 @@ returns if !result_es['aggregations']['time_buckets']['buckets'] raise "Invalid es result, no buckets #{result_es.inspect}" end - result_es['aggregations']['time_buckets']['buckets'].each { |item| + result_es['aggregations']['time_buckets']['buckets'].each do |item| if params[:interval] == 'minute' item['key_as_string'] = item['key_as_string'].sub(/:\d\d.\d\d\dZ$/, '') start_string = start.iso8601.sub(/:\d\dZ$/, '') @@ -90,7 +90,7 @@ returns elsif params[:interval] == 'minute' start = start + 1.minute end - } + end next if match result.push 0 if params[:interval] == 'month' @@ -104,7 +104,7 @@ returns elsif params[:interval] == 'minute' start = start + 1.minute end - } + end result end @@ -147,10 +147,10 @@ returns result = SearchIndexBackend.selectors(['Ticket'], selector, limit, nil, aggs_interval) assets = {} - result[:ticket_ids].each { |ticket_id| + result[:ticket_ids].each do |ticket_id| ticket_full = Ticket.find(ticket_id) assets = ticket_full.assets(assets) - } + end result[:assets] = assets result end diff --git a/lib/report/ticket_moved.rb b/lib/report/ticket_moved.rb index b105f78c1..83df739d4 100644 --- a/lib/report/ticket_moved.rb +++ b/lib/report/ticket_moved.rb @@ -46,7 +46,7 @@ returns start = Time.zone.parse(params[:range_start]) stop_interval = 60 end - (1..stop_interval).each { |_counter| + (1..stop_interval).each do |_counter| if params[:interval] == 'month' stop = start.next_month elsif params[:interval] == 'week' @@ -75,7 +75,7 @@ returns count = history_count(local_params) result.push count start = stop - } + end result end @@ -124,10 +124,10 @@ returns local_params = defaults.merge(local_params) result = history(local_params) assets = {} - result[:ticket_ids].each { |ticket_id| + result[:ticket_ids].each do |ticket_id| ticket_full = Ticket.find(ticket_id) assets = ticket_full.assets(assets) - } + end result[:assets] = assets result end diff --git a/lib/report/ticket_reopened.rb b/lib/report/ticket_reopened.rb index 3a9ddda81..9046e82d9 100644 --- a/lib/report/ticket_reopened.rb +++ b/lib/report/ticket_reopened.rb @@ -40,7 +40,7 @@ returns start = Time.zone.parse(params[:range_start]) stop_interval = 60 end - (1..stop_interval).each { |_counter| + (1..stop_interval).each do |_counter| if params[:interval] == 'month' stop = start.next_month elsif params[:interval] == 'week' @@ -64,7 +64,7 @@ returns ) result.push count start = stop - } + end result end @@ -99,10 +99,10 @@ returns selector: params[:selector] ) assets = {} - result[:ticket_ids].each { |ticket_id| + result[:ticket_ids].each do |ticket_id| ticket_full = Ticket.find(ticket_id) assets = ticket_full.assets(assets) - } + end result[:assets] = assets result end @@ -113,11 +113,11 @@ returns return ticket_state_ids if ticket_state_ids ticket_state_types = Ticket::StateType.where( name: %w(closed merged removed) ) ticket_state_ids = [] - ticket_state_types.each { |ticket_state_type| - ticket_state_type.states.each { |ticket_state| + ticket_state_types.each do |ticket_state_type| + ticket_state_type.states.each do |ticket_state| ticket_state_ids.push ticket_state.id - } - } + end + end Cache.write( key, ticket_state_ids, { expires_in: 2.days } ) ticket_state_ids end diff --git a/lib/search_index_backend.rb b/lib/search_index_backend.rb index 065724f79..893a5e920 100644 --- a/lib/search_index_backend.rb +++ b/lib/search_index_backend.rb @@ -154,10 +154,10 @@ return search result return [] if !query if index.class == Array ids = [] - index.each { |local_index| + index.each do |local_index| local_ids = search_by_index(query, limit, local_index, query_extention) ids = ids.concat(local_ids) - } + end return ids end search_by_index(query, limit, index, query_extention) @@ -241,14 +241,14 @@ return search result return ids if !data return ids if !data['hits'] return ids if !data['hits']['hits'] - data['hits']['hits'].each { |item| + data['hits']['hits'].each do |item| Rails.logger.info "... #{item['_type']} #{item['_id']}" data = { id: item['_id'], type: item['_type'], } ids.push data - } + end ids end @@ -331,9 +331,9 @@ get count of tickets and tickets which match on selector if !aggs_interval || !aggs_interval[:interval] ticket_ids = [] - response.data['hits']['hits'].each { |item| + response.data['hits']['hits'].each do |item| ticket_ids.push item['_id'] - } + end return { count: response.data['hits']['total'], ticket_ids: ticket_ids, @@ -346,7 +346,7 @@ get count of tickets and tickets which match on selector query_must = [] query_must_not = [] if selector && !selector.empty? - selector.each { |key, data| + selector.each do |key, data| key_tmp = key.sub(/^.+?\./, '') t = {} if data['value'].class == Array @@ -367,7 +367,7 @@ get count of tickets and tickets which match on selector else raise "unknown operator '#{data['operator']}'" end - } + end end data = { query: {}, diff --git a/lib/session_helper.rb b/lib/session_helper.rb index fbb4c0bcc..ef72786d6 100644 --- a/lib/session_helper.rb +++ b/lib/session_helper.rb @@ -7,10 +7,10 @@ module SessionHelper # load collections to deliver from external files dir = File.expand_path('../../', __FILE__) files = Dir.glob( "#{dir}/app/controllers/sessions/collection_*.rb") - files.each { |file| + files.each do |file| load file (default_collection, assets) = ExtraCollection.session(default_collection, assets, user) - } + end [default_collection, assets] end @@ -18,10 +18,10 @@ module SessionHelper def self.models(user = nil) models = {} objects = ObjectManager.list_objects - objects.each { |object| + objects.each do |object| attributes = ObjectManager::Attribute.by_object(object, user) models[object] = attributes - } + end models end diff --git a/lib/sessions.rb b/lib/sessions.rb index c6e3d4435..a78b29a2d 100644 --- a/lib/sessions.rb +++ b/lib/sessions.rb @@ -42,9 +42,9 @@ returns # store session data in session file FileUtils.mkpath path_tmp - File.open(session_file, 'wb') { |file| + File.open(session_file, 'wb') do |file| file.write content - } + end # destroy old session if needed if File.exist?(path) @@ -148,11 +148,11 @@ returns def self.list client_ids = sessions session_list = {} - client_ids.each { |client_id| + client_ids.each do |client_id| data = get(client_id) next if !data session_list[client_id] = data - } + end session_list end @@ -188,12 +188,12 @@ returns def self.destroy_idle_sessions(idle_time_in_sec = 240) list_of_closed_sessions = [] clients = Sessions.list - clients.each { |client_id, client| + clients.each do |client_id, client| if !client[:meta] || !client[:meta][:last_ping] || ( client[:meta][:last_ping].to_i + idle_time_in_sec ) < Time.now.utc.to_i list_of_closed_sessions.push client_id Sessions.destroy(client_id) end - } + end list_of_closed_sessions end @@ -214,11 +214,11 @@ returns return false if !data path = "#{@path}/#{client_id}" data[:meta][:last_ping] = Time.now.utc.to_i - File.open("#{path}/session", 'wb' ) { |file| + File.open("#{path}/session", 'wb' ) do |file| file.flock(File::LOCK_EX) file.write data.to_json file.flock(File::LOCK_UN) - } + end true end @@ -261,7 +261,7 @@ returns return end begin - File.open(session_file, 'rb') { |file| + File.open(session_file, 'rb') do |file| file.flock(File::LOCK_SH) all = file.read file.flock(File::LOCK_UN) @@ -270,7 +270,7 @@ returns data = symbolize_keys(data_json) data[:user] = data_json['user'] # for compat. reasons end - } + end rescue => e log('error', e.inspect) destroy(client_id) @@ -308,12 +308,12 @@ returns end return false if !File.directory? path begin - File.open(location, 'wb') { |file| + File.open(location, 'wb') do |file| file.flock(File::LOCK_EX) file.write data.to_json file.flock(File::LOCK_UN) file.close - } + end rescue => e log('error', e.inspect) log('error', "error in writing message file '#{location}'") @@ -338,14 +338,14 @@ returns # list all current clients client_list = sessions - client_list.each { |client_id| + client_list.each do |client_id| session = Sessions.get(client_id) next if !session next if !session[:user] next if !session[:user]['id'] next if session[:user]['id'].to_i != user_id.to_i Sessions.send(client_id, data) - } + end true end @@ -374,7 +374,7 @@ broadcase also not to sender # list all current clients recipients = [] client_list = sessions - client_list.each { |client_id| + client_list.each do |client_id| session = Sessions.get(client_id) next if !session @@ -388,7 +388,7 @@ broadcase also not to sender end Sessions.send(client_id, data) recipients.push client_id - } + end recipients end @@ -417,29 +417,29 @@ returns path = "#{@path}/#{client_id}/" data = [] files = [] - Dir.foreach(path) { |entry| + Dir.foreach(path) do |entry| next if entry == '.' next if entry == '..' files.push entry - } - files.sort.each { |entry| + end + files.sort.each do |entry| filename = "#{path}/#{entry}" next if entry !~ /^send/ message = Sessions.queue_file_read(path, entry) next if !message data.push message - } + end data end def self.queue_file_read(path, filename) location = "#{path}#{filename}" message = '' - File.open(location, 'rb') { |file| + File.open(location, 'rb') do |file| file.flock(File::LOCK_EX) message = file.read file.flock(File::LOCK_UN) - } + end File.delete(location) return if message.blank? begin @@ -473,11 +473,11 @@ remove all session and spool messages timestamp: Time.now.utc.to_i, } file_path = "#{path}/#{Time.now.utc.to_f}-#{rand(99_999)}" - File.open(file_path, 'wb') { |file| + File.open(file_path, 'wb') do |file| file.flock(File::LOCK_EX) file.write data.to_json file.flock(File::LOCK_UN) - } + end end def self.spool_list(timestamp, current_user_id) @@ -486,15 +486,15 @@ remove all session and spool messages data = [] to_delete = [] files = [] - Dir.foreach(path) { |entry| + Dir.foreach(path) do |entry| next if entry == '.' next if entry == '..' files.push entry - } - files.sort.each { |entry| + end + files.sort.each do |entry| filename = "#{path}/#{entry}" next if !File.exist?(filename) - File.open(filename, 'rb') { |file| + File.open(filename, 'rb') do |file| file.flock(File::LOCK_SH) message = file.read file.flock(File::LOCK_UN) @@ -522,7 +522,7 @@ remove all session and spool messages # spool to recipient list if message_parsed['recipient'] && message_parsed['recipient']['user_id'] - message_parsed['recipient']['user_id'].each { |user_id| + message_parsed['recipient']['user_id'].each do |user_id| next if current_user_id != user_id @@ -536,7 +536,7 @@ remove all session and spool messages message: message, } data.push item - } + end # spool to every client else @@ -551,11 +551,11 @@ remove all session and spool messages data.push item end end - } - } - to_delete.each { |file| + end + end + to_delete.each do |file| File.delete(file) - } + end data end @@ -569,7 +569,7 @@ remove all session and spool messages Thread.abort_on_exception = true loop do client_ids = sessions - client_ids.each { |client_id| + client_ids.each do |client_id| # connection already open, ignore next if @@client_threads[client_id] @@ -586,14 +586,14 @@ remove all session and spool messages next if @@client_threads[client_id] @@client_threads[client_id] = true - @@client_threads[client_id] = Thread.new { + @@client_threads[client_id] = Thread.new do thread_client(client_id) @@client_threads[client_id] = nil log('debug', "close client (#{client_id}) thread") ActiveRecord::Base.connection.close - } + end sleep 0.5 - } + end # system settings sleep 0.5 @@ -662,7 +662,7 @@ returns end def self.symbolize_keys(hash) - hash.each_with_object({}) { |(key, value), result| + hash.each_with_object({}) do |(key, value), result| new_key = case key when String then key.to_sym else key @@ -672,7 +672,7 @@ returns else value end result[new_key] = new_value - } + end end # we use it in rails and non rails context diff --git a/lib/sessions/backend/collections.rb b/lib/sessions/backend/collections.rb index ea8c22ff2..794fbe5c4 100644 --- a/lib/sessions/backend/collections.rb +++ b/lib/sessions/backend/collections.rb @@ -11,14 +11,14 @@ class Sessions::Backend::Collections < Sessions::Backend::Base def push results = [] - @backends.each { |backend| + @backends.each do |backend| #puts "B: #{backend.inspect}" result = backend.push #puts "R: #{result.inspect}" if result results.push result end - } + end results end @@ -30,7 +30,7 @@ class Sessions::Backend::Collections < Sessions::Backend::Base # load collections to deliver from external files dir = File.expand_path('../../../../', __FILE__) files = Dir.glob("#{dir}/lib/sessions/backend/collections/*.rb") - files.each { |file| + files.each do |file| file.gsub!("#{dir}/lib/", '') file.gsub!(/\.rb$/, '') next if file.classify == 'Sessions::Backend::Collections::Base' @@ -40,7 +40,7 @@ class Sessions::Backend::Collections < Sessions::Backend::Base if backend backends.push backend end - } + end backends end diff --git a/lib/sessions/backend/collections/base.rb b/lib/sessions/backend/collections/base.rb index 32cf96ba3..33588df94 100644 --- a/lib/sessions/backend/collections/base.rb +++ b/lib/sessions/backend/collections/base.rb @@ -46,16 +46,16 @@ class Sessions::Backend::Collections::Base < Sessions::Backend::Base # get relations of data all = [] - items.each { |item| + items.each do |item| all.push item.attributes_with_association_ids - } + end # collect assets assets = {} - items.each { |item| + items.each do |item| next if !asset_needed?(item) assets = item.assets(assets) - } + end if !@client return { collection: { diff --git a/lib/sessions/backend/ticket_overview_list.rb b/lib/sessions/backend/ticket_overview_list.rb index 220936de0..6f0d8cafb 100644 --- a/lib/sessions/backend/ticket_overview_list.rb +++ b/lib/sessions/backend/ticket_overview_list.rb @@ -68,7 +68,7 @@ class Sessions::Backend::TicketOverviewList < Sessions::Backend::Base # push overview index indexes = [] - index_and_lists.each { |index| + index_and_lists.each do |index| assets = {} overview = Overview.lookup(id: index[:overview][:id]) meta = { @@ -78,7 +78,7 @@ class Sessions::Backend::TicketOverviewList < Sessions::Backend::Base count: index[:count], } indexes.push meta - } + end if @client @client.log "push overview_index for user #{@user.id}" @client.send( @@ -89,7 +89,7 @@ class Sessions::Backend::TicketOverviewList < Sessions::Backend::Base # push overviews results = [] - index_and_lists.each { |data| + index_and_lists.each do |data| # do not deliver unchanged lists next if @last_overview[data[:overview][:id]] == data @@ -100,11 +100,11 @@ class Sessions::Backend::TicketOverviewList < Sessions::Backend::Base if asset_needed?(overview) assets = overview.assets(assets) end - data[:tickets].each { |ticket_meta| + data[:tickets].each do |ticket_meta| ticket = Ticket.lookup(id: ticket_meta[:id]) next if !asset_needed?(ticket) assets = ticket.assets(assets) - } + end data[:assets] = assets if !@client @@ -123,7 +123,7 @@ class Sessions::Backend::TicketOverviewList < Sessions::Backend::Base data: data, ) end - } + end return results if !@client nil end diff --git a/lib/sessions/client.rb b/lib/sessions/client.rb index ca012d931..264b4a49f 100644 --- a/lib/sessions/client.rb +++ b/lib/sessions/client.rb @@ -36,16 +36,16 @@ class Sessions::Client asset_lookup = {} # release old objects - backend_pool.collect! { + backend_pool.collect! do nil - } + end # create new pool backend_pool = [] - backends.each { |backend| + backends.each do |backend| item = backend.constantize.new(user, asset_lookup, self, @client_id) backend_pool.push item - } + end end loop_count += 1 diff --git a/lib/sessions/event/base.rb b/lib/sessions/event/base.rb index c985bc9ff..936b8e7a9 100644 --- a/lib/sessions/event/base.rb +++ b/lib/sessions/event/base.rb @@ -1,9 +1,9 @@ class Sessions::Event::Base def initialize(params) - params.each { |key, value| + params.each do |key, value| instance_variable_set "@#{key}", value - } + end @is_web_socket = false return if !@clients[@client_id] diff --git a/lib/sessions/event/broadcast.rb b/lib/sessions/event/broadcast.rb index 4cacafce1..9d1c6818a 100644 --- a/lib/sessions/event/broadcast.rb +++ b/lib/sessions/event/broadcast.rb @@ -4,7 +4,7 @@ class Sessions::Event::Broadcast < Sessions::Event::Base # list all current clients client_list = Sessions.list - client_list.each { |local_client_id, local_client| + client_list.each do |local_client_id, local_client| if local_client_id == @client_id log 'notice', 'do not send broadcast to it self' next @@ -19,13 +19,13 @@ class Sessions::Event::Broadcast < Sessions::Event::Base elsif @payload['recipient']['user_id'].class != Array log 'error', "recipient.user_id attribute isn't an array '#{@payload['recipient']['user_id'].inspect}'" else - @payload['recipient']['user_id'].each { |user_id| + @payload['recipient']['user_id'].each do |user_id| next if local_client[:user]['id'].to_i != user_id.to_i log 'notice', "send broadcast from (#{@client_id}) to (user_id=#{user_id})", local_client_id websocket_send(local_client_id, @payload['data']) - } + end end # broadcast every client @@ -33,7 +33,7 @@ class Sessions::Event::Broadcast < Sessions::Event::Base log 'notice', "send broadcast from (#{@client_id})", local_client_id websocket_send(local_client_id, @payload['data']) end - } + end false end diff --git a/lib/sessions/event/chat_status_agent.rb b/lib/sessions/event/chat_status_agent.rb index f78f47b83..9c91f53c2 100644 --- a/lib/sessions/event/chat_status_agent.rb +++ b/lib/sessions/event/chat_status_agent.rb @@ -11,9 +11,9 @@ class Sessions::Event::ChatStatusAgent < Sessions::Event::ChatBase Chat::Agent.state(@session['id'], state) # update recipients of existing sessions - Chat::Session.where(state: 'running', user_id: @session['id']).order('created_at ASC').each { |chat_session| + Chat::Session.where(state: 'running', user_id: @session['id']).order('created_at ASC').each do |chat_session| chat_session.add_recipient(@client_id, true) - } + end { event: 'chat_status_agent', data: Chat.agent_state_with_sessions(@session['id']), diff --git a/lib/sessions/event/spool.rb b/lib/sessions/event/spool.rb index f51a03ace..c47ea3f2e 100644 --- a/lib/sessions/event/spool.rb +++ b/lib/sessions/event/spool.rb @@ -16,7 +16,7 @@ class Sessions::Event::Spool < Sessions::Event::Base end spool = Sessions.spool_list(@payload['timestamp'], @session['id']) - spool.each { |item| + spool.each do |item| # create new msg to push to client if item[:type] == 'direct' @@ -25,7 +25,7 @@ class Sessions::Event::Spool < Sessions::Event::Base log 'notice', 'send spool' end websocket_send(@client_id, item[:message]) - } + end # send spool:sent event to client log 'notice', 'send spool:sent event' diff --git a/lib/signature_detection.rb b/lib/signature_detection.rb index 28942adf8..03ed608b1 100644 --- a/lib/signature_detection.rb +++ b/lib/signature_detection.rb @@ -22,23 +22,23 @@ returns def self.find_signature(messages) string_list = [] - messages.each { |message| + messages.each do |message| if message[:content_type] =~ %r{text/html}i string_list.push message[:content].html2text(true) next end string_list.push message[:content] - } + end # hash with possible signature and count of matches in string list possible_signatures = {} # loop all strings in array - string_list.each_with_index { |_main_string, main_string_index| + string_list.each_with_index do |_main_string, main_string_index| break if main_string_index + 1 > string_list.length - 1 # loop all all strings in array except of the previous index - ( main_string_index + 1..string_list.length - 1 ).each { |second_string_index| + ( main_string_index + 1..string_list.length - 1 ).each do |second_string_index| # get content of string 1 string1_content = string_list[main_string_index] @@ -56,7 +56,7 @@ returns match_block = nil # loop of lines of the diff result - ( 0..diff_result_array.length - 1 ).each { |diff_string_index| + ( 0..diff_result_array.length - 1 ).each do |diff_string_index| # if no block with difference is defined then we try to find a string block without a difference if !match_block @@ -83,11 +83,11 @@ returns # get string of possible signature, use only the first 10 lines match_max_content = 0 match_content = '' - ( match_block..match_block_total ).each { |match_block_index| + ( match_block..match_block_total ).each do |match_block_index| break if match_max_content == 10 match_max_content += 1 match_content += "#{diff_result_array[match_block_index][1..-1]}\n" - } + end # count the match of the signature in string list to rank # the signature @@ -98,9 +98,9 @@ returns end match_block = nil - } - } - } + end + end + end # loop all possible signature by rating and return highest rating possible_signatures.sort { |a1, a2| a2[1].to_i <=> a1[1].to_i }.map do |content, _score| @@ -187,7 +187,7 @@ returns create_article_sender_id: sender.id ).limit(5).order(id: :desc) article_bodies = [] - tickets.each { |ticket| + tickets.each do |ticket| article = ticket.articles.first next if !article data = { @@ -195,7 +195,7 @@ returns content_type: article.content_type, } article_bodies.push data - } + end find_signature(article_bodies) end @@ -213,9 +213,9 @@ returns =end def self.rebuild_all_user - User.select('id').where(active: true).order(id: :desc).each { |local_user| + User.select('id').where(active: true).order(id: :desc).each do |local_user| rebuild_user(local_user.id) - } + end true end @@ -259,7 +259,7 @@ returns def self.rebuild_all_articles article_type = Ticket::Article::Type.lookup(name: 'email') - Ticket::Article.select('id').where(type_id: article_type.id).order(id: :desc).each { |local_article| + Ticket::Article.select('id').where(type_id: article_type.id).order(id: :desc).each do |local_article| article = Ticket::Article.find(local_article.id) user = User.find(article.created_by_id) next if !user.preferences[:signature_detection] @@ -274,7 +274,7 @@ returns article.preferences[:signature_detection] = signature_line article.save - } + end true end diff --git a/lib/sso.rb b/lib/sso.rb index 7f960e409..9f653f36c 100644 --- a/lib/sso.rb +++ b/lib/sso.rb @@ -25,15 +25,15 @@ returns ] # added configured backends - Setting.where( area: 'Security::SSO' ).each { |setting| + Setting.where( area: 'Security::SSO' ).each do |setting| if setting.state_current[:value] config.push setting.state_current[:value] end - } + end # try to login against configure auth backends user_auth = nil - config.each { |config_item| + config.each do |config_item| next if !config_item[:adapter] # load backend @@ -51,7 +51,7 @@ returns user_auth.update_last_login return user_auth - } + end nil end end diff --git a/lib/stats.rb b/lib/stats.rb index 7d7eb7e0d..ef0e9cd74 100644 --- a/lib/stats.rb +++ b/lib/stats.rb @@ -31,47 +31,47 @@ returns users = User.with_permissions('ticket.agent') agent_count = 0 user_result = {} - users.each { |user| + users.each do |user| next if user.id == 1 next if !user.active agent_count += 1 data = {} - backends.each { |backend| + backends.each do |backend| data[backend] = backend.generate(user) - } + end user_result[user.id] = data - } + end # calculate average backend_average_sum = {} - user_result.each { |_user_id, data| - data.each { |backend_model, backend_result| + user_result.each do |_user_id, data| + data.each do |backend_model, backend_result| next if !backend_result.key?(:used_for_average) if !backend_average_sum[backend_model] backend_average_sum[backend_model] = 0 end backend_average_sum[backend_model] += backend_result[:used_for_average] - } - } + end + end # generate average param and icon state - backend_average_sum.each { |backend_model_average, result| + backend_average_sum.each do |backend_model_average, result| average = ( result.to_f / agent_count.to_f ).round(1) - user_result.each { |user_id, data| + user_result.each do |user_id, data| next if !data[backend_model_average] next if !data[backend_model_average].key?(:used_for_average) data[backend_model_average][:average_per_agent] = average # generate icon state backend_model_average.to_s.constantize.average_state(data[backend_model_average], user_id) - } - } + end + end - user_result.each { |user_id, data| + user_result.each do |user_id, data| data_for_user = {} - data.each { |backend, result| + data.each do |backend, result| data_for_user[backend.to_app_model] = result - } + end state_store = StatsStore.sync( object: 'User', o_id: user_id, @@ -90,7 +90,7 @@ returns event: 'dashboard_stats_rebuild', } Sessions.send_to(user_id, event) - } + end true end diff --git a/lib/stats/ticket_channel_distribution.rb b/lib/stats/ticket_channel_distribution.rb index 06da940b7..34e06d788 100644 --- a/lib/stats/ticket_channel_distribution.rb +++ b/lib/stats/ticket_channel_distribution.rb @@ -34,15 +34,15 @@ class Stats::TicketChannelDistribution result = {} total_in = 0 total_out = 0 - channels.each { |channel| + channels.each do |channel| result[channel[:sender].to_sym] = { icon: channel[:icon] } type_ids = [] - Ticket::Article::Type.all.each { |type| + Ticket::Article::Type.all.each do |type| next if type.name !~ /^#{channel[:sender]}/i type_ids.push type.id - } + end sender = Ticket::Article::Sender.lookup( name: 'Customer' ) count = Ticket.where(group_id: group_ids).joins(:articles).where( @@ -61,10 +61,10 @@ class Stats::TicketChannelDistribution ).count result[channel[:sender].to_sym][:outbound] = count total_out += count - } + end # append in percent - channels.each { |channel| + channels.each do |channel| count = result[channel[:sender].to_sym][:inbound] #puts "#{channel.inspect}:in/#{result.inspect}:#{count}" in_process_precent = if count.zero? @@ -81,7 +81,7 @@ class Stats::TicketChannelDistribution (count * 1000) / ((total_out * 1000) / 100) end result[channel[:sender].to_sym][:outbound_in_percent] = out_process_precent - } + end { channels: result } end diff --git a/lib/stats/ticket_response_time.rb b/lib/stats/ticket_response_time.rb index 8a1ac73f8..4323679f9 100644 --- a/lib/stats/ticket_response_time.rb +++ b/lib/stats/ticket_response_time.rb @@ -27,14 +27,14 @@ class Stats::TicketResponseTime total = 0 count_own = 0 own = 0 - items.each { |_item| + items.each do |_item| ticket = Ticket.lookup(id: data[:ticket_id]) if ticket.owner_id == user.id count_own += 1 own += data[:time] end total += data[:time] - } + end if total.nonzero? own = (own / count_own).round end diff --git a/lib/stats/ticket_waiting_time.rb b/lib/stats/ticket_waiting_time.rb index 7a474dcb8..026bbb151 100644 --- a/lib/stats/ticket_waiting_time.rb +++ b/lib/stats/ticket_waiting_time.rb @@ -55,9 +55,9 @@ class Stats::TicketWaitingTime average_time = 0 count_articles = 0 - tickets.each { |ticket| + tickets.each do |ticket| count_time = 0 - ticket.articles.joins(:type).where('ticket_articles.created_at > ? AND ticket_articles.internal = ? AND ticket_article_types.communication = ?', start_time, false, true).each { |article| + ticket.articles.joins(:type).where('ticket_articles.created_at > ? AND ticket_articles.internal = ? AND ticket_article_types.communication = ?', start_time, false, true).each do |article| if article.sender.name == 'Customer' count_time = article.created_at.to_i elsif count_time.positive? @@ -65,8 +65,8 @@ class Stats::TicketWaitingTime count_articles += 1 count_time = 0 end - } - } + end + end if count_articles.positive? average_time = average_time / count_articles diff --git a/lib/telegram.rb b/lib/telegram.rb index 1ecddcb1f..729dee516 100644 --- a/lib/telegram.rb +++ b/lib/telegram.rb @@ -127,14 +127,14 @@ returns =end def self.bot_duplicate?(bot_id, channel_id = nil) - Channel.where(area: 'Telegram::Bot').each { |channel| + Channel.where(area: 'Telegram::Bot').each do |channel| next if !channel.options next if !channel.options[:bot] next if !channel.options[:bot][:id] next if channel.options[:bot][:id] != bot_id next if channel.id.to_s == channel_id.to_s return true - } + end false end @@ -151,12 +151,12 @@ returns =end def self.bot_by_bot_id(bot_id) - Channel.where(area: 'Telegram::Bot').each { |channel| + Channel.where(area: 'Telegram::Bot').each do |channel| next if !channel.options next if !channel.options[:bot] next if !channel.options[:bot][:id] return channel if channel.options[:bot][:id].to_s == bot_id.to_s - } + end nil end @@ -174,19 +174,19 @@ returns def self.message_id(params) message_id = nil - [:message, :edited_message].each { |key| + [:message, :edited_message].each do |key| next if !params[key] next if !params[key][:message_id] message_id = params[key][:message_id] break - } + end if message_id - [:message, :edited_message].each { |key| + [:message, :edited_message].each do |key| next if !params[key] next if !params[key][:chat] next if !params[key][:chat][:id] message_id = "#{message_id}.#{params[key][:chat][:id]}" - } + end end if !message_id message_id = params[:update_id] @@ -279,14 +279,14 @@ returns # prepare title title = '-' - [:text, :caption].each { |area| + [:text, :caption].each do |area| next if !params[:message] next if !params[:message][area] title = params[:message][area] break - } + end if title == '-' - [:sticker, :photo, :document, :voice].each { |area| + [:sticker, :photo, :document, :voice].each do |area| begin next if !params[:message] next if !params[:message][area] @@ -297,7 +297,7 @@ returns # just go ahead title end - } + end end if title.length > 60 title = "#{title[0, 60]}..." @@ -388,7 +388,7 @@ returns max_width = 650 * 2 last_width = 0 last_height = 0 - params[:message][:photo].each { |file| + params[:message][:photo].each do |file| if !photo photo = file last_width = file['width'].to_i @@ -398,7 +398,7 @@ returns photo = file last_width = file['width'].to_i last_height = file['height'].to_i - } + end if last_width > 650 last_width = (last_width / 2).to_i last_height = (last_height / 2).to_i diff --git a/lib/tweet_base.rb b/lib/tweet_base.rb index ccee60fb7..cc492641a 100644 --- a/lib/tweet_base.rb +++ b/lib/tweet_base.rb @@ -46,12 +46,12 @@ class TweetBase } # ignore if value is already set - map.each { |target, source| + map.each do |target, source| next if user[target] && !user[target].empty? new_value = tweet_user.send(source).to_s next if !new_value || new_value.empty? user_data[target] = new_value - } + end user.update!(user_data) else user_data[:login] = tweet_user.screen_name @@ -170,7 +170,7 @@ class TweetBase from = "@#{tweet.user.screen_name}" mention_ids = [] if tweet.user_mentions - tweet.user_mentions.each { |local_user| + tweet.user_mentions.each do |local_user| if !to to = '' else @@ -178,7 +178,7 @@ class TweetBase end to += "@#{local_user.screen_name}" mention_ids.push local_user.id - } + end end in_reply_to = tweet.in_reply_to_status_id @@ -370,9 +370,9 @@ class TweetBase def preferences_cleanup(preferences) # replace Twitter::NullObject with nill to prevent elasticsearch index issue - preferences.each { |_key, value| + preferences.each do |_key, value| next if !value.is_a?(Hash) - value.each { |sub_key, sub_level| + value.each do |sub_key, sub_level| if sub_level.class == NilClass value[sub_key] = nil next @@ -383,21 +383,21 @@ class TweetBase end next if sub_level.class != Twitter::NullObject value[sub_key] = nil - } - } + end + end preferences end def locale_sender?(tweet) tweet_user = user(tweet) - Channel.where(area: 'Twitter::Account').each { |local_channel| + Channel.where(area: 'Twitter::Account').each do |local_channel| next if !local_channel.options next if !local_channel.options[:user] next if !local_channel.options[:user][:id] next if local_channel.options[:user][:id].to_s != tweet_user.id.to_s Rails.logger.debug "Tweet is sent by local account with user id #{tweet_user.id} and tweet.id #{tweet.id}" return true - } + end false end diff --git a/lib/user_agent.rb b/lib/user_agent.rb index 620fb04c4..5f8eb98c5 100644 --- a/lib/user_agent.rb +++ b/lib/user_agent.rb @@ -332,9 +332,9 @@ returns content_encoding: request['Content-Encoding'], source: request['User-Agent'] || request['Server'], } - request.each_header { |key, value| + request.each_header do |key, value| request_data[:content] += "#{key}: #{value}\n" - } + end body = request.body if body request_data[:content] += "\n" + body @@ -354,9 +354,9 @@ returns response_data[:content_type] = response['Content-Type'] response_data[:content_encoding] = response['Content-Encoding'] response_data[:source] = response['User-Agent'] || response['Server'] - response.each_header { |key, value| + response.each_header do |key, value| response_data[:content] += "#{key}: #{value}\n" - } + end body = response.body if body response_data[:content] += "\n" + body diff --git a/script/websocket-server.rb b/script/websocket-server.rb index d7aee77ea..8882aacac 100755 --- a/script/websocket-server.rb +++ b/script/websocket-server.rb @@ -119,11 +119,11 @@ end @clients = {} Rails.configuration.interface = 'websocket' -EventMachine.run { +EventMachine.run do EventMachine::WebSocket.start( host: @options[:b], port: @options[:p], secure: @options[:s], tls_options: tls_options ) do |ws| # register client connection - ws.onopen { |handshake| + ws.onopen do |handshake| headers = handshake.headers remote_ip = get_remote_ip(headers) client_id = ws.object_id.to_s @@ -139,10 +139,10 @@ EventMachine.run { remote_ip: remote_ip, } end - } + end # unregister client connection - ws.onclose { + ws.onclose do client_id = ws.object_id.to_s log 'notice', 'Client disconnected.', client_id @@ -152,10 +152,10 @@ EventMachine.run { end Sessions.destroy(client_id) - } + end # manage messages - ws.onmessage { |msg| + ws.onmessage do |msg| client_id = ws.object_id.to_s log 'debug', "received: #{msg} ", client_id @@ -194,46 +194,46 @@ EventMachine.run { else log 'error', "unknown message '#{data.inspect}'", client_id end - } + end end # check unused connections - EventMachine.add_timer(0.5) { + EventMachine.add_timer(0.5) do check_unused_connections - } + end # check open unused connections, kick all connection without activitie in the last 2 minutes - EventMachine.add_periodic_timer(120) { + EventMachine.add_periodic_timer(120) do check_unused_connections - } + end - EventMachine.add_periodic_timer(20) { + EventMachine.add_periodic_timer(20) do # websocket log 'notice', "Status: websocket clients: #{@clients.size}" - @clients.each { |client_id, _client| + @clients.each do |client_id, _client| log 'notice', 'working...', client_id - } + end # ajax client_list = Sessions.list clients = 0 - client_list.each { |_client_id, client| + client_list.each do |_client_id, client| next if client[:meta][:type] == 'websocket' clients = clients + 1 - } + end log 'notice', "Status: ajax clients: #{clients}" - client_list.each { |client_id, client| + client_list.each do |client_id, client| next if client[:meta][:type] == 'websocket' log 'notice', 'working...', client_id - } + end - } + end - EventMachine.add_periodic_timer(0.4) { + EventMachine.add_periodic_timer(0.4) do next if @clients.size.zero? #log 'debug', 'checking for data to send...' - @clients.each { |client_id, client| + @clients.each do |client_id, client| next if client[:disconnect] log 'debug', 'checking for data...', client_id begin @@ -253,8 +253,8 @@ EventMachine.run { end end end - } - } + end + end def get_remote_ip(headers) return headers['X-Forwarded-For'] if headers && headers['X-Forwarded-For'] @@ -281,7 +281,7 @@ EventMachine.run { idle_time_in_sec = 4 * 60 # close unused web socket sessions - @clients.each { |client_id, client| + @clients.each do |client_id, client| next if ( client[:last_ping].to_i + idle_time_in_sec ) >= Time.now.utc.to_i @@ -296,13 +296,13 @@ EventMachine.run { # delete session from client list sleep 0.3 @clients.delete(client_id) - } + end # close unused ajax long polling sessions clients = Sessions.destroy_idle_sessions(idle_time_in_sec) - clients.each { |client_id| + clients.each do |client_id| log 'notice', 'closing idle long polling connection', client_id - } + end end def log(level, data, client_id = '-') @@ -313,4 +313,4 @@ EventMachine.run { #puts "#{Time.now.utc.iso8601}:#{ level }:client(#{ client_id }) #{ data }" end -} +end diff --git a/spec/lib/import/base_resource_spec.rb b/spec/lib/import/base_resource_spec.rb index 6bbe77404..d2392051c 100644 --- a/spec/lib/import/base_resource_spec.rb +++ b/spec/lib/import/base_resource_spec.rb @@ -3,9 +3,9 @@ require 'rails_helper' RSpec.describe Import::BaseResource do it "needs an implementation of the 'import_class' method" do - expect { + expect do described_class.new(attributes_for(:group)) - }.to raise_error(NoMethodError) + end.to raise_error(NoMethodError) end context "implemented 'import_class' method" do @@ -31,11 +31,11 @@ RSpec.describe Import::BaseResource do Import::Test.send(:remove_const, :Group) end - let(:attributes) { + let(:attributes) do attributes = attributes_for(:group) attributes[:id] = 1337 attributes - } + end context 'live run' do diff --git a/spec/lib/import/model_resource_spec.rb b/spec/lib/import/model_resource_spec.rb index 37c6aa0d1..58b6be07f 100644 --- a/spec/lib/import/model_resource_spec.rb +++ b/spec/lib/import/model_resource_spec.rb @@ -21,9 +21,9 @@ RSpec.describe Import::ModelResource do let(:group_data) { attributes_for(:group).merge(id: 1337) } it 'creates model Objects by class name' do - expect { + expect do Import::Test::Group.new(group_data) - }.to change { Group.count }.by(1) + end.to change { Group.count }.by(1) end it 'updates model Objects by class name' do diff --git a/spec/lib/import/otrs/article/attachment_factory_spec.rb b/spec/lib/import/otrs/article/attachment_factory_spec.rb index 413d0cac9..1350f9c65 100644 --- a/spec/lib/import/otrs/article/attachment_factory_spec.rb +++ b/spec/lib/import/otrs/article/attachment_factory_spec.rb @@ -9,19 +9,19 @@ RSpec.describe Import::OTRS::Article::AttachmentFactory do end let(:local_article) { instance_double(Ticket::Article, ticket_id: 1337, id: 42) } - let(:attachments) { + let(:attachments) do [ load_attachment_json('default'), load_attachment_json('default'), load_attachment_json('default') ] - } - let(:start_import) { + end + let(:start_import) do described_class.import( attachments: attachments, local_article: local_article ) - } + end def import_expectations expect(Store).to receive(:add).exactly(3).times.with(hash_including( diff --git a/spec/lib/import/otrs/article_spec.rb b/spec/lib/import/otrs/article_spec.rb index 9b300f92b..2ee26d638 100644 --- a/spec/lib/import/otrs/article_spec.rb +++ b/spec/lib/import/otrs/article_spec.rb @@ -27,7 +27,7 @@ RSpec.describe Import::OTRS::Article do context 'customer phone' do let(:object_structure) { load_article_json('customer_phone_attachment') } - let(:zammad_structure) { + let(:zammad_structure) do { created_by_id: '3', updated_by_id: 1, @@ -48,7 +48,7 @@ RSpec.describe Import::OTRS::Article do internal: false, sender_id: 2 } - } + end it 'creates' do expect(Import::OTRS::Article::AttachmentFactory).to receive(:import) @@ -64,7 +64,7 @@ RSpec.describe Import::OTRS::Article do context 'content type with comma' do let(:object_structure) { load_article_json('content_type_comma') } - let(:zammad_structure) { + let(:zammad_structure) do { created_by_id: '3', updated_by_id: 1, @@ -85,7 +85,7 @@ RSpec.describe Import::OTRS::Article do internal: false, sender_id: 2 } - } + end it 'creates' do expect(Import::OTRS::Article::AttachmentFactory).to receive(:import) @@ -101,7 +101,7 @@ RSpec.describe Import::OTRS::Article do context 'no content type' do let(:object_structure) { load_article_json('no_content_type') } - let(:zammad_structure) { + let(:zammad_structure) do { created_by_id: '1', updated_by_id: 1, @@ -121,7 +121,7 @@ RSpec.describe Import::OTRS::Article do internal: false, sender_id: 2 } - } + end it 'creates' do creates_with(zammad_structure) @@ -135,7 +135,7 @@ RSpec.describe Import::OTRS::Article do context 'no article body' do let(:object_structure) { load_article_json('customer_phone_no_body') } - let(:zammad_structure) { + let(:zammad_structure) do { created_by_id: '3', updated_by_id: 1, @@ -156,7 +156,7 @@ RSpec.describe Import::OTRS::Article do internal: false, sender_id: 2 } - } + end it 'creates' do creates_with(zammad_structure) diff --git a/spec/lib/import/otrs/customer_spec.rb b/spec/lib/import/otrs/customer_spec.rb index a39e66d03..e1709b13e 100644 --- a/spec/lib/import/otrs/customer_spec.rb +++ b/spec/lib/import/otrs/customer_spec.rb @@ -26,7 +26,7 @@ RSpec.describe Import::OTRS::Customer do context 'Organization' do let(:object_structure) { load_customer_json('default') } - let(:zammad_structure) { + let(:zammad_structure) do { created_by_id: '1', updated_by_id: '1', @@ -35,7 +35,8 @@ RSpec.describe Import::OTRS::Customer do created_at: '2014-06-06 12:41:03', name: 'test922896', note: 'test922896' - }} + } + end it 'creates' do creates_with(zammad_structure) @@ -50,11 +51,11 @@ RSpec.describe Import::OTRS::Customer do let(:customer_id) { 'test922896' } let(:object_structure) { load_customer_json('default') } - let(:otrs_dummy_response) { + let(:otrs_dummy_response) do [ object_structure ] - } + end it 'responds to by_customer_id' do expect(described_class).to respond_to('by_customer_id') diff --git a/spec/lib/import/otrs/customer_user_spec.rb b/spec/lib/import/otrs/customer_user_spec.rb index c3a24c0a9..51374dd4b 100644 --- a/spec/lib/import/otrs/customer_user_spec.rb +++ b/spec/lib/import/otrs/customer_user_spec.rb @@ -40,7 +40,7 @@ RSpec.describe Import::OTRS::CustomerUser do context 'regular user' do let(:object_structure) { load_customer_json('default') } - let(:zammad_structure) { + let(:zammad_structure) do { created_by_id: '1', updated_by_id: '1', @@ -63,7 +63,8 @@ RSpec.describe Import::OTRS::CustomerUser do zip: nil, city: nil, country: nil - }} + } + end it 'creates' do creates_with(zammad_structure) @@ -77,7 +78,7 @@ RSpec.describe Import::OTRS::CustomerUser do context 'no timestamps' do let(:object_structure) { load_customer_json('no_timestamps') } - let(:zammad_structure) { + let(:zammad_structure) do { created_by_id: '1', updated_by_id: '1', @@ -100,7 +101,8 @@ RSpec.describe Import::OTRS::CustomerUser do zip: nil, city: nil, country: nil - }} + } + end before(:each) do travel_to DateTime.current @@ -122,7 +124,7 @@ RSpec.describe Import::OTRS::CustomerUser do context 'regular user' do let(:object_structure) { load_customer_json('capital_email') } - let(:zammad_structure) { + let(:zammad_structure) do { created_by_id: '1', updated_by_id: '1', @@ -145,7 +147,8 @@ RSpec.describe Import::OTRS::CustomerUser do zip: nil, city: nil, country: nil - }} + } + end it 'creates' do creates_with(zammad_structure) diff --git a/spec/lib/import/otrs/dynamic_field_spec.rb b/spec/lib/import/otrs/dynamic_field_spec.rb index e676350d2..b61145df2 100644 --- a/spec/lib/import/otrs/dynamic_field_spec.rb +++ b/spec/lib/import/otrs/dynamic_field_spec.rb @@ -9,8 +9,8 @@ RSpec.describe Import::OTRS::DynamicField do it 'requires an implementation of init_callback' do expect(ObjectManager::Attribute).to receive(:get).and_return(false) - expect { + expect do start_import_test - }.to raise_error(RuntimeError) + end.to raise_error(RuntimeError) end end diff --git a/spec/lib/import/otrs/history_spec.rb b/spec/lib/import/otrs/history_spec.rb index ee223c8a1..6bbcbfa58 100644 --- a/spec/lib/import/otrs/history_spec.rb +++ b/spec/lib/import/otrs/history_spec.rb @@ -7,8 +7,8 @@ RSpec.describe Import::OTRS::History do let(:object_structure) { load_history_json('article/default') } it 'requires an implementation of init_callback' do - expect { + expect do start_import_test - }.to raise_error(RuntimeError) + end.to raise_error(RuntimeError) end end diff --git a/spec/lib/import/otrs/priority_spec.rb b/spec/lib/import/otrs/priority_spec.rb index a17a75de4..e4b1361ec 100644 --- a/spec/lib/import/otrs/priority_spec.rb +++ b/spec/lib/import/otrs/priority_spec.rb @@ -27,7 +27,7 @@ RSpec.describe Import::OTRS::Priority do context 'default' do let(:object_structure) { load_priority_json('default') } - let(:zammad_structure) { + let(:zammad_structure) do { created_by_id: '1', updated_by_id: '1', @@ -37,7 +37,7 @@ RSpec.describe Import::OTRS::Priority do name: '4 high', id: '4' } - } + end it 'creates' do creates_with(zammad_structure) diff --git a/spec/lib/import/otrs/queue_spec.rb b/spec/lib/import/otrs/queue_spec.rb index 7b25179d9..e7f20f54b 100644 --- a/spec/lib/import/otrs/queue_spec.rb +++ b/spec/lib/import/otrs/queue_spec.rb @@ -27,7 +27,7 @@ RSpec.describe Import::OTRS::Queue do context 'default' do let(:object_structure) { load_queue_json('default') } - let(:zammad_structure) { + let(:zammad_structure) do { created_by_id: 1, updated_by_id: 1, @@ -38,7 +38,7 @@ RSpec.describe Import::OTRS::Queue do id: '11', note: 'Some comment' } - } + end it 'creates' do creates_with(zammad_structure) diff --git a/spec/lib/import/otrs/requester_spec.rb b/spec/lib/import/otrs/requester_spec.rb index 630a58a43..7b7419fee 100644 --- a/spec/lib/import/otrs/requester_spec.rb +++ b/spec/lib/import/otrs/requester_spec.rb @@ -16,14 +16,14 @@ RSpec.describe Import::OTRS::Requester do context 'caching request results' do - let(:response) { + let(:response) do response = double() response_body = double() expect(response_body).to receive(:to_s).at_least(:once).and_return('{"Result": {}}') expect(response).to receive('success?').at_least(:once).and_return(true) expect(response).to receive('body').at_least(:once).and_return(response_body) response - } + end it 'is active if no args are given' do expect(UserAgent).to receive(:post).and_return(response) diff --git a/spec/lib/import/otrs/state_factory_spec.rb b/spec/lib/import/otrs/state_factory_spec.rb index 734025fec..1b50b8181 100644 --- a/spec/lib/import/otrs/state_factory_spec.rb +++ b/spec/lib/import/otrs/state_factory_spec.rb @@ -31,13 +31,13 @@ RSpec.describe Import::OTRS::StateFactory do name: 'pending_time', ) - expect { + expect do described_class.import(state_backend_param) # sync changes ticket_state_id.reload ticket_pending_time.reload - }.to change { + end.to change { ticket_state_id.data_option }.and change { ticket_state_id.screens @@ -59,13 +59,13 @@ RSpec.describe Import::OTRS::StateFactory do expect(Import::OTRS).to receive(:diff?).and_return(true) - expect { + expect do described_class.update_attribute_settings # sync changes ticket_state_id.reload ticket_pending_time.reload - }.to not_change { + end.to not_change { ticket_state_id.data_option }.and not_change { ticket_state_id.screens @@ -109,7 +109,7 @@ RSpec.describe Import::OTRS::StateFactory do context 'changing Ticket::State IDs' do - let(:state_backend_param) { + let(:state_backend_param) do states = %w(new open merged pending_reminder pending_auto_close_p pending_auto_close_n pending_auto_close_p closed_successful closed_unsuccessful closed_successful removed) state_backend_param = [] @@ -117,7 +117,7 @@ RSpec.describe Import::OTRS::StateFactory do state_backend_param.push(load_state_json(state)) end state_backend_param - } + end it 'updates Overviews' do name = 'My pending reached Tickets' diff --git a/spec/lib/import/otrs/state_spec.rb b/spec/lib/import/otrs/state_spec.rb index 4347cfd99..f5c1a35bd 100644 --- a/spec/lib/import/otrs/state_spec.rb +++ b/spec/lib/import/otrs/state_spec.rb @@ -28,7 +28,7 @@ RSpec.describe Import::OTRS::State do context 'closed' do let(:object_structure) { load_state_json('default') } - let(:zammad_structure) { + let(:zammad_structure) do { created_by_id: 1, updated_by_id: 1, @@ -40,7 +40,7 @@ RSpec.describe Import::OTRS::State do id: '2', note: 'Ticket is closed successful.' } - } + end it 'creates' do creates_with(zammad_structure) diff --git a/spec/lib/import/otrs/ticket_spec.rb b/spec/lib/import/otrs/ticket_spec.rb index 504f856ab..3a42795b9 100644 --- a/spec/lib/import/otrs/ticket_spec.rb +++ b/spec/lib/import/otrs/ticket_spec.rb @@ -37,7 +37,7 @@ RSpec.describe Import::OTRS::Ticket do context 'default' do let(:object_structure) { load_ticket_json('default') } - let(:zammad_structure) { + let(:zammad_structure) do { title: 'test #3', owner_id: 1, @@ -53,7 +53,7 @@ RSpec.describe Import::OTRS::Ticket do id: '730', close_at: '2014-11-21 00:21:08' } - } + end it 'creates' do import_backend_expectations @@ -69,7 +69,7 @@ RSpec.describe Import::OTRS::Ticket do context 'no title' do let(:object_structure) { load_ticket_json('no_title') } - let(:zammad_structure) { + let(:zammad_structure) do { title: '**EMPTY**', owner_id: 1, @@ -85,7 +85,7 @@ RSpec.describe Import::OTRS::Ticket do id: '730', close_at: '2014-11-21 00:21:08' } - } + end it 'creates' do import_backend_expectations @@ -101,7 +101,7 @@ RSpec.describe Import::OTRS::Ticket do context 'unknown customer' do let(:object_structure) { load_ticket_json('unknown_customer') } - let(:zammad_structure) { + let(:zammad_structure) do { owner_id: 1, customer_id: 1337, @@ -116,7 +116,7 @@ RSpec.describe Import::OTRS::Ticket do title: 'Ask me about performance', id: '540' } - } + end def article_based_customer_expectation user = instance_double(::User) diff --git a/spec/lib/import/otrs/user_spec.rb b/spec/lib/import/otrs/user_spec.rb index fc7deb35c..92423aef6 100644 --- a/spec/lib/import/otrs/user_spec.rb +++ b/spec/lib/import/otrs/user_spec.rb @@ -72,7 +72,7 @@ RSpec.describe Import::OTRS::User do context 'default' do let(:object_structure) { load_user_json('default') } - let(:zammad_structure) { + let(:zammad_structure) do { created_by_id: 1, updated_by_id: 1, @@ -89,7 +89,7 @@ RSpec.describe Import::OTRS::User do lastname: 'OTRS', login: 'root@localhost' } - } + end it 'creates' do prepare_expectations @@ -105,7 +105,7 @@ RSpec.describe Import::OTRS::User do context 'no groups' do let(:object_structure) { load_user_json('no_groups') } - let(:zammad_structure) { + let(:zammad_structure) do { created_by_id: 1, updated_by_id: 1, @@ -122,7 +122,7 @@ RSpec.describe Import::OTRS::User do lastname: 'agent-2-for-role-2', login: 'agent-2-for-role-2' } - } + end it 'creates' do prepare_expectations @@ -138,7 +138,7 @@ RSpec.describe Import::OTRS::User do context 'capital email' do let(:object_structure) { load_user_json('capital_email') } - let(:zammad_structure) { + let(:zammad_structure) do { created_by_id: 1, updated_by_id: 1, @@ -155,7 +155,7 @@ RSpec.describe Import::OTRS::User do lastname: 'OTRS', login: 'root@localhost' } - } + end it 'creates' do prepare_expectations diff --git a/spec/lib/import/statistical_factory_spec.rb b/spec/lib/import/statistical_factory_spec.rb index 728c28527..da72a7a51 100644 --- a/spec/lib/import/statistical_factory_spec.rb +++ b/spec/lib/import/statistical_factory_spec.rb @@ -30,11 +30,11 @@ RSpec.describe Import::StatisticalFactory do Import::Test::GroupFactory.reset_statistics end - let(:attributes) { + let(:attributes) do attributes = attributes_for(:group) attributes[:id] = 1337 attributes - } + end context 'statistics' do diff --git a/spec/lib/ldap/group_spec.rb b/spec/lib/ldap/group_spec.rb index 906439ec0..fc8e9f3f3 100644 --- a/spec/lib/ldap/group_spec.rb +++ b/spec/lib/ldap/group_spec.rb @@ -61,16 +61,16 @@ RSpec.describe Ldap::Group do context 'instance methods' do - let(:initialization_config) { + let(:initialization_config) do { uid_attribute: 'dn', filter: '(objectClass=group)', } - } + end - let(:instance) { + let(:instance) do described_class.new(initialization_config, ldap: mocked_ldap) - } + end context '#list' do @@ -87,11 +87,11 @@ RSpec.describe Ldap::Group do context '#filter' do - let(:initialization_config) { + let(:initialization_config) do { uid_attribute: 'dn', } - } + end it 'responds to #filter' do expect(instance).to respond_to(:filter) diff --git a/spec/lib/ldap/user_spec.rb b/spec/lib/ldap/user_spec.rb index 913146b31..3f06e9b21 100644 --- a/spec/lib/ldap/user_spec.rb +++ b/spec/lib/ldap/user_spec.rb @@ -72,16 +72,16 @@ RSpec.describe Ldap::User do context 'instance methods' do - let(:initialization_config) { + let(:initialization_config) do { uid_attribute: 'samaccountname', filter: '(objectClass=user)', } - } + end - let(:instance) { + let(:instance) do described_class.new(initialization_config, ldap: mocked_ldap) - } + end context '#valid?' do @@ -145,11 +145,11 @@ RSpec.describe Ldap::User do context '#filter' do - let(:initialization_config) { + let(:initialization_config) do { uid_attribute: 'samaccountname', } - } + end it 'responds to #filter' do expect(instance).to respond_to(:filter) @@ -168,11 +168,11 @@ RSpec.describe Ldap::User do context '#uid_attribute' do - let(:initialization_config) { + let(:initialization_config) do { filter: '(objectClass=user)', } - } + end it 'responds to #uid_attribute' do expect(instance).to respond_to(:uid_attribute) diff --git a/spec/lib/sequencer/unit/common/attribute_mapper_spec.rb b/spec/lib/sequencer/unit/common/attribute_mapper_spec.rb index 991180335..ad608a476 100644 --- a/spec/lib/sequencer/unit/common/attribute_mapper_spec.rb +++ b/spec/lib/sequencer/unit/common/attribute_mapper_spec.rb @@ -2,12 +2,12 @@ require 'rails_helper' RSpec.describe Sequencer::Unit::Common::AttributeMapper, sequencer: :unit do - let(:map) { + let(:map) do { old_key: :new_key, second: :new_second, } - } + end it 'expects an implementation of the .map method' do expect do diff --git a/spec/models/concerns/has_groups_examples.rb b/spec/models/concerns/has_groups_examples.rb index 96b93af21..331bca593 100644 --- a/spec/models/concerns/has_groups_examples.rb +++ b/spec/models/concerns/has_groups_examples.rb @@ -3,10 +3,10 @@ RSpec.shared_examples 'HasGroups' do context 'group' do - let(:group_access_instance_inactive) { + let(:group_access_instance_inactive) do group_access_instance.update!(active: false) group_access_instance - } + end let(:group_full) { create(:group) } let(:group_read) { create(:group) } let(:group_inactive) { create(:group, active: false) } diff --git a/spec/models/concerns/has_roles_examples.rb b/spec/models/concerns/has_roles_examples.rb index a17f2b73d..cc86565e4 100644 --- a/spec/models/concerns/has_roles_examples.rb +++ b/spec/models/concerns/has_roles_examples.rb @@ -4,10 +4,10 @@ RSpec.shared_examples 'HasRoles' do context 'role' do - let(:group_access_instance_inactive) { + let(:group_access_instance_inactive) do group_access_instance.update!(active: false) group_access_instance - } + end let(:role) { create(:role) } let(:group_instance) { create(:group) } let(:group_role) { create(:group) } diff --git a/spec/models/ticket_spec.rb b/spec/models/ticket_spec.rb index 0dee7dee3..0b8767ba6 100644 --- a/spec/models/ticket_spec.rb +++ b/spec/models/ticket_spec.rb @@ -42,23 +42,23 @@ RSpec.describe Ticket do ) expect(result).to be(true) - expect { + expect do result = target_ticket.merge_to( ticket_id: source_ticket.id, user_id: 1, ) - }.to raise_error('ticket already merged, no merge into merged ticket possible') + end.to raise_error('ticket already merged, no merge into merged ticket possible') end it 'prevents merging ticket in it self' do source_ticket = create(:ticket) - expect { + expect do result = source_ticket.merge_to( ticket_id: source_ticket.id, user_id: 1, ) - }.to raise_error('Can\'t merge ticket with it self!') + end.to raise_error('Can\'t merge ticket with it self!') end end diff --git a/spec/models/translation_spec.rb b/spec/models/translation_spec.rb index 59ff290cb..1c78441eb 100644 --- a/spec/models/translation_spec.rb +++ b/spec/models/translation_spec.rb @@ -38,12 +38,12 @@ RSpec.describe Translation do # check for non existing custom changes list = Translation.lang(locale) - list['list'].each { |item| + list['list'].each do |item| translation = Translation.find_by(source: item[1], locale: locale) expect(translation.class).to be(Translation) expect(locale).to eq(translation.locale) expect(translation.target).to eq(translation.target_initial) - } + end # add custom changes translation = Translation.find_by(locale: locale, source: 'open') @@ -54,7 +54,7 @@ RSpec.describe Translation do translation.save! list = Translation.lang(locale) - list['list'].each { |item| + list['list'].each do |item| translation = Translation.find_by(source: item[1], locale: locale) expect(translation.class).to be(Translation) expect(locale).to eq(translation.locale) @@ -64,12 +64,12 @@ RSpec.describe Translation do else expect(translation.target).to eq(translation.target_initial) end - } + end # check for existing custom changes after new translations are loaded Translation.load(locale) list = Translation.lang(locale) - list['list'].each { |item| + list['list'].each do |item| translation = Translation.find_by(source: item[1], locale: locale) expect(translation.class).to be(Translation) expect(locale).to eq(translation.locale) @@ -79,17 +79,17 @@ RSpec.describe Translation do else expect(translation.target).to eq(translation.target_initial) end - } + end # reset custom translations and check for non existing custom changes Translation.reset(locale) list = Translation.lang(locale) - list['list'].each { |item| + list['list'].each do |item| translation = Translation.find_by(source: item[1], locale: locale) expect(translation.class).to be(Translation) expect(locale).to eq(translation.locale) expect(translation.target).to eq(translation.target_initial) - } + end end end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index e2a8bf18f..6e814ec6a 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -19,10 +19,10 @@ RSpec.describe User do it 'resets login_failed on password change' do user = create(:user_login_failed) - expect { + expect do user.password = new_password user.save - }.to change { user.login_failed }.to(0) + end.to change { user.login_failed }.to(0) end end @@ -161,10 +161,10 @@ RSpec.describe User do token = create(:token_password_reset) user = User.find(token.user_id) - expect { + expect do described_class.password_reset_via_token(token.name, new_password) user.reload - }.to change { + end.to change { user.password }.and change { Token.count @@ -181,9 +181,9 @@ RSpec.describe User do allow(Setting).to receive(:get) user = build(:user, password: '{sha2}dd9c764fa7ea18cd992c8600006d3dc3ac983d1ba22e9ba2d71f6207456be0ba') # zammad - expect { + expect do user.save - }.to_not change { + end.to_not change { user.password } end diff --git a/test/browser/aaa_getting_started_test.rb b/test/browser/aaa_getting_started_test.rb index ecd7c32c6..ebe5588bc 100644 --- a/test/browser/aaa_getting_started_test.rb +++ b/test/browser/aaa_getting_started_test.rb @@ -200,7 +200,7 @@ class AaaGettingStartedTest < TestCase def test_b_accounts_auto #return # TODO: temp disable accounts = [] - (1..10).each { |count| + (1..10).each do |count| next if !ENV["MAILBOX_AUTO#{count}"] mailbox_user = ENV["MAILBOX_AUTO#{count}"].split(':')[0] mailbox_password = ENV["MAILBOX_AUTO#{count}"].split(':')[1] @@ -210,7 +210,7 @@ class AaaGettingStartedTest < TestCase password: mailbox_password, } accounts.push account - } + end if accounts.empty? #raise "Need min. MAILBOX_AUTO1 as ENV variable like export MAILBOX_AUTO1='nicole.braun2015@gmail.com:somepass'" puts "NOTICE: Need min. MAILBOX_AUTO1 as ENV variable like export MAILBOX_AUTO1='nicole.braun2015@gmail.com:somepass'" @@ -222,7 +222,7 @@ class AaaGettingStartedTest < TestCase password: 'test', url: browser_url, ) - accounts.each { |account| + accounts.each do |account| # getting started - auto mail location(url: browser_url + '/#getting_started/channel') @@ -257,13 +257,13 @@ class AaaGettingStartedTest < TestCase location_check( url: '#getting_started/agents', ) - } + end end def test_b_accounts_manual #return # TODO: temp disable accounts = [] - (1..10).each { |count| + (1..10).each do |count| next if !ENV["MAILBOX_MANUAL#{count}"] mailbox_user = ENV["MAILBOX_MANUAL#{count}"].split(':')[0] mailbox_password = ENV["MAILBOX_MANUAL#{count}"].split(':')[1] @@ -281,7 +281,7 @@ class AaaGettingStartedTest < TestCase }, } accounts.push account - } + end if accounts.empty? #raise "Need min. MAILBOX_MANUAL1 as ENV variable like export MAILBOX_MANUAL1='nicole.bauer2015@yahoo.de:somepass:imap.mail.yahoo.com:smtp.mail.yahoo.com'" puts "NOTICE: Need min. MAILBOX_MANUAL1 as ENV variable like export MAILBOX_MANUAL1='nicole.bauer2015@yahoo.de:somepass:imap.mail.yahoo.com:smtp.mail.yahoo.com'" @@ -294,7 +294,7 @@ class AaaGettingStartedTest < TestCase password: 'test', url: browser_url, ) - accounts.each { |account| + accounts.each do |account| # getting started - manual mail location(url: browser_url + '/#getting_started/channel') @@ -360,6 +360,6 @@ class AaaGettingStartedTest < TestCase location_check( url: '#getting_started/agents', ) - } + end end end diff --git a/test/browser/first_steps_test.rb b/test/browser/first_steps_test.rb index b6316c865..2ed6827c2 100644 --- a/test/browser/first_steps_test.rb +++ b/test/browser/first_steps_test.rb @@ -117,11 +117,11 @@ class FirstStepsTest < TestCase ) click(css: '#navigation a[href="#dashboard"]') hit = false - 37.times { + 37.times do next if !@browser.find_elements(css: '.active.content a[href="#channels/form"].todo.is-done')[0] hit = true break - } + end assert(hit) end diff --git a/test/browser/keyboard_shortcuts_test.rb b/test/browser/keyboard_shortcuts_test.rb index 92e4705c8..6a394e060 100644 --- a/test/browser/keyboard_shortcuts_test.rb +++ b/test/browser/keyboard_shortcuts_test.rb @@ -18,20 +18,20 @@ class KeyboardShortcutsTest < TestCase # ff issue, sometimes shortcut is not fired in browser test env if ENV['BROWSER'] && ENV['BROWSER'] =~ /firefox/i exists = false - (1..4).each { |_count| + (1..4).each do |_count| sleep 1 next if !@browser.find_elements(css: '.modal')[0] exists = true - } + end if !exists reload sleep 4 shortcut(key: 'h') - (1..4).each { |_count| + (1..4).each do |_count| sleep 1 next if !@browser.find_elements(css: '.modal')[0] exists = true - } + end end if !exists shortcut(key: 'h') diff --git a/test/browser_test_helper.rb b/test/browser_test_helper.rb index f0c42a8d1..f8f12fb19 100644 --- a/test/browser_test_helper.rb +++ b/test/browser_test_helper.rb @@ -55,7 +55,7 @@ class TestCase < Test::Unit::TestCase end # avoid "Cannot read property 'get_Current' of undefined" issues - (1..5).each { |count| + (1..5).each do |count| begin local_browser = browser_instance_remote break @@ -64,7 +64,7 @@ class TestCase < Test::Unit::TestCase sleep wait_until_ready log('browser_instance', { rescure: true, count: count, sleep: wait_until_ready }) end - } + end local_browser end @@ -116,10 +116,10 @@ class TestCase < Test::Unit::TestCase def teardown return if !@browsers - @browsers.each { |_hash, local_browser| + @browsers.each do |_hash, local_browser| screenshot(browser: local_browser, comment: 'teardown') browser_instance_close(local_browser) - } + end end def screenshot(params) @@ -258,7 +258,7 @@ class TestCase < Test::Unit::TestCase mute_log: true, ) - 5.times { + 5.times do sleep 1 login = instance.find_elements(css: '#login')[0] @@ -266,7 +266,7 @@ class TestCase < Test::Unit::TestCase screenshot(browser: instance, comment: 'logout_ok') assert(true, 'logout ok') return - } + end screenshot(browser: instance, comment: 'logout_failed') raise 'no login box found, seems logout was not successfully!' end @@ -635,9 +635,9 @@ class TestCase < Test::Unit::TestCase else element.send_keys('') keys = params[:value].to_s.split('') - keys.each { |key| + keys.each do |key| instance.action.send_keys(key).perform - } + end end # it's not working stable with ff via selenium, use js @@ -830,13 +830,13 @@ class TestCase < Test::Unit::TestCase end screenshot(browser: instance, comment: 'sendkey_before') if params[:value].class == Array - params[:value].each { |key| + params[:value].each do |key| if element element.send_keys(key) else instance.action.send_keys(key).perform end - } + end screenshot(browser: instance, comment: 'sendkey_after') return end @@ -878,11 +878,11 @@ class TestCase < Test::Unit::TestCase dropdown = Selenium::WebDriver::Support::Select.new(element) success = false if dropdown.selected_options - dropdown.selected_options.each { |option| + dropdown.selected_options.each do |option| if option.text == params[:value] success = true end - } + end end if params[:should_not_match] if success @@ -1019,7 +1019,7 @@ set type of task (closeTab, closeNextInOverview, stayOnTab) end cookies = instance.manage.all_cookies - cookies.each { |cookie| + cookies.each do |cookie| #puts "CCC #{cookie.inspect}" # :name=>"_zammad_session_c25832f4de2", :value=>"adc31cd21615cb0a7ab269184ec8b76f", :path=>"/", :domain=>"localhost", :expires=>nil, :secure=>false} next if cookie[:name] !~ /#{params[:name]}/i @@ -1038,7 +1038,7 @@ set type of task (closeTab, closeNextInOverview, stayOnTab) return if !params[:should_not_exist] raise "cookie with name '#{params[:name]}' should not exist, but exists '#{cookies}'" - } + end if params[:should_not_exist] assert(true, "cookie with name '#{params[:name]}' is not existing") return @@ -1227,9 +1227,9 @@ set type of task (closeTab, closeNextInOverview, stayOnTab) instance = params[:browser] || @browser - params[:files].each { |file| + params[:files].each do |file| instance.find_elements(css: params[:css])[0].send_keys "#{Rails.root}/#{file}" - } + end sleep 2 * params[:files].count end @@ -1257,7 +1257,7 @@ set type of task (closeTab, closeNextInOverview, stayOnTab) end loops = timeout.to_i * 2 text = '' - (1..loops).each { + (1..loops).each do element = instance.find_elements(css: params[:css])[0] if element #&& element.displayed? begin @@ -1288,7 +1288,7 @@ set type of task (closeTab, closeNextInOverview, stayOnTab) end end sleep 0.5 - } + end screenshot(browser: instance, comment: 'watch_for_failed') if !params[:attribute] && !params[:value] raise "'#{params[:css]}' not found" @@ -1329,7 +1329,7 @@ wait untill text in selector disabppears end loops = timeout.to_i text = '' - (1..loops).each { + (1..loops).each do element = instance.find_elements(css: params[:css])[0] if !element #|| element.displayed? assert(true, 'not found') @@ -1349,7 +1349,7 @@ wait untill text in selector disabppears end end sleep 1 - } + end screenshot(browser: instance, comment: 'disappear_failed') raise "#{params[:css]}) still exsists" end @@ -1631,13 +1631,13 @@ wait untill text in selector disabppears sleep 0.1 end end - data[:roles].each { |role| + data[:roles].each do |role| instance.execute_script("$(\".modal [data-name=role_ids] .js-pool .js-option:not(.is-hidden):contains('#{role}')\").first().click()") - } + end end if data[:selector] - data[:selector].each { |key, value| + data[:selector].each do |key, value| select( browser: instance, css: '.modal .ticket_selector .js-attributeSelector select', @@ -1652,7 +1652,7 @@ wait untill text in selector disabppears deselect_all: true, mute_log: true, ) - } + end end if data['order::direction'] @@ -1666,7 +1666,7 @@ wait untill text in selector disabppears instance.find_elements(css: '.modal button.js-submit')[0].click modal_disappear(browser: instance) - 11.times { + 11.times do element = instance.find_elements(css: 'body')[0] text = element.text if text =~ /#{Regexp.quote(data[:name])}/ @@ -1678,7 +1678,7 @@ wait untill text in selector disabppears return overview end sleep 1 - } + end screenshot(browser: instance, comment: 'overview_create_failed') raise 'overview creation failed' end @@ -1737,13 +1737,13 @@ wait untill text in selector disabppears sleep 0.1 end end - data[:roles].each { |role| + data[:roles].each do |role| instance.execute_script("$(\".modal [data-name=role_ids] .js-pool .js-option:not(.is-hidden):contains('#{role}')\").first().click()") - } + end end if data[:selector] - data[:selector].each { |key, value| + data[:selector].each do |key, value| select( browser: instance, css: '.modal .ticket_selector .js-attributeSelector select', @@ -1758,7 +1758,7 @@ wait untill text in selector disabppears deselect_all: true, mute_log: true, ) - } + end end if data['order::direction'] @@ -1772,7 +1772,7 @@ wait untill text in selector disabppears instance.find_elements(css: '.modal button.js-submit')[0].click modal_disappear(browser: instance) - 11.times { + 11.times do element = instance.find_elements(css: 'body')[0] text = element.text if text =~ /#{Regexp.quote(data[:name])}/ @@ -1784,7 +1784,7 @@ wait untill text in selector disabppears return overview end sleep 1 - } + end screenshot(browser: instance, comment: 'overview_update_failed') raise 'overview update failed' end @@ -1851,14 +1851,14 @@ wait untill text in selector disabppears ) found = false - 7.times { + 7.times do element = instance.find_elements(css: '.content.active .newTicket')[0] if element found = true break end sleep 1 - } + end if !found screenshot(browser: instance, comment: 'ticket_create_failed') raise 'no ticket create screen found!' @@ -1870,18 +1870,18 @@ wait untill text in selector disabppears # check if owner selection exists count = instance.find_elements(css: '.content.active .newTicket select[name="group_id"] option').count if count.nonzero? - instance.find_elements(css: '.content.active .newTicket select[name="group_id"] option').each { |element| + instance.find_elements(css: '.content.active .newTicket select[name="group_id"] option').each do |element| log('ticket_create invalid group count', text: element.text) - } + end end assert_equal(0, count, 'owner selection should not be showm') # check count of agents, should be only 3 / - selection + master + agent on init screen count = instance.find_elements(css: '.content.active .newTicket select[name="owner_id"] option').count if count != 3 - instance.find_elements(css: '.content.active .newTicket select[name="owner_id"] option').each { |element| + instance.find_elements(css: '.content.active .newTicket select[name="owner_id"] option').each do |element| log('ticket_create invalid owner count', text: element.text) - } + end end assert_equal(3, count, 'check if owner selection is - selection + master + agent per default') else @@ -1890,9 +1890,9 @@ wait untill text in selector disabppears if !params[:disable_group_check] count = instance.find_elements(css: '.content.active .newTicket select[name="owner_id"] option').count if count != 1 - instance.find_elements(css: '.content.active .newTicket select[name="owner_id"] option').each { |element| + instance.find_elements(css: '.content.active .newTicket select[name="owner_id"] option').each do |element| log('ticket_create invalid owner count', text: element.text) - } + end end assert_equal(1, count, 'check if owner selection is empty per default') end @@ -1964,23 +1964,23 @@ wait untill text in selector disabppears end if params[:custom_data_select] - params[:custom_data_select].each { |local_key, local_value| + params[:custom_data_select].each do |local_key, local_value| select( browser: instance, css: ".content.active .newTicket select[name=\"#{local_key}\"]", value: local_value, ) - } + end end if params[:custom_data_input] - params[:custom_data_input].each { |local_key, local_value| + params[:custom_data_input].each do |local_key, local_value| set( browser: instance, css: ".content.active .newTicket input[name=\"#{local_key}\"]", value: local_value, clear: true, ) - } + end end if data[:attachment] @@ -2004,7 +2004,7 @@ wait untill text in selector disabppears ) sleep 1 - 9.times { + 9.times do if instance.current_url =~ /#{Regexp.quote('#ticket/zoom/')}/ assert(true, 'ticket created') sleep 2.5 @@ -2026,7 +2026,7 @@ wait untill text in selector disabppears end end sleep 1 - } + end screenshot(browser: instance, comment: 'ticket_create_failed') raise "ticket creation failed, can't get zoom url (current url is '#{instance.current_url}')" end @@ -2198,28 +2198,28 @@ wait untill text in selector disabppears end if params[:custom_data_select] - params[:custom_data_select].each { |local_key, local_value| + params[:custom_data_select].each do |local_key, local_value| select( browser: instance, css: ".active .sidebar select[name=\"#{local_key}\"]", value: local_value, ) - } + end end if params[:custom_data_input] - params[:custom_data_input].each { |local_key, local_value| + params[:custom_data_input].each do |local_key, local_value| set( browser: instance, css: ".active .sidebar input[name=\"#{local_key}\"]", value: local_value, clear: true, ) - } + end end if data[:state] || data[:group] || data[:body] || !params[:custom_data_select].empty? || !params[:custom_data_input].empty? found = nil - 9.times { + 9.times do break if found @@ -2232,7 +2232,7 @@ wait untill text in selector disabppears # try again end sleep 1 - } + end if !found screenshot(browser: instance, comment: 'ticket_update_discard_message_failed') raise 'no discard message found' @@ -2258,7 +2258,7 @@ wait untill text in selector disabppears return end - 9.times { + 9.times do begin text = instance.find_elements(css: '.content.active .js-reset')[0].text if text.blank? @@ -2270,7 +2270,7 @@ wait untill text in selector disabppears # try again end sleep 1 - } + end screenshot(browser: instance, comment: 'ticket_update_failed') raise 'unable to update ticket' end @@ -2321,7 +2321,7 @@ wait untill text in selector disabppears end if params[:custom_data_select] - params[:custom_data_select].each { |local_key, local_value| + params[:custom_data_select].each do |local_key, local_value| element = instance.find_elements(css: ".active .sidebar select[name=\"#{local_key}\"] option[selected]").first value = element.text.strip if value =~ /#{local_value}/i @@ -2329,10 +2329,10 @@ wait untill text in selector disabppears else raise "not matching '#{value}' in #{local_key} '#{local_value}'" end - } + end end if params[:custom_data_input] - params[:custom_data_input].each { |local_key, local_value| + params[:custom_data_input].each do |local_key, local_value| element = instance.find_elements(css: ".active .sidebar input[name=\"#{local_key}\"]").first value = element.text.strip if value =~ /#{local_value}/i @@ -2340,7 +2340,7 @@ wait untill text in selector disabppears else raise "not matching '#{value}' in #{local_key} '#{local_value}'" end - } + end end true @@ -2521,17 +2521,17 @@ wait untill text in selector disabppears #) overviews = {} - instance.find_elements(css: '.content.active .sidebar a[href]').each { |element| + instance.find_elements(css: '.content.active .sidebar a[href]').each do |element| url = element.attribute('href') url.gsub!(%r{(http|https)://.+?/(.+?)$}, '\\2') overviews[url] = 0 #puts url.inspect #puts element.inspect - } - overviews.each { |url, _value| + end + overviews.each do |url, _value| count = instance.find_elements(css: ".content.active .sidebar a[href=\"#{url}\"] .badge")[0].text overviews[url] = count.to_i - } + end log('overview_counter', overviews) overviews end @@ -2732,7 +2732,7 @@ wait untill text in selector disabppears element.send_keys(data[:first_response_time_in_text]) instance.find_elements(css: '.modal button.js-submit')[0].click modal_disappear(browser: instance) - 7.times { + 7.times do element = instance.find_elements(css: 'body')[0] text = element.text if text =~ /#{Regexp.quote(data[:name])}/ @@ -2741,7 +2741,7 @@ wait untill text in selector disabppears return true end sleep 1 - } + end screenshot(browser: instance, comment: 'sla_create_failed') raise 'sla creation failed' end @@ -2799,7 +2799,7 @@ wait untill text in selector disabppears ) instance.find_elements(css: '.modal button.js-submit')[0].click modal_disappear(browser: instance) - 7.times { + 7.times do element = instance.find_elements(css: 'body')[0] text = element.text if text =~ /#{Regexp.quote(data[:name])}/ @@ -2808,7 +2808,7 @@ wait untill text in selector disabppears return true end sleep 1 - } + end screenshot(browser: instance, comment: 'text_module_create_failed') raise 'text module creation failed' end @@ -2866,7 +2866,7 @@ wait untill text in selector disabppears ) instance.find_elements(css: '.modal button.js-submit')[0].click modal_disappear(browser: instance) - 11.times { + 11.times do element = instance.find_elements(css: 'body')[0] text = element.text if text =~ /#{Regexp.quote(data[:name])}/ @@ -2875,7 +2875,7 @@ wait untill text in selector disabppears return true end sleep 1 - } + end screenshot(browser: instance, comment: 'signature_create_failed') raise 'signature creation failed' end @@ -2935,7 +2935,7 @@ wait untill text in selector disabppears end instance.find_elements(css: '.modal button.js-submit')[0].click modal_disappear(browser: instance) - 11.times { + 11.times do element = instance.find_elements(css: 'body')[0] text = element.text if text =~ /#{Regexp.quote(data[:name])}/ @@ -2944,7 +2944,7 @@ wait untill text in selector disabppears # add member if data[:member] - data[:member].each { |member| + data[:member].each do |member| instance.find_elements(css: 'a[href="#manage"]')[0].click sleep 1 instance.find_elements(css: '.content.active a[href="#manage/users"]')[0].click @@ -2961,12 +2961,12 @@ wait untill text in selector disabppears screenshot(browser: instance, comment: 'group_create_member') instance.find_elements(css: '.modal button.js-submit')[0].click modal_disappear(browser: instance) - } + end end end sleep 1 return true - } + end screenshot(browser: instance, comment: 'group_create_failed') raise 'group creation failed' end @@ -3028,7 +3028,7 @@ wait untill text in selector disabppears end if data.key?(:permission) - data[:permission].each { |permission_name, permission_value| + data[:permission].each do |permission_name, permission_value| if permission_value == false uncheck( browser: instance, @@ -3040,12 +3040,12 @@ wait untill text in selector disabppears css: ".modal [data-permission-name=\"#{permission_name}\"]", ) end - } + end end instance.find_elements(css: '.modal button.js-submit')[0].click modal_disappear(browser: instance) - 11.times { + 11.times do element = instance.find_elements(css: 'body')[0] text = element.text if text =~ /#{Regexp.quote(data[:name])}/ @@ -3054,7 +3054,7 @@ wait untill text in selector disabppears # add member if data[:member] - data[:member].each { |login| + data[:member].each do |login| instance.find_elements(css: 'a[href="#manage"]')[0].click sleep 1 instance.find_elements(css: '.content.active a[href="#manage/users"]')[0].click @@ -3070,12 +3070,12 @@ wait untill text in selector disabppears instance.execute_script('$(\'label:contains(" ' + data[:name] + '")\').first().click()') instance.find_elements(css: '.modal button.js-submit')[0].click modal_disappear(browser: instance) - } + end end end sleep 1 return true - } + end screenshot(browser: instance, comment: 'role_create_failed') raise 'role creation failed' end @@ -3134,7 +3134,7 @@ wait untill text in selector disabppears end if data.key?(:permission) - data[:permission].each { |permission_name, permission_value| + data[:permission].each do |permission_name, permission_value| if permission_value == false uncheck( browser: instance, @@ -3146,7 +3146,7 @@ wait untill text in selector disabppears css: ".modal [data-permission-name=\"#{permission_name}\"]", ) end - } + end end if data.key?(:active) @@ -3161,7 +3161,7 @@ wait untill text in selector disabppears instance.find_elements(css: '.modal button.js-submit')[0].click modal_disappear(browser: instance) - 11.times { + 11.times do element = instance.find_elements(css: 'body')[0] text = element.text if text =~ /#{Regexp.quote(data[:name])}/ @@ -3170,7 +3170,7 @@ wait untill text in selector disabppears # add member if data[:member] - data[:member].each { |login| + data[:member].each do |login| instance.find_elements(css: 'a[href="#manage"]')[0].click sleep 1 instance.find_elements(css: '.content.active a[href="#manage/users"]')[0].click @@ -3186,12 +3186,12 @@ wait untill text in selector disabppears instance.execute_script('$(\'label:contains(" ' + data[:name] + '")\').first().click()') instance.find_elements(css: '.modal button.js-submit')[0].click modal_disappear(browser: instance) - } + end end end sleep 1 return true - } + end screenshot(browser: instance, comment: 'role_edit_failed') raise 'role edit failed' end @@ -3339,7 +3339,7 @@ wait untill text in selector disabppears element.clear element.send_keys(data[:data_option][:options][:false]) else - data[:data_option][:options].each { |key, value| + data[:data_option][:options].each do |key, value| element = instance.find_elements(css: '.modal .js-Table .js-key').last element.clear element.send_keys(key) @@ -3348,18 +3348,18 @@ wait untill text in selector disabppears element.send_keys(value) element = instance.find_elements(css: '.modal .js-Table .js-add')[0] element.click - } + end end end - [:default, :min, :max, :diff].each { |key| + [:default, :min, :max, :diff].each do |key| next if !data[:data_option].key?(key) element = instance.find_elements(css: ".modal [name=\"data_option::#{key}\"]").first element.clear element.send_keys(data[:data_option][key]) - } + end - [:future, :past].each { |key| + [:future, :past].each do |key| next if !data[:data_option].key?(key) select( browser: instance, @@ -3367,7 +3367,7 @@ wait untill text in selector disabppears value: data[:data_option][key], mute_log: true, ) - } + end end instance.find_elements(css: '.modal button.js-submit')[0].click @@ -3385,7 +3385,7 @@ wait untill text in selector disabppears return end - 11.times { + 11.times do element = instance.find_elements(css: 'body')[0] text = element.text if text =~ /#{Regexp.quote(data[:name])}/ @@ -3394,7 +3394,7 @@ wait untill text in selector disabppears return true end sleep 1 - } + end screenshot(browser: instance, comment: 'object_manager_attribute_create_failed') raise 'object manager attribute creation failed' end @@ -3461,7 +3461,7 @@ wait untill text in selector disabppears element.clear element.send_keys(data[:data_option][:options][:false]) else - data[:data_option][:options].each { |key, value| + data[:data_option][:options].each do |key, value| element = instance.find_elements(css: '.modal .js-Table .js-key').last element.clear element.send_keys(key) @@ -3470,18 +3470,18 @@ wait untill text in selector disabppears element.send_keys(value) element = instance.find_elements(css: '.modal .js-Table .js-add')[0] element.click - } + end end end - [:default, :min, :max, :diff].each { |key| + [:default, :min, :max, :diff].each do |key| next if !data[:data_option].key?(key) element = instance.find_elements(css: ".modal [name=\"data_option::#{key}\"]").first element.clear element.send_keys(data[:data_option][key]) - } + end - [:future, :past].each { |key| + [:future, :past].each do |key| next if !data[:data_option].key?(key) select( browser: instance, @@ -3489,7 +3489,7 @@ wait untill text in selector disabppears value: data[:data_option][key], mute_log: true, ) - } + end end instance.find_elements(css: '.modal button.js-submit')[0].click @@ -3507,7 +3507,7 @@ wait untill text in selector disabppears return end - 11.times { + 11.times do element = instance.find_elements(css: 'body')[0] text = element.text if text =~ /#{Regexp.quote(data[:name])}/ @@ -3516,7 +3516,7 @@ wait untill text in selector disabppears return true end sleep 1 - } + end screenshot(browser: instance, comment: 'object_manager_attribute_update_failed') raise 'object manager attribute update failed' end @@ -3617,21 +3617,21 @@ wait untill text in selector disabppears assert(tags[0]) tags_found = {} - params[:tags].each { |key, _value| + params[:tags].each do |key, _value| tags_found[key] = false - } + end - tags.each { |element| + tags.each do |element| text = element.text if tags_found.key?(text) tags_found[text] = true else assert(false, "tag exists but is not in check to verify '#{text}'") end - } - params[:tags].each { |key, value| + end + params[:tags].each do |key, value| assert_equal(value, tags_found[key], "tag '#{key}'") - } + end end def quote(string) @@ -3656,11 +3656,11 @@ wait untill text in selector disabppears instance = params[:browser] || @browser if instance logs = instance.manage.logs.get(:browser) - logs.each { |log| + logs.each do |log| next if log.level == 'WARNING' && log.message =~ /Declaration\sdropped./ # ignore ff css warnings time = Time.zone.parse(Time.zone.at(log.timestamp / 1000).to_datetime.to_s) puts "#{time}/#{log.level}: #{log.message}" - } + end end rescue # failed to get logs diff --git a/test/controllers/form_controller_test.rb b/test/controllers/form_controller_test.rb index 8aacf1157..1eb9a844a 100644 --- a/test/controllers/form_controller_test.rb +++ b/test/controllers/form_controller_test.rb @@ -195,7 +195,7 @@ class FormControllerTest < ActionDispatch::IntegrationTest assert(result['token']) token = result['token'] - (1..20).each { |count| + (1..20).each do |count| travel 10.seconds post '/api/v1/form_submit', params: { fingerprint: fingerprint, token: token, name: 'Bob Smith', email: 'discard@znuny.com', title: "test#{count}", body: 'hello' }.to_json, headers: @headers assert_response(200) @@ -208,7 +208,7 @@ class FormControllerTest < ActionDispatch::IntegrationTest assert(result['ticket']['number']) Scheduler.worker(true) sleep 1 # wait until elasticsearch is index - } + end sleep 10 # wait until elasticsearch is index @@ -220,7 +220,7 @@ class FormControllerTest < ActionDispatch::IntegrationTest @headers = { 'ACCEPT' => 'application/json', 'CONTENT_TYPE' => 'application/json', 'REMOTE_ADDR' => '1.2.3.5' } - (1..20).each { |count| + (1..20).each do |count| travel 10.seconds post '/api/v1/form_submit', params: { fingerprint: fingerprint, token: token, name: 'Bob Smith', email: 'discard@znuny.com', title: "test-2-#{count}", body: 'hello' }.to_json, headers: @headers assert_response(200) @@ -233,7 +233,7 @@ class FormControllerTest < ActionDispatch::IntegrationTest assert(result['ticket']['number']) Scheduler.worker(true) sleep 1 # wait until elasticsearch is index - } + end sleep 10 # wait until elasticsearch is index diff --git a/test/controllers/monitoring_controller_test.rb b/test/controllers/monitoring_controller_test.rb index a511a95ee..26bfe7389 100644 --- a/test/controllers/monitoring_controller_test.rb +++ b/test/controllers/monitoring_controller_test.rb @@ -17,22 +17,22 @@ class MonitoringControllerTest < ActionDispatch::IntegrationTest # channel cleanup Channel.where.not(area: 'Email::Notification').destroy_all - Channel.all.each { |channel| + Channel.all.each do |channel| channel.status_in = 'ok' channel.status_out = 'ok' channel.last_log_in = nil channel.last_log_out = nil channel.save! - } + end dir = "#{Rails.root}/tmp/unprocessable_mail" Dir.glob("#{dir}/*.eml") do |entry| File.delete(entry) end - Scheduler.where(active: true).each { |scheduler| + Scheduler.where(active: true).each do |scheduler| scheduler.last_run = Time.zone.now scheduler.save! - } + end permission = Permission.find_by(name: 'admin.monitoring') permission.active = true diff --git a/test/controllers/settings_controller_test.rb b/test/controllers/settings_controller_test.rb index 6206b8730..93249425b 100644 --- a/test/controllers/settings_controller_test.rb +++ b/test/controllers/settings_controller_test.rb @@ -101,14 +101,14 @@ class SettingsControllerTest < ActionDispatch::IntegrationTest assert(result) hit_api = false hit_product_name = false - result.each { |setting| + result.each do |setting| if setting['name'] == 'api_token_access' hit_api = true end if setting['name'] == 'product_name' hit_product_name = true end - } + end assert_equal(true, hit_api) assert_equal(true, hit_product_name) @@ -185,14 +185,14 @@ class SettingsControllerTest < ActionDispatch::IntegrationTest assert(result) hit_api = false hit_product_name = false - result.each { |setting| + result.each do |setting| if setting['name'] == 'api_token_access' hit_api = true end if setting['name'] == 'product_name' hit_product_name = true end - } + end assert_equal(true, hit_api) assert_equal(false, hit_product_name) diff --git a/test/controllers/tickets_controller_test.rb b/test/controllers/tickets_controller_test.rb index b21aaee60..d63bac89e 100644 --- a/test/controllers/tickets_controller_test.rb +++ b/test/controllers/tickets_controller_test.rb @@ -801,7 +801,7 @@ AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO test '02.05 ticket pagination' do title = "ticket pagination #{rand(999_999_999)}" tickets = [] - (1..20).each { |count| + (1..20).each do |count| ticket = Ticket.create!( title: "#{title} - #{count}", group: Group.lookup(name: 'Users'), @@ -823,7 +823,7 @@ AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO ) tickets.push ticket travel 2.seconds - } + end credentials = ActionController::HttpAuthentication::Basic.encode_credentials('tickets-admin', 'adminpw') get "/api/v1/tickets/search?query=#{CGI.escape(title)}&limit=40", params: {}, headers: @headers.merge('Authorization' => credentials) diff --git a/test/fixtures/seeds.rb b/test/fixtures/seeds.rb index 158350737..4d788de1d 100644 --- a/test/fixtures/seeds.rb +++ b/test/fixtures/seeds.rb @@ -18,7 +18,7 @@ email_address = EmailAddress.create_or_update( updated_by_id: 1, created_by_id: 1 ) -Group.all.each { |group| +Group.all.each do |group| group.email_address_id = email_address.id group.save -} +end diff --git a/test/integration/auto_wizard_test.rb b/test/integration/auto_wizard_test.rb index b47d62701..d7cde3d0d 100644 --- a/test/integration/auto_wizard_test.rb +++ b/test/integration/auto_wizard_test.rb @@ -48,7 +48,7 @@ class AutoWizardTest < ActiveSupport::TestCase # check first user roles auto_wizard_data[:Users][0][:roles] = %w(Agent Admin) - auto_wizard_data[:Users].each { |local_user| + auto_wizard_data[:Users].each do |local_user| user = User.find_by(login: local_user[:login]) assert_equal(local_user[:login], user.login) assert_equal(local_user[:firstname], user.firstname) @@ -56,24 +56,24 @@ class AutoWizardTest < ActiveSupport::TestCase assert_equal(local_user[:email], user.email) assert_equal(local_user[:roles].count, user.role_ids.count) next unless local_user[:roles] - local_user[:roles].each { |local_role_name| + local_user[:roles].each do |local_role_name| local_role = Role.find_by(name: local_role_name) assert(user.role_ids.include?(local_role.id)) - } - } - auto_wizard_data[:Groups].each { |local_group| + end + end + auto_wizard_data[:Groups].each do |local_group| group = Group.find_by(name: local_group[:name]) assert_equal(local_group[:name], group.name) next unless local_group[:users] - local_group[:users].each { |local_user_login| + local_group[:users].each do |local_user_login| local_user = User.find_by(login: local_user_login) assert(group.user_ids.include?(local_user.id)) - } - } - auto_wizard_data[:Settings].each { |local_setting| + end + end + auto_wizard_data[:Settings].each do |local_setting| setting_value = Setting.get(local_setting[:name]) assert_equal(local_setting[:value], setting_value) - } + end end test 'b complex' do @@ -177,7 +177,7 @@ class AutoWizardTest < ActiveSupport::TestCase assert_equal('Switzerland', Calendar.first.name) assert_equal('Europe/Zurich', Calendar.first.timezone) - auto_wizard_data[:Users].each { |local_user| + auto_wizard_data[:Users].each do |local_user| user = User.find_by(login: local_user[:login]) assert_equal(local_user[:login], user.login) assert_equal(local_user[:firstname], user.firstname) @@ -185,42 +185,42 @@ class AutoWizardTest < ActiveSupport::TestCase assert_equal(local_user[:email], user.email) next unless local_user[:roles] assert_equal(local_user[:roles].count, user.role_ids.count) - local_user[:roles].each { |local_role_name| + local_user[:roles].each do |local_role_name| local_role = Role.find_by(name: local_role_name) assert(user.role_ids.include?(local_role.id)) - } - } - auto_wizard_data[:Groups].each { |local_group| + end + end + auto_wizard_data[:Groups].each do |local_group| group = Group.find_by(name: local_group[:name]) assert_equal(local_group[:name], group.name) if local_group[:users] - local_group[:users].each { |local_user_login| + local_group[:users].each do |local_user_login| local_user = User.find_by(login: local_user_login) assert(group.user_ids.include?(local_user.id)) - } + end end if local_group[:signature] signature = group.signature assert_equal('default', signature.name) end - } - auto_wizard_data[:EmailAddresses].each { |local_email_address| + end + auto_wizard_data[:EmailAddresses].each do |local_email_address| email_address = EmailAddress.find_by(email: local_email_address[:email]) assert_equal(local_email_address[:email], email_address.email) assert_equal(local_email_address[:realname], email_address.realname) channel = email_address.channel assert_equal(local_email_address[:channel_id], email_address.channel.id) - } - auto_wizard_data[:Channels].each { |local_channel| + end + auto_wizard_data[:Channels].each do |local_channel| channel = Channel.find_by(id: local_channel[:id]) assert_equal(local_channel[:area], channel.area) group = channel.group assert_equal(local_channel[:group], group.name) - } - auto_wizard_data[:Settings].each { |local_setting| + end + auto_wizard_data[:Settings].each do |local_setting| setting_value = Setting.get(local_setting[:name]) assert_equal(local_setting[:value], setting_value) - } + end end def auto_wizard_file_write(data) diff --git a/test/integration/calendar_subscriptions_tickets_test.rb b/test/integration/calendar_subscriptions_tickets_test.rb index e7866c10d..0816aacb8 100644 --- a/test/integration/calendar_subscriptions_tickets_test.rb +++ b/test/integration/calendar_subscriptions_tickets_test.rb @@ -185,10 +185,10 @@ class CalendarSubscriptionsTicketsTest < ActiveSupport::TestCase }, ] - tickets.each { |ticket| + tickets.each do |ticket| Ticket.create( ticket ) - } + end defaults_disabled = { escalation: { @@ -254,7 +254,7 @@ class CalendarSubscriptionsTicketsTest < ActiveSupport::TestCase }, ] - tests.each { |test_data| + tests.each do |test_data| preferences = defaults_disabled.merge( test_data[:preferences] ) @@ -269,7 +269,7 @@ class CalendarSubscriptionsTicketsTest < ActiveSupport::TestCase calendar_subscriptions = CalendarSubscriptions.new( user ) ical = calendar_subscriptions.all - event_data.each { |event| + event_data.each do |event| contained = false if ical =~ /#{event[:summary]}/ @@ -277,8 +277,8 @@ class CalendarSubscriptionsTicketsTest < ActiveSupport::TestCase end assert( contained, "#{test_data[:name]} new_open ical contains '#{event[:summary]}'" ) - } - } + end + end end test 'pending' do @@ -330,7 +330,7 @@ class CalendarSubscriptionsTicketsTest < ActiveSupport::TestCase }, ] - tests.each { |test_data| + tests.each do |test_data| preferences = defaults_disabled.merge( test_data[:preferences] ) @@ -345,7 +345,7 @@ class CalendarSubscriptionsTicketsTest < ActiveSupport::TestCase calendar_subscriptions = CalendarSubscriptions.new( user ) ical = calendar_subscriptions.all - event_data.each { |event| + event_data.each do |event| contained = false if ical =~ /#{event[:summary]}/ @@ -353,8 +353,8 @@ class CalendarSubscriptionsTicketsTest < ActiveSupport::TestCase end assert( contained, "#{test_data[:name]} pending ical contains '#{event[:summary]}'" ) - } - } + end + end end test 'escalation' do @@ -406,7 +406,7 @@ class CalendarSubscriptionsTicketsTest < ActiveSupport::TestCase }, ] - tests.each { |test_data| + tests.each do |test_data| preferences = defaults_disabled.merge( test_data[:preferences] ) @@ -421,7 +421,7 @@ class CalendarSubscriptionsTicketsTest < ActiveSupport::TestCase calendar_subscriptions = CalendarSubscriptions.new( user ) ical = calendar_subscriptions.all - event_data.each { |event| + event_data.each do |event| contained = false if ical =~ /#{event[:summary]}/ @@ -429,8 +429,8 @@ class CalendarSubscriptionsTicketsTest < ActiveSupport::TestCase end assert( contained, "#{test_data[:name]} escalation ical contains '#{event[:summary]}'" ) - } - } + end + end end end diff --git a/test/integration/email_deliver_test.rb b/test/integration/email_deliver_test.rb index bb5f48251..5b069068d 100644 --- a/test/integration/email_deliver_test.rb +++ b/test/integration/email_deliver_test.rb @@ -114,10 +114,10 @@ class EmailDeliverTest < ActiveSupport::TestCase }, }, ) - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do result = Observer::Ticket::Article::CommunicateEmail::BackgroundJob.new(article1.id) assert_not(result.perform) - } + end article1_lookup = Ticket::Article.find(article1.id) assert_equal(2, article1_lookup.preferences['delivery_retry']) assert_equal('fail', article1_lookup.preferences['delivery_status']) @@ -205,9 +205,9 @@ class EmailDeliverTest < ActiveSupport::TestCase ticket1.state = Ticket::State.find_by(name: 'closed') ticket1.save - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do Scheduler.worker(true) - } + end ticket1.reload article2_lookup = Ticket::Article.find(article2.id) @@ -229,9 +229,9 @@ class EmailDeliverTest < ActiveSupport::TestCase assert_equal('closed', ticket1.state.name) sleep 6 - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do Scheduler.worker(true) - } + end ticket1.reload article2_lookup = Ticket::Article.find(article2.id) @@ -254,9 +254,9 @@ class EmailDeliverTest < ActiveSupport::TestCase assert_equal('closed', ticket1.state.name) sleep 11 - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do Scheduler.worker(true) - } + end ticket1.reload article2_lookup = Ticket::Article.find(article2.id) @@ -268,9 +268,9 @@ class EmailDeliverTest < ActiveSupport::TestCase assert_equal('closed', ticket1.state.name) sleep 16 - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do Scheduler.worker(true) - } + end ticket1.reload article2_lookup = Ticket::Article.find(article2.id) diff --git a/test/integration/facebook_test.rb b/test/integration/facebook_test.rb index 8ea2ade71..de647a283 100644 --- a/test/integration/facebook_test.rb +++ b/test/integration/facebook_test.rb @@ -82,26 +82,26 @@ class FacebookTest < ActiveSupport::TestCase test 'b - available pages' do client = Facebook.new(user_access_token) page_found = false - client.pages.each { |page| + client.pages.each do |page| next if page[:name] != page_name page_found = true assert_equal(page_id, page[:id]) assert_equal(page_name, page[:name]) - } + end assert(page_found, "Page lookup for '#{page_name}'") end # check access to pages test 'c - page access' do page_found = false - provider_options[:pages].each { |page| + provider_options[:pages].each do |page| client = Facebook.new(page['access_token']) current_user = client.current_user next if page['name'] != page_name page_found = true assert_equal(page_id, current_user['id']) assert_equal(page_name, current_user['name']) - } + end assert(page_found, "Page lookup for '#{page_name}'") end diff --git a/test/integration/otrs_import_test.rb b/test/integration/otrs_import_test.rb index 818727393..c3a839d5a 100644 --- a/test/integration/otrs_import_test.rb +++ b/test/integration/otrs_import_test.rb @@ -33,11 +33,11 @@ class OtrsImportTest < ActiveSupport::TestCase test 'check dynamic fields' do local_objects = ObjectManager::Attribute.list_full - object_attribute_names = local_objects.reject { |local_object| + object_attribute_names = local_objects.reject do |local_object| local_object[:object] != 'Ticket' - }.collect { |local_object| + end.collect do |local_object| local_object['name'] - } + end expected_object_attribute_names = %w(vertriebsweg te_test sugar_crm_remote_no sugar_crm_company_selected_no sugar_crm_company_selection combine itsm_criticality customer_id itsm_impact itsm_review_required itsm_decision_result itsm_repair_start_time itsm_recovery_start_time itsm_decision_date title itsm_due_date topic_no open_exchange_ticket_number hostname ticket_free_key11 type ticket_free_text11 open_exchange_tn topic zarafa_tn group_id scom_hostname checkbox_example scom_uuid scom_state scom_service location owner_id department customer_location state_id pending_time priority_id tags) assert_equal(expected_object_attribute_names, object_attribute_names, 'dynamic field names') diff --git a/test/integration/slack_test.rb b/test/integration/slack_test.rb index 6a99642fc..52847def9 100644 --- a/test/integration/slack_test.rb +++ b/test/integration/slack_test.rb @@ -282,10 +282,10 @@ class SlackTest < ActiveSupport::TestCase client = Slack::Client.new channels = client.channels_list['channels'] channel_id = nil - channels.each { |channel| + channels.each do |channel| next if channel['name'] != channel_name channel_id = channel['id'] - } + end if !channel_id raise "ERROR: No such channel '#{channel_name}'" end @@ -298,13 +298,13 @@ class SlackTest < ActiveSupport::TestCase raise "ERROR: No history messages for channel #{channel_name}/#{channel_id}" end message_count = 0 - channel_history['messages'].each { |message| + channel_history['messages'].each do |message| next if !message['text'] if message['text'] =~ /#{search_for}/i message_count += 1 p "SUCCESS: message with #{search_for} found #{message_count} time(s)!" end - } + end message_count end diff --git a/test/integration/telegram_controller_test.rb b/test/integration/telegram_controller_test.rb index c07dabc35..c31465ca1 100644 --- a/test/integration/telegram_controller_test.rb +++ b/test/integration/telegram_controller_test.rb @@ -23,9 +23,9 @@ class TelegramControllerTest < ActionDispatch::IntegrationTest stub_request(:post, 'https://api.telegram.org/botnot_existing/getMe') .to_return(status: 404, body: '{"ok":false,"error_code":404,"description":"Not Found"}', headers: {}) - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do Telegram.check_token('not_existing') - } + end # try valid token stub_request(:post, "https://api.telegram.org/bot#{token}/getMe") @@ -38,9 +38,9 @@ class TelegramControllerTest < ActionDispatch::IntegrationTest .to_return(status: 200, body: "{\"ok\":true,\"result\":{\"id\":#{bot_id},\"first_name\":\"Chrispresso Customer Service\",\"username\":\"ChrispressoBot\"}}", headers: {}) Setting.set('http_type', 'http') - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do Telegram.create_or_update_channel(token, { group_id: group_id, welcome: 'hi!' }) - } + end # try invalid port stub_request(:post, "https://api.telegram.org:443/bot#{token}/getMe") @@ -51,9 +51,9 @@ class TelegramControllerTest < ActionDispatch::IntegrationTest Setting.set('http_type', 'https') Setting.set('fqdn', 'somehost.example.com:12345') - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do Telegram.create_or_update_channel(token, { group_id: group_id, welcome: 'hi!' }) - } + end # try invalid host stub_request(:post, "https://api.telegram.org:443/bot#{token}/setWebhook") @@ -61,9 +61,9 @@ class TelegramControllerTest < ActionDispatch::IntegrationTest .to_return(status: 400, body: '{"ok":false,"error_code":400,"description":"Bad Request: bad webhook: getaddrinfo: Name or service not known"}', headers: {}) Setting.set('fqdn', 'somehost.example.com') - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do Telegram.create_or_update_channel(token, { group_id: group_id, welcome: 'hi!' }) - } + end # valid token, host and port stub_request(:post, "https://api.telegram.org:443/bot#{token}/setWebhook") diff --git a/test/integration/twitter_browser_test.rb b/test/integration/twitter_browser_test.rb index 32bef3329..dab4ae94e 100644 --- a/test/integration/twitter_browser_test.rb +++ b/test/integration/twitter_browser_test.rb @@ -265,9 +265,9 @@ class TwitterBrowserTest < TestCase # watch till tweet reached customer sleep 10 text = nil - client.search(re_hash, result_type: 'mixed').collect { |local_tweet| + client.search(re_hash, result_type: 'mixed').collect do |local_tweet| text = local_tweet.text - } + end assert(text) end diff --git a/test/integration/twitter_test.rb b/test/integration/twitter_test.rb index 53f640191..2675cdf87 100644 --- a/test/integration/twitter_test.rb +++ b/test/integration/twitter_test.rb @@ -138,11 +138,11 @@ class TwitterTest < ActiveSupport::TestCase end tweet_found = false - client.user_timeline(system_login_without_at).each { |tweet| + client.user_timeline(system_login_without_at).each do |tweet| next if tweet.id.to_s != article.message_id.to_s tweet_found = true break - } + end assert(tweet_found, "found outbound '#{text}' tweet '#{article.message_id}'") reply_text = "#{system_login} on my side the weather is nice, too! 😍😍😍 #weather#{rand(999_999)}" @@ -156,14 +156,14 @@ class TwitterTest < ActiveSupport::TestCase # fetch check system account sleep 10 article = nil - 2.times { + 2.times do Channel.fetch # check if follow up article has been created article = Ticket::Article.find_by(message_id: tweet.id) break if article sleep 10 - } + end assert(article, "article tweet '#{tweet.id}' imported") assert_equal(customer_login, article.from, 'ticket article from') @@ -200,14 +200,14 @@ class TwitterTest < ActiveSupport::TestCase # fetch check system account sleep 20 article = nil - 2.times { + 2.times do Channel.fetch # check if ticket and article has been created article = Ticket::Article.find_by(message_id: tweet.id) break if article sleep 20 - } + end assert(article, "Can't find tweet id #{tweet.id}/#{text}") assert_equal(customer_login, article.from, 'ticket article from') assert_nil(article.to, 'ticket article to') @@ -235,12 +235,12 @@ class TwitterTest < ActiveSupport::TestCase assert_equal(customer_login, article.to, 'ticket article to') sleep 5 tweet_found = false - client.user_timeline(system_login_without_at).each { |local_tweet| + client.user_timeline(system_login_without_at).each do |local_tweet| sleep 10 next if local_tweet.id.to_s != article.message_id.to_s tweet_found = true break - } + end assert(tweet_found, "found outbound '#{reply_text}' tweet '#{article.message_id}'") channel = Channel.find(channel.id) @@ -270,14 +270,14 @@ class TwitterTest < ActiveSupport::TestCase # fetch check system account sleep 20 article = nil - 2.times { + 2.times do Channel.fetch # check if ticket and article has been created article = Ticket::Article.find_by(message_id: tweet.id) break if article sleep 20 - } + end assert(article, "Can't find tweet id #{tweet.id}/#{text}") assert_equal('closed', ticket.reload.state.name) @@ -293,9 +293,9 @@ class TwitterTest < ActiveSupport::TestCase config.access_token_secret = system_token_secret end dms = client.direct_messages(count: 100) - dms.each { |dm| + dms.each do |dm| client.destroy_direct_message(dm.id) - } + end client = Twitter::REST::Client.new( consumer_key: consumer_key, consumer_secret: consumer_secret, @@ -303,9 +303,9 @@ class TwitterTest < ActiveSupport::TestCase access_token_secret: customer_token_secret ) dms = client.direct_messages(count: 100) - dms.each { |dm| + dms.each do |dm| client.destroy_direct_message(dm.id) - } + end hash = "#citheo44 #{hash_gen}" text = "How about #{rand_word} the details? #{hash} - #{'Long' * 50}" dm = client.create_direct_message( @@ -317,14 +317,14 @@ class TwitterTest < ActiveSupport::TestCase # fetch check system account sleep 15 article = nil - 1.times { + 1.times do Channel.fetch # check if ticket and article has been created article = Ticket::Article.find_by(message_id: dm.id) break if article sleep 10 - } + end assert(article, "inbound article '#{text}' created") assert_equal(customer_login, article.from, 'ticket article from') @@ -367,14 +367,14 @@ class TwitterTest < ActiveSupport::TestCase # fetch check system account sleep 15 article = nil - 1.times { + 1.times do Channel.fetch # check if ticket and article has been created article = Ticket::Article.find_by(message_id: dm.id) break if article sleep 10 - } + end assert(article, "inbound article '#{text}' created") assert_equal(customer_login, article.from, 'ticket article inbound from') @@ -400,14 +400,14 @@ class TwitterTest < ActiveSupport::TestCase # fetch check system account sleep 15 article = nil - 1.times { + 1.times do Channel.fetch # check if ticket and article has been created article = Ticket::Article.find_by(message_id: dm.id) break if article sleep 15 - } + end assert(article, "inbound article '#{text}' created with dm id #{dm.id}") assert_equal(customer_login, article.from, 'ticket article inbound from') @@ -454,14 +454,14 @@ class TwitterTest < ActiveSupport::TestCase # fetch check system account sleep 15 article = nil - 2.times { + 2.times do Channel.fetch # check if ticket and article has been created article = Ticket::Article.find_by(message_id: retweet.id) break if article sleep 10 - } + end assert(article, "retweet article '#{text}' created") end @@ -495,22 +495,22 @@ class TwitterTest < ActiveSupport::TestCase # fetch check system account sleep 15 article = nil - 2.times { + 2.times do Channel.fetch # check if ticket and article has been created article = Ticket::Article.find_by(message_id: retweet.id) break if article sleep 10 - } + end assert_nil(article, "retweet article '#{text}' not created") end test 'f streaming test' do - thread = Thread.new { + thread = Thread.new do Channel.stream - } + end sleep 10 # new tweet I - by me_bauer @@ -528,14 +528,14 @@ class TwitterTest < ActiveSupport::TestCase ) article = nil - 5.times { + 5.times do Scheduler.worker(true) article = Ticket::Article.find_by(message_id: tweet.id) break if article ActiveRecord::Base.clear_all_connections! ActiveRecord::Base.connection.query_cache.clear sleep 10 - } + end assert(article, "article from customer with text '#{text}' message_id '#{tweet.id}' created") assert_equal(customer_login, article.from, 'ticket article from') assert_nil(article.to, 'ticket article to') @@ -554,14 +554,14 @@ class TwitterTest < ActiveSupport::TestCase ) article = nil - 5.times { + 5.times do Scheduler.worker(true) article = Ticket::Article.find_by(message_id: tweet.id) break if article ActiveRecord::Base.clear_all_connections! ActiveRecord::Base.connection.query_cache.clear sleep 10 - } + end assert(article, "article from customer with text '#{text}' message_id '#{tweet.id}' created") assert_equal(customer_login, article.from, 'ticket article from') assert_nil(article.to, 'ticket article to') @@ -587,12 +587,12 @@ class TwitterTest < ActiveSupport::TestCase sleep 5 tweet_found = false - client.user_timeline(system_login_without_at).each { |local_tweet| + client.user_timeline(system_login_without_at).each do |local_tweet| sleep 10 next if local_tweet.id.to_s != article.message_id.to_s tweet_found = true break - } + end assert(tweet_found, "found outbound '#{reply_text}' tweet '#{article.message_id}'") count = Ticket::Article.where(message_id: article.message_id).count @@ -620,12 +620,12 @@ class TwitterTest < ActiveSupport::TestCase assert(dm, "dm with ##{hash} created") article = nil - 5.times { + 5.times do Scheduler.worker(true) article = Ticket::Article.find_by(message_id: dm.id) break if article sleep 10 - } + end assert(article, "inbound article '#{text}' message_id '#{dm.id}' created") assert_equal(customer_login, article.from, 'ticket article from') assert_equal(system_login, article.to, 'ticket article to') @@ -634,7 +634,7 @@ class TwitterTest < ActiveSupport::TestCase end test 'g streaming test retweet enabled' do - thread = Thread.new { + thread = Thread.new do # enable track_retweets in current thread # since Threads are not spawned in the same scope # as the current test is running in ..... @@ -643,7 +643,7 @@ class TwitterTest < ActiveSupport::TestCase channel_thread.save! Channel.stream - } + end sleep 10 client = Twitter::REST::Client.new do |config| @@ -669,7 +669,7 @@ class TwitterTest < ActiveSupport::TestCase # fetch check system account sleep 15 article = nil - 2.times { + 2.times do Channel.fetch # check if ticket and article has been created @@ -678,7 +678,7 @@ class TwitterTest < ActiveSupport::TestCase ActiveRecord::Base.clear_all_connections! ActiveRecord::Base.connection.query_cache.clear sleep 10 - } + end assert(article, "retweet article '#{text}' created") @@ -687,7 +687,7 @@ class TwitterTest < ActiveSupport::TestCase end test 'h streaming test retweet disabled' do - thread = Thread.new { + thread = Thread.new do # disable track_retweets in current thread # since Threads are not spawned in the same scope # as the current test is running in ..... @@ -696,7 +696,7 @@ class TwitterTest < ActiveSupport::TestCase channel_thread.save! Channel.stream - } + end sleep 10 client = Twitter::REST::Client.new do |config| @@ -721,12 +721,12 @@ class TwitterTest < ActiveSupport::TestCase # fetch check system account article = nil - 4.times { + 4.times do # check if ticket and article has been created article = Ticket::Article.find_by(message_id: retweet.id) break if article sleep 10 - } + end assert_nil(article, "retweet article '#{text}' not created") @@ -737,7 +737,7 @@ class TwitterTest < ActiveSupport::TestCase test 'i restart stream after config of channel has changed' do hash = "#citheo#{rand(999)}" - thread = Thread.new { + thread = Thread.new do Channel.stream sleep 10 item = { @@ -747,7 +747,7 @@ class TwitterTest < ActiveSupport::TestCase channel_thread = Channel.find(channel.id) channel_thread[:options]['sync']['search'].push item channel_thread.save! - } + end sleep 60 @@ -765,14 +765,14 @@ class TwitterTest < ActiveSupport::TestCase text, ) article = nil - 5.times { + 5.times do Scheduler.worker(true) article = Ticket::Article.find_by(message_id: tweet.id) break if article ActiveRecord::Base.clear_all_connections! ActiveRecord::Base.connection.query_cache.clear sleep 10 - } + end assert(article, "article from customer with text '#{text}' message_id '#{tweet.id}' created") assert_equal(customer_login, article.from, 'ticket article from') assert_nil(article.to, 'ticket article to') diff --git a/test/integration/zendesk_import_test.rb b/test/integration/zendesk_import_test.rb index 563ed7bff..820d53178 100644 --- a/test/integration/zendesk_import_test.rb +++ b/test/integration/zendesk_import_test.rb @@ -133,9 +133,9 @@ class ZendeskImportTest < ActiveSupport::TestCase }, ] - checks.each { |check| + checks.each do |check| user = User.find(check[:id]) - check[:data].each { |key, value| + check[:data].each do |key, value| user_value = user[key] text = "user.#{key} for user_id #{check[:id]}" @@ -144,10 +144,10 @@ class ZendeskImportTest < ActiveSupport::TestCase else assert_equal(value, user_value, text) end - } + end assert_equal(check[:roles], user.roles.sort.to_a, "#{user.login} roles") assert_equal(check[:groups], user.groups_access('full').sort.to_a, "#{user.login} groups") - } + end end # check user fields @@ -223,12 +223,12 @@ class ZendeskImportTest < ActiveSupport::TestCase }, ] - checks.each { |check| + checks.each do |check| group = Group.find(check[:id]) - check[:data].each { |key, value| + check[:data].each do |key, value| assert_equal(value, group[key], "group.#{key} for group_id #{check[:id]}") - } - } + end + end end # check imported organizations @@ -255,9 +255,9 @@ class ZendeskImportTest < ActiveSupport::TestCase }, ] - checks.each { |check| + checks.each do |check| organization = Organization.find(check[:id]) - check[:data].each { |key, value| + check[:data].each do |key, value| organization_value = organization[key] text = "organization.#{key} for organization_id #{check[:id]}" @@ -266,8 +266,8 @@ class ZendeskImportTest < ActiveSupport::TestCase else assert_equal(value, organization_value, text) end - } - } + end + end end # check organization fields @@ -391,9 +391,9 @@ If you\'re reading this message in your email, click the ticket number link that # }, ] - checks.each { |check| + checks.each do |check| ticket = Ticket.find(check[:id]) - check[:data].each { |key, value| + check[:data].each do |key, value| ticket_value = ticket[key] text = "ticket.#{key} for ticket_id #{check[:id]}" @@ -402,8 +402,8 @@ If you\'re reading this message in your email, click the ticket number link that else assert_equal(value, ticket_value, text) end - } - } + end + end end test 'check article attachments' do @@ -435,20 +435,20 @@ If you\'re reading this message in your email, click the ticket number link that }, ] - checks.each { |check| + checks.each do |check| article = Ticket::Article.find_by(message_id: check[:message_id]) assert_equal(check[:data][:count], article.attachments.count, 'attachemnt count') - (1..check[:data][:count]).each { |attachment_counter| + (1..check[:data][:count]).each do |attachment_counter| attachment = article.attachments[ attachment_counter - 1 ] compare_attachment = check[:data][ attachment_counter ] assert_equal(compare_attachment[:filename], attachment.filename, 'attachment file name') assert_equal(compare_attachment[:preferences], attachment[:preferences], 'attachment preferences') - } - } + end + end end # check ticket fields diff --git a/test/test_helper.rb b/test/test_helper.rb index cd46de640..c83c0aba7 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -66,10 +66,10 @@ class ActiveSupport::TestCase Calendar.destroy_all # reset settings - Setting.all.pluck(:name).each { |name| + Setting.all.pluck(:name).each do |name| next if name == 'models_searchable' # skip setting Setting.reset(name, false) - } + end Setting.set('system_init_done', true) Setting.reload @@ -94,12 +94,12 @@ class ActiveSupport::TestCase lines.push line end count = 0 - lines.reverse.each { |line| + lines.reverse.each do |line| break if line =~ /\+\+\+\+NEW\+\+\+\+TEST\+\+\+\+/ next if line !~ /Send notification \(#{type}\)/ next if line !~ /to:\s#{recipient}/ count += 1 - } + end count end @@ -112,12 +112,12 @@ class ActiveSupport::TestCase lines.push line end count = 0 - lines.reverse.each { |line| + lines.reverse.each do |line| break if line =~ /\+\+\+\+NEW\+\+\+\+TEST\+\+\+\+/ next if line !~ /Send email to:/ next if line !~ /to:\s'#{recipient}'/ count += 1 - } + end count end diff --git a/test/unit/assets_test.rb b/test/unit/assets_test.rb index 6e30b9007..84d098dae 100644 --- a/test/unit/assets_test.rb +++ b/test/unit/assets_test.rb @@ -278,14 +278,14 @@ class AssetsTest < ActiveSupport::TestCase def diff(o1, o2) return true if o1 == o2 - %w(updated_at created_at).each { |item| + %w(updated_at created_at).each do |item| if o1[item] o1[item] = o1[item].to_s end if o2[item] o2[item] = o2[item].to_s end - } + end return true if (o1.to_a - o2.to_a).empty? #puts "ERROR: difference \n1: #{o1.inspect}\n2: #{o2.inspect}\ndiff: #{(o1.to_a - o2.to_a).inspect}" false diff --git a/test/unit/auth_test.rb b/test/unit/auth_test.rb index ffcd46e8d..f982e4e6e 100644 --- a/test/unit/auth_test.rb +++ b/test/unit/auth_test.rb @@ -62,21 +62,21 @@ class AuthTest < ActiveSupport::TestCase }, ] - tests.each { |test| + tests.each do |test| user = User.authenticate(test[:username], test[:password]) if test[:result] == true if !user assert(false, 'auth failed') else - test[:verify].each { |key, value| + test[:verify].each do |key, value| assert_equal(user[key], value, 'verify') - } + end end elsif test[:result].nil? assert_nil(user, 'failed or not existing') else assert_equal(test[:result], user, 'failed or not existing') end - } + end end end diff --git a/test/unit/email_build_test.rb b/test/unit/email_build_test.rb index 8d161ea5b..c293bcd98 100644 --- a/test/unit/email_build_test.rb +++ b/test/unit/email_build_test.rb @@ -74,7 +74,7 @@ class EmailBuildTest < ActiveSupport::TestCase # check attachments if data[:attachments] - data[:attachments].each { |attachment| + data[:attachments].each do |attachment| if attachment[:filename] == 'message.html' assert_nil(attachment[:preferences]['Content-ID']) assert_equal(true, attachment[:preferences]['content-alternative']) @@ -88,7 +88,7 @@ class EmailBuildTest < ActiveSupport::TestCase else assert(false, "invalid attachment, should not be there, #{attachment.inspect}") end - } + end end end @@ -128,7 +128,7 @@ class EmailBuildTest < ActiveSupport::TestCase # check attachments if data[:attachments] - data[:attachments].each { |attachment| + data[:attachments].each do |attachment| if attachment[:filename] == 'somename.png' assert_nil(attachment[:preferences]['Content-ID']) assert_nil(attachment[:preferences]['content-alternative']) @@ -137,7 +137,7 @@ class EmailBuildTest < ActiveSupport::TestCase else assert(false, "invalid attachment, should not be there, #{attachment.inspect}") end - } + end end end diff --git a/test/unit/history_test.rb b/test/unit/history_test.rb index b3ab587d1..afb276786 100644 --- a/test/unit/history_test.rb +++ b/test/unit/history_test.rb @@ -148,7 +148,7 @@ class HistoryTest < ActiveSupport::TestCase }, ] tickets = [] - tests.each { |test| + tests.each do |test| ticket = nil article = nil @@ -182,7 +182,7 @@ class HistoryTest < ActiveSupport::TestCase # check history history_check(ticket.history_get, test[:history_check]) - } + end # delete tickets tickets.each(&:destroy!) @@ -248,7 +248,7 @@ class HistoryTest < ActiveSupport::TestCase ] users = [] - tests.each { |test| + tests.each do |test| user = nil @@ -269,7 +269,7 @@ class HistoryTest < ActiveSupport::TestCase # check history history_check(user.history_get, test[:history_check]) - } + end # delete user users.each(&:destroy!) @@ -312,7 +312,7 @@ class HistoryTest < ActiveSupport::TestCase }, ] organizations = [] - tests.each { |test| + tests.each do |test| organization = nil @@ -332,16 +332,16 @@ class HistoryTest < ActiveSupport::TestCase # check history history_check(organization.history_get, test[:history_check]) - } + end # delete user organizations.each(&:destroy!) end def history_check(history_list, history_check) - history_check.each { |check_item| + history_check.each do |check_item| match = false - history_list.each { |history_item| + history_list.each do |history_item| next if match next if history_item['object'] != check_item[:history_object] next if history_item['type'] != check_item[:history_type] @@ -367,13 +367,13 @@ class HistoryTest < ActiveSupport::TestCase if check_item[:id_to] assert_equal(check_item[:id_to], history_item['id_to'], "check history :id_to #{history_item['id_to']} ok") end - } + end if check_item[:result] assert(match, "history check not matched! #{check_item.inspect}") else assert_not(match, "history check matched but should not! #{check_item.inspect}") end - } + end end end diff --git a/test/unit/model_test.rb b/test/unit/model_test.rb index c86389560..b7c0d7777 100644 --- a/test/unit/model_test.rb +++ b/test/unit/model_test.rb @@ -11,7 +11,7 @@ class ModelTest < ActiveSupport::TestCase updated_by_id: 1, created_by_id: 1, ) - assert_raises( ActiveRecord::RecordNotUnique ) { + assert_raises( ActiveRecord::RecordNotUnique ) do Group.create_if_not_exists( name: 'model1-Create_If_Not_Exists', active: true, @@ -19,7 +19,7 @@ class ModelTest < ActiveSupport::TestCase updated_by_id: 1, created_by_id: 1, ) - } + end group2 = Group.create_if_not_exists( name: 'model1-create_if_not_exists', @@ -40,7 +40,7 @@ class ModelTest < ActiveSupport::TestCase updated_by_id: 1, created_by_id: 1, ) - assert_raises( ActiveRecord::RecordNotUnique ) { + assert_raises( ActiveRecord::RecordNotUnique ) do Group.create_or_update( name: 'model1-Create_Or_Update', active: true, @@ -48,7 +48,7 @@ class ModelTest < ActiveSupport::TestCase updated_by_id: 1, created_by_id: 1, ) - } + end group2 = Group.create_or_update( name: 'model1-create_or_update', diff --git a/test/unit/object_create_update_with_ref_name_test.rb b/test/unit/object_create_update_with_ref_name_test.rb index 1438bf68c..f79557371 100644 --- a/test/unit/object_create_update_with_ref_name_test.rb +++ b/test/unit/object_create_update_with_ref_name_test.rb @@ -62,7 +62,7 @@ class ObjectCreateUpdateWithRefNameTest < ActiveSupport::TestCase assert(org3.member_ids.sort.include?(user2.id)) assert_not_equal(org2.id, org3.id) - assert_raises( ActiveRecord::AssociationTypeMismatch ) { + assert_raises( ActiveRecord::AssociationTypeMismatch ) do Organization.create_or_update_with_ref( name: 'some org update_with_ref member2', members: ['object_ref_name2@example.org'], @@ -70,7 +70,7 @@ class ObjectCreateUpdateWithRefNameTest < ActiveSupport::TestCase updated_by_id: 1, created_by_id: 1, ) - } + end end diff --git a/test/unit/object_manager_test.rb b/test/unit/object_manager_test.rb index 4ae4d918a..177be2eba 100644 --- a/test/unit/object_manager_test.rb +++ b/test/unit/object_manager_test.rb @@ -73,7 +73,7 @@ class ObjectManagerTest < ActiveSupport::TestCase assert_not(attribute1) # create invalid attributes - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do attribute2 = ObjectManager::Attribute.add( object: 'Ticket', name: 'test2_id', @@ -90,8 +90,8 @@ class ObjectManagerTest < ActiveSupport::TestCase created_by_id: 1, updated_by_id: 1, ) - } - assert_raises(RuntimeError) { + end + assert_raises(RuntimeError) do attribute3 = ObjectManager::Attribute.add( object: 'Ticket', name: 'test3_ids', @@ -108,8 +108,8 @@ class ObjectManagerTest < ActiveSupport::TestCase created_by_id: 1, updated_by_id: 1, ) - } - assert_raises(RuntimeError) { + end + assert_raises(RuntimeError) do attribute4 = ObjectManager::Attribute.add( object: 'Ticket', name: 'test4', @@ -125,7 +125,7 @@ class ObjectManagerTest < ActiveSupport::TestCase created_by_id: 1, updated_by_id: 1, ) - } + end attribute5 = ObjectManager::Attribute.add( object: 'Ticket', @@ -153,7 +153,7 @@ class ObjectManagerTest < ActiveSupport::TestCase name: 'test5', ) - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do attribute6 = ObjectManager::Attribute.add( object: 'Ticket', name: 'test6', @@ -172,7 +172,7 @@ class ObjectManagerTest < ActiveSupport::TestCase created_by_id: 1, updated_by_id: 1, ) - } + end attribute7 = ObjectManager::Attribute.add( object: 'Ticket', @@ -200,7 +200,7 @@ class ObjectManagerTest < ActiveSupport::TestCase name: 'test7', ) - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do attribute8 = ObjectManager::Attribute.add( object: 'Ticket', name: 'test8', @@ -216,7 +216,7 @@ class ObjectManagerTest < ActiveSupport::TestCase created_by_id: 1, updated_by_id: 1, ) - } + end attribute9 = ObjectManager::Attribute.add( object: 'Ticket', @@ -242,7 +242,7 @@ class ObjectManagerTest < ActiveSupport::TestCase name: 'test9', ) - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do attribute10 = ObjectManager::Attribute.add( object: 'Ticket', name: 'test10', @@ -259,7 +259,7 @@ class ObjectManagerTest < ActiveSupport::TestCase created_by_id: 1, updated_by_id: 1, ) - } + end attribute11 = ObjectManager::Attribute.add( object: 'Ticket', @@ -285,7 +285,7 @@ class ObjectManagerTest < ActiveSupport::TestCase name: 'test11', ) - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do attribute12 = ObjectManager::Attribute.add( object: 'Ticket', name: 'test12', @@ -302,10 +302,10 @@ class ObjectManagerTest < ActiveSupport::TestCase created_by_id: 1, updated_by_id: 1, ) - } + end assert_equal(false, ObjectManager::Attribute.pending_migration?) - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do attribute13 = ObjectManager::Attribute.add( object: 'Ticket', name: 'test13|', @@ -323,10 +323,10 @@ class ObjectManagerTest < ActiveSupport::TestCase created_by_id: 1, updated_by_id: 1, ) - } + end assert_equal(false, ObjectManager::Attribute.pending_migration?) - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do attribute14 = ObjectManager::Attribute.add( object: 'Ticket', name: 'test14!', @@ -344,10 +344,10 @@ class ObjectManagerTest < ActiveSupport::TestCase created_by_id: 1, updated_by_id: 1, ) - } + end assert_equal(false, ObjectManager::Attribute.pending_migration?) - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do attribute15 = ObjectManager::Attribute.add( object: 'Ticket', name: 'test15ä', @@ -365,10 +365,10 @@ class ObjectManagerTest < ActiveSupport::TestCase created_by_id: 1, updated_by_id: 1, ) - } + end assert_equal(false, ObjectManager::Attribute.pending_migration?) - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do attribute16 = ObjectManager::Attribute.add( object: 'Ticket', name: 'test16', @@ -385,10 +385,10 @@ class ObjectManagerTest < ActiveSupport::TestCase created_by_id: 1, updated_by_id: 1, ) - } + end assert_equal(false, ObjectManager::Attribute.pending_migration?) - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do attribute17 = ObjectManager::Attribute.add( object: 'Ticket', name: 'test17', @@ -404,10 +404,10 @@ class ObjectManagerTest < ActiveSupport::TestCase created_by_id: 1, updated_by_id: 1, ) - } + end assert_equal(false, ObjectManager::Attribute.pending_migration?) - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do attribute18 = ObjectManager::Attribute.add( object: 'Ticket', name: 'delete', @@ -424,7 +424,7 @@ class ObjectManagerTest < ActiveSupport::TestCase created_by_id: 1, updated_by_id: 1, ) - } + end assert_equal(false, ObjectManager::Attribute.pending_migration?) end diff --git a/test/unit/online_notifiaction_test.rb b/test/unit/online_notifiaction_test.rb index 8c2710266..a50354f11 100644 --- a/test/unit/online_notifiaction_test.rb +++ b/test/unit/online_notifiaction_test.rb @@ -355,7 +355,7 @@ class OnlineNotificationTest < ActiveSupport::TestCase assert(!OnlineNotification.all_seen?('Ticket', tickets[1].id), 'no notifications for master ticket available') # delete tickets - tickets.each { |ticket| + tickets.each do |ticket| ticket_id = ticket.id ticket.destroy found = Ticket.find_by(id: ticket_id) @@ -365,7 +365,7 @@ class OnlineNotificationTest < ActiveSupport::TestCase Scheduler.worker(true) notifications = OnlineNotification.list_by_object('Ticket', ticket_id) assert(notifications.empty?, 'still notifications for destroyed ticket available') - } + end end test 'ticket notification item check' do diff --git a/test/unit/organization_ref_object_touch_test.rb b/test/unit/organization_ref_object_touch_test.rb index 59e3c83e6..f6095fd98 100644 --- a/test/unit/organization_ref_object_touch_test.rb +++ b/test/unit/organization_ref_object_touch_test.rb @@ -176,7 +176,7 @@ class OrganizationRefObjectTouchTest < ActiveSupport::TestCase updated_by_id: 1, created_by_id: 1, ) - (1..100).each { |count| + (1..100).each do |count| User.create_or_update( login: "organization-ref-object-update-customer3-#{count}@example.com", firstname: 'Notification', @@ -190,7 +190,7 @@ class OrganizationRefObjectTouchTest < ActiveSupport::TestCase updated_by_id: 1, created_by_id: 1, ) - } + end ticket = Ticket.create!( title: "some title1\n äöüß", diff --git a/test/unit/package_test.rb b/test/unit/package_test.rb index 4ba9d4d59..dfec3e3f2 100644 --- a/test/unit/package_test.rb +++ b/test/unit/package_test.rb @@ -301,7 +301,7 @@ class PackageTest < ActiveSupport::TestCase }, ] - tests.each { |test| + tests.each do |test| if test[:action] == 'install' begin package = Package.install(string: test[:zpm]) @@ -373,15 +373,15 @@ class PackageTest < ActiveSupport::TestCase next if !test[:verify] next if !test[:verify][:check_files] - test[:verify][:check_files].each { |item| + test[:verify][:check_files].each do |item| exists = File.exist?(item[:location]) if item[:result] assert(exists, "'#{item[:location]}' exists" ) else assert(!exists, "'#{item[:location]}' doesn't exists" ) end - } - } + end + end end end diff --git a/test/unit/role_test.rb b/test/unit/role_test.rb index 27494690f..65dedd62c 100644 --- a/test/unit/role_test.rb +++ b/test/unit/role_test.rb @@ -31,7 +31,7 @@ class RoleTest < ActiveSupport::TestCase preferences: {}, ) - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do Role.create( name: 'Test1', note: 'Test1 Role.', @@ -39,8 +39,8 @@ class RoleTest < ActiveSupport::TestCase updated_by_id: 1, created_by_id: 1 ) - } - assert_raises(RuntimeError) { + end + assert_raises(RuntimeError) do Role.create( name: 'Test1', note: 'Test1 Role.', @@ -48,8 +48,8 @@ class RoleTest < ActiveSupport::TestCase updated_by_id: 1, created_by_id: 1 ) - } - assert_raises(RuntimeError) { + end + assert_raises(RuntimeError) do Role.create( name: 'Test1', note: 'Test1 Role.', @@ -57,7 +57,7 @@ class RoleTest < ActiveSupport::TestCase updated_by_id: 1, created_by_id: 1 ) - } + end role11 = Role.create( name: 'Test1.1', note: 'Test1.1 Role.', diff --git a/test/unit/role_validate_agent_limit_test.rb b/test/unit/role_validate_agent_limit_test.rb index fef223564..f3505a594 100644 --- a/test/unit/role_validate_agent_limit_test.rb +++ b/test/unit/role_validate_agent_limit_test.rb @@ -48,9 +48,9 @@ class RoleValidateAgentLimit < ActiveSupport::TestCase ) role_agent_limit_success.permissions = permission_ticket_agent - assert_raises(Exceptions::UnprocessableEntity) { + assert_raises(Exceptions::UnprocessableEntity) do role_agent_limit_fail.permissions = permission_ticket_agent - } + end user1.destroy user2.destroy diff --git a/test/unit/session_collections_test.rb b/test/unit/session_collections_test.rb index 2b5691909..621531b4c 100644 --- a/test/unit/session_collections_test.rb +++ b/test/unit/session_collections_test.rb @@ -136,7 +136,7 @@ class SessionCollectionsTest < ActiveSupport::TestCase end def check_if_collection_exists(results, collection, attributes = nil) - results.each { |result| + results.each do |result| next if !result next if !result[:collection] next if !result[:collection][collection] @@ -145,9 +145,9 @@ class SessionCollectionsTest < ActiveSupport::TestCase return true if !attributes # check if objetc with attributes in collection exists - result[:collection][collection].each { |item| + result[:collection][collection].each do |item| match_all = true - attributes.each { |key, value| + attributes.each do |key, value| # sort array, database result maybe unsorted item_attributes = item[ key.to_s ] @@ -163,10 +163,10 @@ class SessionCollectionsTest < ActiveSupport::TestCase #p "FAILED: #{key} -> #{item_attributes.inspect} vs. #{value.inspect}" match_all = false end - } + end return true if match_all - } - } + end + end nil end diff --git a/test/unit/session_enhanced_test.rb b/test/unit/session_enhanced_test.rb index 0c3303003..3029c5589 100644 --- a/test/unit/session_enhanced_test.rb +++ b/test/unit/session_enhanced_test.rb @@ -139,9 +139,9 @@ class SessionEnhancedTest < ActiveSupport::TestCase assert_equal(messages.count, 0, 'messages count') # start jobs - jobs = Thread.new { + jobs = Thread.new do Sessions.jobs - } + end sleep 6 # check client threads @@ -231,9 +231,9 @@ class SessionEnhancedTest < ActiveSupport::TestCase Sessions.destroy(client_id3) # start jobs - jobs = Thread.new { + jobs = Thread.new do Sessions.jobs - } + end sleep 5 Sessions.create(client_id1_0, agent1.attributes, { type: 'websocket' }) sleep 6.5 @@ -323,25 +323,25 @@ class SessionEnhancedTest < ActiveSupport::TestCase #puts "cid: #{client_id}" #puts "m: #{messages.inspect}" collections_result = {} - messages.each { |message| + messages.each do |message| #puts "" #puts "message: #{message.inspect}" next if message['event'] != 'resetCollection' #puts "rc: " next if !message['data'] - message['data'].each { |key, _value| + message['data'].each do |key, _value| #puts "rc: #{key}" collections_result[key] = true - } - } + end + end #puts "c: #{collections_result.inspect}" - collections_orig.each { |key, _value| + collections_orig.each do |key, _value| if collections_orig[key].nil? assert_nil(collections_result[key], "collection message for #{key} #{type}-check (client_id #{client_id})") else assert_equal(collections_orig[key], collections_result[key], "collection message for #{key} #{type}-check (client_id #{client_id})") end - } + end end end diff --git a/test/unit/store_test.rb b/test/unit/store_test.rb index cc49f5f17..1213768f2 100644 --- a/test/unit/store_test.rb +++ b/test/unit/store_test.rb @@ -53,7 +53,7 @@ class StoreTest < ActiveSupport::TestCase }, ] - files.each { |file| + files.each do |file| sha = Digest::SHA256.hexdigest( file[:data] ) # add attachments @@ -83,14 +83,14 @@ class StoreTest < ActiveSupport::TestCase # provider check assert_equal( 'DB', attachments[0].provider ) - } + end success = Store::File.verify assert success, 'verify ok' Store::File.move( 'DB', 'File' ) - files.each { |file| + files.each do |file| sha = Digest::SHA256.hexdigest( file[:data] ) # get list of attachments @@ -109,14 +109,14 @@ class StoreTest < ActiveSupport::TestCase # provider check assert_equal( 'File', attachments[0].provider ) - } + end success = Store::File.verify assert success, 'verify ok' Store::File.move( 'File', 'DB' ) - files.each { |file| + files.each do |file| sha = Digest::SHA256.hexdigest( file[:data] ) # get list of attachments @@ -149,6 +149,6 @@ class StoreTest < ActiveSupport::TestCase o_id: file[:o_id], ) assert !attachments[0] - } + end end end diff --git a/test/unit/tag_test.rb b/test/unit/tag_test.rb index a193b1092..c54ce4416 100644 --- a/test/unit/tag_test.rb +++ b/test/unit/tag_test.rb @@ -128,7 +128,7 @@ class TagTest < ActiveSupport::TestCase }, ] - tests.each { |test| + tests.each do |test| tags = nil if test[:tag_add] tags = test[:tag_add] @@ -140,17 +140,17 @@ class TagTest < ActiveSupport::TestCase assert(success, 'Tag.tag_remove successful') end list = Tag.tag_list(tags) - test[:verify][:items].each { |key, value| + test[:verify][:items].each do |key, value| if value == true assert(list.include?(key), "Tag verify - should exists but exists #{key}") else assert(!list.include?(key), "Tag verify - exists but should not #{key}") end - } - } + end + end # delete tags - tests.each { |test| + tests.each do |test| tags = nil tags = if test[:tag_add] test[:tag_add] @@ -161,7 +161,7 @@ class TagTest < ActiveSupport::TestCase assert(success, 'Tag.tag_remove successful') list = Tag.tag_list(tags) assert(!list.include?(tags[:item]), 'Tag entry destroyed') - } + end end test 'tags - real live' do diff --git a/test/unit/ticket_test.rb b/test/unit/ticket_test.rb index dcb2d9f9b..549d7130e 100644 --- a/test/unit/ticket_test.rb +++ b/test/unit/ticket_test.rb @@ -262,10 +262,10 @@ class TicketTest < ActiveSupport::TestCase test 'ticket process_pending' do # close all other pending close tickets first - Ticket.where('pending_time IS NOT NULL').each { |ticket| + Ticket.where('pending_time IS NOT NULL').each do |ticket| ticket.state = Ticket::State.lookup(name: 'closed') ticket.save! - } + end ticket = Ticket.create( title: 'pending close test', diff --git a/test/unit/ticket_trigger_test.rb b/test/unit/ticket_trigger_test.rb index 2310efbd8..686827c6c 100644 --- a/test/unit/ticket_trigger_test.rb +++ b/test/unit/ticket_trigger_test.rb @@ -2669,7 +2669,7 @@ class TicketTriggerTest < ActiveSupport::TestCase end test '1 empty condition should not create errors' do - assert_raises(Exception) { + assert_raises(Exception) do trigger_empty = Trigger.create_or_update( name: 'aaa loop check', condition: { @@ -2690,7 +2690,7 @@ class TicketTriggerTest < ActiveSupport::TestCase created_by_id: 1, updated_by_id: 1, ) - } + end end test 'article_last_sender trigger -> reply_to' do diff --git a/test/unit/user_out_of_office_test.rb b/test/unit/user_out_of_office_test.rb index 1d573bd89..07cc65e02 100644 --- a/test/unit/user_out_of_office_test.rb +++ b/test/unit/user_out_of_office_test.rb @@ -49,33 +49,33 @@ class UserOutOfOfficeTest < ActiveSupport::TestCase assert_not(@agent2.out_of_office?) assert_not(@agent3.out_of_office?) - assert_raises(Exceptions::UnprocessableEntity) { + assert_raises(Exceptions::UnprocessableEntity) do @agent1.out_of_office = true @agent1.out_of_office_start_at = Time.zone.now + 2.days @agent1.out_of_office_end_at = Time.zone.now @agent1.save! - } + end - assert_raises(Exceptions::UnprocessableEntity) { + assert_raises(Exceptions::UnprocessableEntity) do @agent1.out_of_office = true @agent1.out_of_office_start_at = Time.zone.now @agent1.out_of_office_end_at = Time.zone.now - 2.days @agent1.save! - } + end - assert_raises(Exceptions::UnprocessableEntity) { + assert_raises(Exceptions::UnprocessableEntity) do @agent1.out_of_office = true @agent1.out_of_office_start_at = nil @agent1.out_of_office_end_at = Time.zone.now @agent1.save! - } + end - assert_raises(Exceptions::UnprocessableEntity) { + assert_raises(Exceptions::UnprocessableEntity) do @agent1.out_of_office = true @agent1.out_of_office_start_at = Time.zone.now @agent1.out_of_office_end_at = nil @agent1.save! - } + end @agent1.out_of_office = false @agent1.out_of_office_start_at = Time.zone.now + 2.days @@ -84,16 +84,16 @@ class UserOutOfOfficeTest < ActiveSupport::TestCase assert_not(@agent1.out_of_office?) - assert_raises(Exceptions::UnprocessableEntity) { + assert_raises(Exceptions::UnprocessableEntity) do @agent1.out_of_office = true @agent1.out_of_office_start_at = Time.zone.now + 2.days @agent1.out_of_office_end_at = Time.zone.now + 4.days @agent1.save! - } - assert_raises(Exceptions::UnprocessableEntity) { + end + assert_raises(Exceptions::UnprocessableEntity) do @agent1.out_of_office_replacement_id = 999_999_999_999 # not existing @agent1.save! - } + end @agent1.out_of_office_replacement_id = @agent2.id @agent1.save! diff --git a/test/unit/user_ref_object_touch_test.rb b/test/unit/user_ref_object_touch_test.rb index f4d949c04..3060cb474 100644 --- a/test/unit/user_ref_object_touch_test.rb +++ b/test/unit/user_ref_object_touch_test.rb @@ -164,7 +164,7 @@ class UserRefObjectTouchTest < ActiveSupport::TestCase created_by_id: 1, ) - (1..100).each { |count| + (1..100).each do |count| User.create_or_update( login: "user-ref-object-update-customer3-#{count}@example.com", firstname: 'Notification', @@ -178,7 +178,7 @@ class UserRefObjectTouchTest < ActiveSupport::TestCase updated_by_id: 1, created_by_id: 1, ) - } + end ticket = Ticket.create( title: "some title1\n äöüß", diff --git a/test/unit/user_test.rb b/test/unit/user_test.rb index 1dcdae943..c541aac87 100644 --- a/test/unit/user_test.rb +++ b/test/unit/user_test.rb @@ -242,7 +242,7 @@ class UserTest < ActiveSupport::TestCase }, ] - tests.each { |test| + tests.each do |test| # check if user exists user = User.where(login: test[:create][:login]).first @@ -252,7 +252,7 @@ class UserTest < ActiveSupport::TestCase user = User.create( test[:create] ) - test[:create_verify].each { |key, value| + test[:create_verify].each do |key, value| next if key == :image_md5 if user.respond_to?(key) result = user.send(key) @@ -264,7 +264,7 @@ class UserTest < ActiveSupport::TestCase else assert_equal(value, user[key], "create check #{key} in (#{test[:name]})") end - } + end if test[:create_verify][:image_md5] file = Avatar.get_by_hash(user.image) file_md5 = Digest::MD5.hexdigest(file.content) @@ -273,14 +273,14 @@ class UserTest < ActiveSupport::TestCase if test[:update] user.update!( test[:update] ) - test[:update_verify].each { |key, value| + test[:update_verify].each do |key, value| next if key == :image_md5 if user.respond_to?(key) assert_equal(value, user.send(key), "update check #{key} in (#{test[:name]})") else assert_equal(value, user[key], "update check #{key} in (#{test[:name]})") end - } + end if test[:update_verify][:image_md5] file = Avatar.get_by_hash( user.image ) @@ -290,7 +290,7 @@ class UserTest < ActiveSupport::TestCase end user.destroy! - } + end end test 'without email - but login eq email' do @@ -387,7 +387,7 @@ class UserTest < ActiveSupport::TestCase assert(admin1.id) assert_equal(admin1.email, email1) - assert_raises(Exceptions::UnprocessableEntity) { + assert_raises(Exceptions::UnprocessableEntity) do User.create!( login: "#{email1}-1", firstname: 'Role', @@ -399,7 +399,7 @@ class UserTest < ActiveSupport::TestCase updated_by_id: 1, created_by_id: 1, ) - } + end email2 = "admin2-role_without_email#{name}@example.com" admin2 = User.create!( @@ -413,10 +413,10 @@ class UserTest < ActiveSupport::TestCase created_by_id: 1, ) - assert_raises(Exceptions::UnprocessableEntity) { + assert_raises(Exceptions::UnprocessableEntity) do admin2.email = email1 admin2.save! - } + end admin1.email = admin1.email admin1.save! @@ -632,7 +632,7 @@ class UserTest < ActiveSupport::TestCase updated_by_id: 1, ) name = rand(999_999_999) - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do User.create_or_update( login: "customer-role#{name}@example.com", firstname: 'Role', @@ -644,8 +644,8 @@ class UserTest < ActiveSupport::TestCase updated_by_id: 1, created_by_id: 1, ) - } - assert_raises(RuntimeError) { + end + assert_raises(RuntimeError) do User.create_or_update( login: "customer-role#{name}@example.com", firstname: 'Role', @@ -657,7 +657,7 @@ class UserTest < ActiveSupport::TestCase updated_by_id: 1, created_by_id: 1, ) - } + end user1 = User.create_or_update( login: "customer-role#{name}@example.com", firstname: 'Role', @@ -688,7 +688,7 @@ class UserTest < ActiveSupport::TestCase assert_not(user1.role_ids.include?(test_role_2.id)) assert_not(user1.role_ids.include?(test_role_3.id)) assert(user1.role_ids.include?(test_role_4.id)) - assert_raises(RuntimeError) { + assert_raises(RuntimeError) do User.create_or_update( login: "customer-role#{name}@example.com", firstname: 'Role', @@ -700,8 +700,8 @@ class UserTest < ActiveSupport::TestCase updated_by_id: 1, created_by_id: 1, ) - } - assert_raises(RuntimeError) { + end + assert_raises(RuntimeError) do User.create_or_update( login: "customer-role#{name}@example.com", firstname: 'Role', @@ -713,7 +713,7 @@ class UserTest < ActiveSupport::TestCase updated_by_id: 1, created_by_id: 1, ) - } + end assert(user1.role_ids.include?(test_role_1.id)) assert_not(user1.role_ids.include?(test_role_2.id)) assert_not(user1.role_ids.include?(test_role_3.id)) @@ -858,9 +858,9 @@ class UserTest < ActiveSupport::TestCase admin_count_inital = User.with_permissions('admin').count assert_equal(1, admin_count_inital) - assert_raises(Exceptions::UnprocessableEntity) { + assert_raises(Exceptions::UnprocessableEntity) do admin3.update!(roles: Role.where(name: %w(Agent))) - } + end admin_count_inital = User.with_permissions('admin').count assert_equal(1, admin_count_inital) diff --git a/test/unit/user_validate_agent_limit_test.rb b/test/unit/user_validate_agent_limit_test.rb index a28f147ff..88860ed4b 100644 --- a/test/unit/user_validate_agent_limit_test.rb +++ b/test/unit/user_validate_agent_limit_test.rb @@ -25,7 +25,7 @@ class UserValidateAgentLimit < ActiveSupport::TestCase roles: [role_agent], ) - assert_raises(Exceptions::UnprocessableEntity) { + assert_raises(Exceptions::UnprocessableEntity) do user3 = User.create( firstname: 'Firstname2', lastname: 'Lastname2', @@ -33,7 +33,7 @@ class UserValidateAgentLimit < ActiveSupport::TestCase login: 'some-agentlimit-2@example.com', roles: [role_agent], ) - } + end user3 = User.create( firstname: 'Firstname2', @@ -43,9 +43,9 @@ class UserValidateAgentLimit < ActiveSupport::TestCase roles: [role_customer], ) - assert_raises(Exceptions::UnprocessableEntity) { + assert_raises(Exceptions::UnprocessableEntity) do user3.roles = [role_agent] - } + end user1.destroy user2.destroy From 4e8bc9564ec596247381ff358d3ac715da240fc4 Mon Sep 17 00:00:00 2001 From: Thorsten Eckel Date: Sun, 1 Oct 2017 14:31:29 +0200 Subject: [PATCH 2/3] Follow up: Applied RuboCop Style/BlockDelimiters to improve readability. --- ...0001_fixed_twitter_ticket_article_preferences4.rb | 12 ++++++------ lib/tasks/search_index_es.rake | 4 ++-- lib/tasks/test_browser.rake | 4 ++-- spec/lib/ldap_spec.rb | 4 ++-- test/unit/ticket_article_dos_test.rb | 4 ++-- 5 files changed, 14 insertions(+), 14 deletions(-) diff --git a/db/migrate/20170908000001_fixed_twitter_ticket_article_preferences4.rb b/db/migrate/20170908000001_fixed_twitter_ticket_article_preferences4.rb index 9b97fb7cd..76e07c07d 100644 --- a/db/migrate/20170908000001_fixed_twitter_ticket_article_preferences4.rb +++ b/db/migrate/20170908000001_fixed_twitter_ticket_article_preferences4.rb @@ -7,13 +7,13 @@ class FixedTwitterTicketArticlePreferences4 < ActiveRecord::Migration[5.0] # find article preferences with Twitter::NullObject and replace it with nill to prevent elasticsearch index issue article_type_ids = Ticket::Article::Type.where(name: ['twitter status', 'twitter direct-message']).pluck(:id) article_ids = Ticket::Article.where(type_id: article_type_ids).pluck(:id) - article_ids.each { |article_id| + article_ids.each do |article_id| article = Ticket::Article.find(article_id) next if !article.preferences changed = false - article.preferences.each { |_key, value| + article.preferences.each do |_key, value| next if value.class != ActiveSupport::HashWithIndifferentAccess - value.each { |sub_key, sub_level| + value.each do |sub_key, sub_level| if sub_level.class == NilClass value[sub_key] = nil next @@ -26,11 +26,11 @@ class FixedTwitterTicketArticlePreferences4 < ActiveRecord::Migration[5.0] next if sub_level.class != Twitter::NullObject value[sub_key] = nil changed = true - } - } + end + end next if !changed article.save! - } + end end end diff --git a/lib/tasks/search_index_es.rake b/lib/tasks/search_index_es.rake index 5a1b47e5a..c24416669 100644 --- a/lib/tasks/search_index_es.rake +++ b/lib/tasks/search_index_es.rake @@ -43,14 +43,14 @@ namespace :searchindex do task :reload, [:opts] => :environment do |_t, _args| puts 'reload data...' - Models.searchable.each { |model_class| + Models.searchable.each do |model_class| puts " reload #{model_class}" started_at = Time.zone.now puts " - started at #{started_at}" model_class.search_index_reload took = Time.zone.now - started_at puts " - took #{took.to_i} seconds" - } + end end diff --git a/lib/tasks/test_browser.rake b/lib/tasks/test_browser.rake index 2bc8d1a87..d6c280484 100644 --- a/lib/tasks/test_browser.rake +++ b/lib/tasks/test_browser.rake @@ -9,11 +9,11 @@ namespace :test do if !args.opts args.opts = '' end - Dir.glob('test/browser/*_test.rb').sort.each { |r| + Dir.glob('test/browser/*_test.rb').sort.each do |r| sh "#{args.opts} ruby -Itest #{r}" do |ok, res| raise 'Failed test. ' + res.inspect if !ok end - } + end puts 'All browser tests, elapsed: ' + (Time.zone.now - start).to_s + ' seconds' end diff --git a/spec/lib/ldap_spec.rb b/spec/lib/ldap_spec.rb index bd43e70d3..a7d719804 100644 --- a/spec/lib/ldap_spec.rb +++ b/spec/lib/ldap_spec.rb @@ -206,13 +206,13 @@ RSpec.describe Ldap do # expectations and reuse it in 'let' instance # as return param of Net::LDAP.new let(:mocked_ldap) { double(bind: true) } - let(:instance) { + let(:instance) do expect(Net::LDAP).to receive(:new).and_return(mocked_ldap) described_class.new( host: 'localhost', port: 1337, ) - } + end context '#preferences' do diff --git a/test/unit/ticket_article_dos_test.rb b/test/unit/ticket_article_dos_test.rb index cd75dd747..1891bcb5b 100644 --- a/test/unit/ticket_article_dos_test.rb +++ b/test/unit/ticket_article_dos_test.rb @@ -72,7 +72,7 @@ class TicketArticleDos < ActiveSupport::TestCase created_by_id: 1, ) - assert_raises(Exceptions::UnprocessableEntity) { + assert_raises(Exceptions::UnprocessableEntity) do article3 = Ticket::Article.create!( ticket_id: ticket3.id, type_id: Ticket::Article::Type.find_by(name: 'phone').id, @@ -83,7 +83,7 @@ class TicketArticleDos < ActiveSupport::TestCase updated_by_id: 1, created_by_id: 1, ) - } + end end From 5fa34aa559edb40bbab0880d74083a31486a8839 Mon Sep 17 00:00:00 2001 From: Martin Edenhofer Date: Mon, 2 Oct 2017 13:23:14 +0200 Subject: [PATCH 3/3] Fixed issue #1406 - Channel: Twitter streaming is complaining about. --- app/models/channel.rb | 53 ++++++++++++++++-------- app/models/channel/driver/facebook.rb | 14 +++++++ app/models/channel/driver/pop3.rb | 16 ++++++- app/models/channel/driver/telegram.rb | 14 +++++++ app/models/channel/driver/twitter.rb | 16 ++++++- lib/sessions/backend/collections/base.rb | 10 ++--- 6 files changed, 99 insertions(+), 24 deletions(-) diff --git a/app/models/channel.rb b/app/models/channel.rb index 00a872600..6b55defd8 100644 --- a/app/models/channel.rb +++ b/app/models/channel.rb @@ -15,6 +15,7 @@ class Channel < ApplicationModel # rubocop:disable Style/ClassVars @@channel_stream = {} + @@channel_stream_started_till_at = {} # rubocop:enable Style/ClassVars =begin @@ -63,7 +64,7 @@ fetch one account self.status_in = result[:result] self.last_log_in = result[:notice] preferences[:last_fetch] = Time.zone.now - save + save! rescue => e error = "Can't use Channel::Driver::#{adapter.to_classname}: #{e.inspect}" logger.error error @@ -71,7 +72,7 @@ fetch one account self.status_in = 'error' self.last_log_in = error preferences[:last_fetch] = Time.zone.now - save + save! end end @@ -116,7 +117,7 @@ stream instance of account logger.error e.backtrace self.status_in = 'error' self.last_log_in = error - save + save! end end @@ -132,7 +133,7 @@ stream all accounts def self.stream Thread.abort_on_exception = true - auto_reconnect_after = 25 + auto_reconnect_after = 180 last_channels = [] loop do @@ -141,11 +142,20 @@ stream all accounts current_channels = [] channels = Channel.where('active = ? AND area LIKE ?', true, '%::Account') channels.each do |channel| - next if channel.options[:adapter] != 'twitter' + adapter = channel.options[:adapter] + driver_class = Object.const_get("Channel::Driver::#{adapter.to_classname}") + next if !driver_class.respond_to?(:streamable?) + next if !driver_class.streamable? channel_id = channel.id.to_s + + if @@channel_stream[channel_id].blank? && @@channel_stream_started_till_at[channel_id] && @@channel_stream_started_till_at[channel_id] > Time.zone.now - 65.seconds + logger.info "skipp channel (#{channel_id}) for streaming, already tried to connect or connection was active within the last minute" + next + end + current_channels.push channel_id - # exit it channel has changed or connection is older then 25 min. + # exit it channel has changed or connection is older then 180 minutes if @@channel_stream[channel_id] if @@channel_stream[channel_id][:updated_at] != channel.updated_at logger.info "channel (#{channel.id}) has changed, stop thread" @@ -153,12 +163,14 @@ stream all accounts @@channel_stream[channel_id][:thread].join @@channel_stream[channel_id][:stream_instance].disconnect @@channel_stream[channel_id] = false + @@channel_stream_started_till_at[channel_id] = Time.zone.now elsif @@channel_stream[channel_id][:started_at] && @@channel_stream[channel_id][:started_at] < Time.zone.now - auto_reconnect_after.minutes logger.info "channel (#{channel.id}) reconnect - thread is older then #{auto_reconnect_after} minutes, restart thread" @@channel_stream[channel_id][:thread].exit @@channel_stream[channel_id][:thread].join @@channel_stream[channel_id][:stream_instance].disconnect @@channel_stream[channel_id] = false + @@channel_stream_started_till_at[channel_id] = Time.zone.now end end @@ -177,19 +189,24 @@ stream all accounts @@channel_stream[channel_id][:thread] = Thread.new do begin logger.info "Started stream channel for '#{channel.id}' (#{channel.area})..." + channel.status_in = 'ok' + channel.last_log_in = '' + channel.save! + @@channel_stream_started_till_at[channel_id] = Time.zone.now @@channel_stream[channel_id] ||= {} @@channel_stream[channel_id][:stream_instance] = channel.stream_instance @@channel_stream[channel_id][:stream_instance].stream @@channel_stream[channel_id][:stream_instance].disconnect @@channel_stream[channel_id] = false - logger.info " ...stopped thread for '#{channel.id}'" + @@channel_stream_started_till_at[channel_id] = Time.zone.now + logger.info " ...stopped stream thread for '#{channel.id}'" rescue => e - error = "Can't use channel (#{channel.id}): #{e.inspect}" + error = "Can't use stream for channel (#{channel.id}): #{e.inspect}" logger.error error logger.error e.backtrace channel.status_in = 'error' channel.last_log_in = error - channel.save + channel.save! @@channel_stream[channel_id] = false end end @@ -197,14 +214,16 @@ stream all accounts # cleanup deleted channels last_channels.each do |channel_id| - next if !@@channel_stream[channel_id.to_s] + next if @@channel_stream[channel_id].blank? next if current_channels.include?(channel_id) - logger.info "channel (#{channel_id}) not longer active, stop thread" - @@channel_stream[channel_id.to_s][:thread].exit - @@channel_stream[channel_id.to_s][:thread].join - @@channel_stream[channel_id.to_s][:stream_instance].disconnect - @@channel_stream[channel_id.to_s] = false + logger.info "channel (#{channel_id}) not longer active, stop stream thread" + @@channel_stream[channel_id][:thread].exit + @@channel_stream[channel_id][:thread].join + @@channel_stream[channel_id][:stream_instance].disconnect + @@channel_stream[channel_id] = false + @@channel_stream_started_till_at[channel_id] = Time.zone.now end + last_channels = current_channels sleep 20 @@ -245,14 +264,14 @@ send via account result = driver_instance.send(adapter_options, mail_params, notification) self.status_out = 'ok' self.last_log_out = '' - save + save! rescue => e error = "Can't use Channel::Driver::#{adapter.to_classname}: #{e.inspect}" logger.error error logger.error e.backtrace self.status_out = 'error' self.last_log_out = error - save + save! raise error end result diff --git a/app/models/channel/driver/facebook.rb b/app/models/channel/driver/facebook.rb index 910595bf6..3d46638e6 100644 --- a/app/models/channel/driver/facebook.rb +++ b/app/models/channel/driver/facebook.rb @@ -63,6 +63,20 @@ class Channel::Driver::Facebook def disconnect end +=begin + + Channel::Driver::Facebook.streamable? + +returns + + true|false + +=end + + def self.streamable? + false + end + private def get_page(page_id) diff --git a/app/models/channel/driver/pop3.rb b/app/models/channel/driver/pop3.rb index a8341b6e4..4b5542709 100644 --- a/app/models/channel/driver/pop3.rb +++ b/app/models/channel/driver/pop3.rb @@ -44,7 +44,7 @@ returns =end - def fetch (options, channel, check_type = '', verify_string = '') + def fetch(options, channel, check_type = '', verify_string = '') ssl = true port = 995 if options.key?(:ssl) && options[:ssl] == false @@ -180,6 +180,20 @@ returns true end +=begin + + Channel::Driver::Pop3.streamable? + +returns + + true|false + +=end + + def self.streamable? + false + end + def disconnect return if !@pop @pop.finish diff --git a/app/models/channel/driver/telegram.rb b/app/models/channel/driver/telegram.rb index ffa24fc67..66f1eb5b5 100644 --- a/app/models/channel/driver/telegram.rb +++ b/app/models/channel/driver/telegram.rb @@ -30,6 +30,20 @@ class Channel::Driver::Telegram message end +=begin + + Channel::Driver::Telegram.streamable? + +returns + + true|false + +=end + + def self.streamable? + false + end + private def check_external_credential(options) diff --git a/app/models/channel/driver/twitter.rb b/app/models/channel/driver/twitter.rb index 2a3f60447..0780b7d2c 100644 --- a/app/models/channel/driver/twitter.rb +++ b/app/models/channel/driver/twitter.rb @@ -123,6 +123,20 @@ returns @rest_client.disconnect if @rest_client end +=begin + + Channel::Driver::Twitter.streamable? + +returns + + true|false + +=end + + def self.streamable? + true + end + =begin create stream endpoint form twitter account @@ -183,7 +197,7 @@ returns =end def stream - sleep_on_unauthorized = 61 + sleep_on_unauthorized = 65 2.times do |loop_count| begin stream_start diff --git a/lib/sessions/backend/collections/base.rb b/lib/sessions/backend/collections/base.rb index 33588df94..1b3e526a2 100644 --- a/lib/sessions/backend/collections/base.rb +++ b/lib/sessions/backend/collections/base.rb @@ -22,11 +22,6 @@ class Sessions::Backend::Collections::Base < Sessions::Backend::Base def push - # check permission based access - if self.class.permissions - return if !@user.permissions?(self.class.permissions) - end - # check timeout timeout = Sessions::CacheIn.get(client_key) return if timeout @@ -34,6 +29,11 @@ class Sessions::Backend::Collections::Base < Sessions::Backend::Base # set new timeout Sessions::CacheIn.set(client_key, true, { expires_in: @ttl.seconds }) + # check permission based access + if self.class.permissions + return if !@user.permissions?(self.class.permissions) + end + # check if update has been done last_change = self.class.model.constantize.latest_change return if last_change.to_s == @last_change