From 705487154c81599768dd5429d23434f59422b03e Mon Sep 17 00:00:00 2001 From: Thorsten Eckel Date: Thu, 23 Nov 2017 09:09:44 +0100 Subject: [PATCH] Applied changes for Rubocop 0.51. --- .rubocop.yml | 61 ++- Gemfile | 128 ++++--- Gemfile.lock | 15 +- Rakefile | 0 .../application_controller/authenticates.rb | 2 +- .../application_controller/handles_devices.rb | 3 +- .../application_controller/handles_errors.rb | 2 +- .../application_controller/renders_models.rb | 2 +- app/controllers/channels_email_controller.rb | 2 +- app/controllers/form_controller.rb | 25 +- app/controllers/getting_started_controller.rb | 6 +- app/controllers/import_otrs_controller.rb | 8 +- app/controllers/import_zendesk_controller.rb | 2 +- .../integration/check_mk_controller.rb | 2 + .../integration/idoit_controller.rb | 4 +- .../integration/sipgate_controller.rb | 2 + app/controllers/long_polling_controller.rb | 5 +- app/controllers/monitoring_controller.rb | 12 +- .../object_manager_attributes_controller.rb | 12 +- app/controllers/organizations_controller.rb | 8 +- app/controllers/search_controller.rb | 3 + app/controllers/sessions_controller.rb | 4 +- app/controllers/settings_controller.rb | 6 +- app/controllers/ticket_articles_controller.rb | 2 +- app/controllers/tickets_controller.rb | 25 +- .../time_accountings_controller.rb | 6 +- .../user_access_token_controller.rb | 2 +- app/controllers/user_devices_controller.rb | 2 +- app/controllers/users_controller.rb | 17 +- app/models/activity_stream.rb | 2 +- app/models/application_model/can_assets.rb | 2 +- .../application_model/can_associations.rb | 40 +- .../application_model/can_cleanup_param.rb | 4 +- .../can_creates_and_updates.rb | 20 +- .../application_model/can_touch_references.rb | 2 +- .../application_model/has_attachments.rb | 2 +- app/models/authorization.rb | 2 +- app/models/avatar.rb | 18 +- app/models/calendar.rb | 8 +- app/models/channel.rb | 3 - app/models/channel/assets.rb | 4 +- app/models/channel/driver/facebook.rb | 3 +- app/models/channel/driver/imap.rb | 4 +- app/models/channel/driver/smtp.rb | 2 +- app/models/channel/driver/twitter.rb | 23 +- app/models/channel/email_build.rb | 60 ++- app/models/channel/email_parser.rb | 77 ++-- .../channel/filter/auto_response_check.rb | 2 +- .../bounce_delivery_permanent_failed.rb | 2 +- app/models/channel/filter/follow_up_check.rb | 1 + app/models/channel/filter/identify_sender.rb | 6 +- .../channel/filter/match/email_regex.rb | 4 +- app/models/channel/filter/monitoring_base.rb | 9 +- .../channel/filter/out_of_office_check.rb | 5 +- app/models/channel/filter/trusted.rb | 2 +- app/models/chat.rb | 6 +- app/models/chat/agent.rb | 2 +- app/models/concerns/can_seed.rb | 2 +- .../concerns/has_activity_stream_log.rb | 5 +- app/models/concerns/has_history.rb | 10 +- .../concerns/has_search_index_backend.rb | 2 +- app/models/cti/caller_id.rb | 16 +- app/models/cti/log.rb | 2 +- app/models/email_address.rb | 2 +- app/models/external_sync.rb | 2 +- app/models/job.rb | 8 +- app/models/job/assets.rb | 2 +- app/models/locale.rb | 4 +- app/models/object_manager.rb | 4 +- app/models/object_manager/attribute.rb | 65 ++-- .../observer/chat/leave/background_job.rb | 2 - .../observer/organization/ref_object_touch.rb | 4 +- .../observer/sla/ticket_rebuild_escalation.rb | 4 +- .../background_job.rb | 3 +- .../ticket/article/communicate_email.rb | 2 +- .../communicate_email/background_job.rb | 4 +- .../ticket/article/communicate_facebook.rb | 2 +- .../ticket/article/communicate_twitter.rb | 2 +- .../ticket/article/fillup_from_email.rb | 2 +- .../ticket/article/fillup_from_general.rb | 2 +- .../article/fillup_from_origin_by_id.rb | 2 +- app/models/observer/ticket/article_changes.rb | 4 +- .../observer/ticket/ref_object_touch.rb | 10 +- app/models/observer/ticket/reset_new_state.rb | 2 +- app/models/observer/transaction.rb | 8 +- app/models/observer/user/geo.rb | 4 +- app/models/observer/user/ref_object_touch.rb | 6 +- app/models/organization/assets.rb | 2 +- app/models/overview.rb | 4 +- app/models/overview/assets.rb | 14 +- app/models/package.rb | 14 +- app/models/postmaster_filter.rb | 2 +- app/models/report.rb | 2 +- app/models/role/assets.rb | 4 +- app/models/scheduler.rb | 4 +- app/models/sla/assets.rb | 2 +- app/models/store.rb | 2 +- app/models/store/file.rb | 4 +- app/models/store/provider/file.rb | 9 +- app/models/taskbar.rb | 8 +- app/models/ticket.rb | 49 +-- app/models/ticket/article.rb | 17 +- app/models/ticket/article/assets.rb | 2 +- app/models/ticket/assets.rb | 2 +- app/models/ticket/escalation.rb | 14 +- app/models/ticket/overviews.rb | 2 +- app/models/ticket/priority.rb | 7 +- app/models/ticket/screen_options.rb | 2 +- app/models/ticket/search_index.rb | 2 +- app/models/ticket/state.rb | 12 +- app/models/transaction/background_job.rb | 2 +- .../transaction/cti_caller_id_detection.rb | 1 + app/models/transaction/karma.rb | 11 +- app/models/transaction/notification.rb | 8 +- app/models/transaction/slack.rb | 14 +- app/models/transaction/trigger.rb | 8 +- app/models/translation.rb | 12 +- app/models/user.rb | 31 +- app/models/user/assets.rb | 36 +- app/models/user_device.rb | 2 +- config/application.rb | 6 +- config/initializers/assets.rb | 4 +- config/initializers/core_ext.rb | 2 +- config/initializers/doorkeeper.rb | 2 +- .../initializers/filter_parameter_logging.rb | 2 +- config/initializers/html_email_style.rb | 154 ++++---- config/initializers/html_sanitizer.rb | 78 ++-- config/initializers/vendor_lib.rb | 2 +- config/routes.rb | 2 +- config/routes/auth.rb | 8 +- config/routes/message.rb | 4 +- config/routes/organization.rb | 2 +- config/routes/report.rb | 2 +- config/routes/search.rb | 4 +- config/routes/ticket.rb | 2 +- config/routes/user.rb | 4 +- db/migrate/20120101000001_create_base.rb | 28 +- db/migrate/20120101000010_create_ticket.rb | 14 +- .../20150979000001_update_timestamps.rb | 2 +- ...160217000001_object_manager_update_user.rb | 1 + ...01_organization_domain_based_assignment.rb | 1 + ...00002_ticket_number_generator_issue_427.rb | 2 +- ...3000001_fixed_admin_user_permission_920.rb | 6 +- db/migrate/20170419000001_ldap_support.rb | 2 +- db/migrate/20170531144425_foreign_keys.rb | 96 ++--- ...905140038_cti_log_preferences_migration.rb | 4 +- ...xed_twitter_ticket_article_preferences4.rb | 2 +- db/migrate/20170910000002_out_of_office2.rb | 8 +- db/migrate/20170912123300_remove_network.rb | 1 + db/seeds.rb | 3 +- db/seeds/object_manager_attributes.rb | 6 +- db/seeds/overviews.rb | 54 +-- db/seeds/roles.rb | 2 +- db/seeds/settings.rb | 8 +- db/seeds/triggers.rb | 6 +- lib/application_handle_info.rb | 5 + lib/application_lib.rb | 3 +- lib/auth/ldap.rb | 2 +- lib/auto_wizard.rb | 50 ++- lib/calendar_subscriptions.rb | 7 +- lib/calendar_subscriptions/tickets.rb | 2 +- lib/core_ext/integer.rb | 17 - lib/core_ext/nil_class.rb | 17 - lib/core_ext/open-uri.rb | 5 +- lib/core_ext/string.rb | 17 +- lib/email_helper/probe.rb | 16 +- lib/encode.rb | 2 - lib/enrichment/clearbit/user.rb | 2 +- lib/facebook.rb | 13 +- lib/fill_db.rb | 65 ++-- lib/html_sanitizer.rb | 38 +- lib/import/base_factory.rb | 6 +- lib/import/base_resource.rb | 6 +- lib/import/exchange/folder.rb | 2 +- lib/import/exchange/item_attributes.rb | 4 +- lib/import/integration_base.rb | 2 +- lib/import/ldap/user.rb | 8 +- lib/import/ldap/user_factory.rb | 2 +- lib/import/otrs.rb | 2 +- lib/import/otrs/article/attachment_factory.rb | 2 +- lib/import/otrs/article_customer.rb | 2 +- lib/import/otrs/article_customer_factory.rb | 2 +- lib/import/otrs/dynamic_field_factory.rb | 4 +- lib/import/otrs/history_factory.rb | 2 +- lib/import/otrs/import_stats.rb | 6 +- lib/import/otrs/requester.rb | 4 +- lib/import/otrs/state_factory.rb | 8 +- lib/import/otrs/sys_config_factory.rb | 4 +- lib/import/otrs/ticket.rb | 6 +- lib/import/otrs/user.rb | 4 +- lib/import/zendesk/import_stats.rb | 2 +- lib/import/zendesk/object_attribute.rb | 3 +- lib/import/zendesk/ticket/comment.rb | 2 +- .../ticket/comment/attachment_factory.rb | 2 +- lib/import/zendesk/user/group.rb | 2 +- lib/ldap.rb | 9 +- lib/ldap/group.rb | 6 +- lib/ldap/user.rb | 78 ++-- lib/mixin/required_sub_paths.rb | 2 +- lib/models.rb | 30 +- lib/notification_factory/mailer.rb | 2 +- lib/notification_factory/renderer.rb | 4 +- lib/report/ticket_moved.rb | 5 +- lib/report/ticket_reopened.rb | 2 +- lib/search_index_backend.rb | 8 +- .../common/import_job/sub_sequence/general.rb | 3 +- .../import/common/model/skip/blank/base.rb | 2 +- .../model/skip/missing_mandatory/base.rb | 2 +- .../common/model/statistics/mixin/diff.rb | 2 +- .../import/common/user/attributes/downcase.rb | 2 +- .../folder_contact/statistics/diff.rb | 2 +- lib/sequencer/unit/mixin/dynamic_attribute.rb | 1 - lib/service/image/zammad.rb | 2 +- lib/sessions.rb | 22 +- lib/sessions/backend/activity_stream.rb | 4 +- lib/sessions/event/base.rb | 3 +- lib/sessions/event/login.rb | 2 +- lib/signature_detection.rb | 6 +- lib/static_assets.rb | 24 +- lib/stats.rb | 2 +- lib/telegram.rb | 12 +- lib/tweet_base.rb | 29 +- lib/tweet_stream.rb | 2 +- lib/user_agent.rb | 10 +- lib/version.rb | 2 +- script/websocket-server.rb | 7 +- spec/factories/signature.rb | 2 +- spec/lib/auth/ldap_spec.rb | 2 +- spec/lib/import/ldap/user_factory_spec.rb | 4 +- spec/lib/import/otrs/state_factory_spec.rb | 4 +- spec/lib/import/otrs/user_spec.rb | 3 +- spec/models/concerns/has_groups_examples.rb | 16 +- spec/models/concerns/has_roles_examples.rb | 14 +- spec/models/cti/caller_id_spec.rb | 6 +- spec/models/taskbar_spec.rb | 2 +- spec/models/translation_spec.rb | 6 +- spec/rails_helper.rb | 2 +- spec/support/system_init.rb | 12 +- test/browser/aaa_getting_started_test.rb | 6 +- test/browser/aab_basic_urls_test.rb | 2 +- test/browser/aab_unit_test.rb | 2 +- test/browser/aac_basic_richtext_test.rb | 2 +- test/browser/abb_one_group_test.rb | 2 +- test/browser/admin_channel_email_test.rb | 2 +- test/browser/admin_object_manager_test.rb | 2 +- test/browser/admin_overview_test.rb | 2 +- test/browser/admin_role_test.rb | 2 +- .../agent_navigation_and_title_test.rb | 2 +- .../agent_organization_profile_test.rb | 2 +- test/browser/agent_ticket_attachment_test.rb | 2 +- ...agent_ticket_email_reply_keep_body_test.rb | 2 +- .../agent_ticket_email_signature_test.rb | 2 +- test/browser/agent_ticket_link_test.rb | 2 +- test/browser/agent_ticket_macro_test.rb | 2 +- test/browser/agent_ticket_merge_test.rb | 2 +- .../agent_ticket_online_notification_test.rb | 2 +- .../agent_ticket_overview_level0_test.rb | 2 +- .../agent_ticket_overview_level1_test.rb | 2 +- .../browser/agent_ticket_overview_tab_test.rb | 2 +- test/browser/agent_ticket_tag_test.rb | 2 +- test/browser/agent_ticket_text_module_test.rb | 4 +- .../agent_ticket_time_accounting_test.rb | 2 +- test/browser/agent_ticket_update1_test.rb | 2 +- test/browser/agent_ticket_update2_test.rb | 2 +- test/browser/agent_ticket_update3_test.rb | 2 +- .../agent_ticket_update_and_reload_test.rb | 2 +- test/browser/agent_user_manage_test.rb | 2 +- test/browser/agent_user_profile_test.rb | 2 +- test/browser/auth_test.rb | 2 +- test/browser/chat_test.rb | 2 +- test/browser/customer_ticket_create_test.rb | 2 +- test/browser/first_steps_test.rb | 2 +- test/browser/form_test.rb | 2 +- test/browser/integration_test.rb | 2 +- test/browser/keyboard_shortcuts_test.rb | 2 +- test/browser/maintenance_app_version_test.rb | 2 +- .../browser/maintenance_login_message_test.rb | 2 +- test/browser/maintenance_mode_test.rb | 2 +- .../maintenance_session_message_test.rb | 2 +- test/browser/manage_test.rb | 2 +- test/browser/monitoring_test.rb | 2 +- test/browser/preferences_language_test.rb | 2 +- .../preferences_permission_check_test.rb | 2 +- test/browser/preferences_token_access_test.rb | 2 +- test/browser/setting_test.rb | 2 +- .../signup_password_change_and_reset_test.rb | 2 +- test/browser/switch_to_user_test.rb | 2 +- test/browser/taskbar_session_test.rb | 2 +- test/browser/taskbar_task_test.rb | 2 +- test/browser/translation_test.rb | 2 +- test/browser/user_switch_cache_test.rb | 2 +- test/browser_test_helper.rb | 348 ++++++++---------- test/controllers/api_auth_controller_test.rb | 4 +- test/controllers/basic_controller_test.rb | 2 +- test/controllers/form_controller_test.rb | 2 +- .../integration_check_mk_controller_test.rb | 2 +- .../controllers/monitoring_controller_test.rb | 8 +- test/controllers/packages_controller_test.rb | 4 +- test/controllers/search_controller_test.rb | 10 +- test/controllers/settings_controller_test.rb | 4 +- test/controllers/taskbars_controller_test.rb | 2 +- ...ket_article_attachments_controller_test.rb | 4 +- .../ticket_articles_controller_test.rb | 4 +- test/controllers/tickets_controller_test.rb | 4 +- .../user_organization_controller_test.rb | 4 +- test/fixtures/seeds.rb | 4 +- .../aaa_auto_wizard_base_setup_test.rb | 2 +- test/integration/auto_wizard_browser_test.rb | 2 +- test/integration/auto_wizard_test.rb | 16 +- .../calendar_subscriptions_tickets_test.rb | 8 +- test/integration/clearbit_test.rb | 2 +- test/integration/elasticsearch_test.rb | 28 +- test/integration/email_deliver_test.rb | 2 +- test/integration/email_helper_test.rb | 4 +- test/integration/email_keep_on_server_test.rb | 2 +- test/integration/facebook_browser_test.rb | 2 +- test/integration/facebook_test.rb | 2 +- test/integration/geo_calendar_test.rb | 2 +- test/integration/geo_ip_test.rb | 2 +- test/integration/geo_location_test.rb | 2 +- test/integration/idoit_controller_test.rb | 6 +- test/integration/object_manager_test.rb | 6 +- test/integration/otrs_import_browser_test.rb | 2 +- test/integration/otrs_import_test.rb | 8 +- test/integration/package_test.rb | 2 +- test/integration/report_test.rb | 2 +- test/integration/sipgate_controller_test.rb | 4 +- test/integration/slack_test.rb | 6 +- test/integration/telegram_controller_test.rb | 2 +- test/integration/twitter_browser_test.rb | 2 +- test/integration/twitter_test.rb | 2 +- test/integration/user_agent_test.rb | 2 +- .../user_device_controller_test.rb | 4 +- .../zendesk_import_browser_test.rb | 2 +- test/integration/zendesk_import_test.rb | 14 +- test/integration_test_helper.rb | 4 +- test/test_helper.rb | 12 +- test/unit/aaa_string_test.rb | 1 - test/unit/activity_stream_test.rb | 12 +- test/unit/assets_test.rb | 30 +- test/unit/auth_test.rb | 2 +- test/unit/cache_test.rb | 2 +- test/unit/calendar_subscription_test.rb | 2 +- test/unit/calendar_test.rb | 2 +- test/unit/chat_test.rb | 4 +- test/unit/cti_caller_id_test.rb | 2 +- test/unit/db_auto_increment_test.rb | 2 +- test/unit/email_address_test.rb | 2 +- test/unit/email_build_test.rb | 48 ++- test/unit/email_parser_test.rb | 1 - test/unit/email_postmaster_test.rb | 1 - test/unit/email_process_auto_response_test.rb | 2 +- ...s_bounce_delivery_permanent_failed_test.rb | 6 +- test/unit/email_process_bounce_follow_test.rb | 6 +- .../email_process_follow_up_possible_test.rb | 2 +- test/unit/email_process_follow_up_test.rb | 6 +- .../email_process_identify_sender_max_test.rb | 2 +- test/unit/email_process_out_of_office_test.rb | 2 +- test/unit/email_process_reply_to_test.rb | 2 +- ..._sender_is_system_address_or_agent_test.rb | 2 +- ...il_process_sender_name_update_if_needed.rb | 2 +- test/unit/email_process_state_open_set.rb | 2 +- test/unit/email_process_test.rb | 1 - test/unit/email_regex_test.rb | 2 +- test/unit/email_signatur_detection_test.rb | 20 +- test/unit/history_test.rb | 2 +- test/unit/html_sanitizer_test.rb | 2 +- test/unit/integration_icinga_test.rb | 2 +- test/unit/integration_monit_test.rb | 2 +- test/unit/integration_nagios_test.rb | 2 +- test/unit/job_test.rb | 2 +- test/unit/karma_test.rb | 2 +- test/unit/migration_ror_42_to50_store_test.rb | 2 +- test/unit/model_test.rb | 10 +- ...tification_factory_mailer_template_test.rb | 6 +- test/unit/notification_factory_mailer_test.rb | 2 +- .../notification_factory_renderer_test.rb | 2 +- ...otification_factory_slack_template_test.rb | 6 +- .../notification_factory_template_test.rb | 2 +- test/unit/object_cache_test.rb | 6 +- ...object_create_update_with_ref_name_test.rb | 8 +- test/unit/object_type_lookup_test.rb | 2 +- test/unit/online_notifiaction_test.rb | 8 +- ...ganization_domain_based_assignment_test.rb | 2 +- .../organization_ref_object_touch_test.rb | 2 +- test/unit/overview_test.rb | 56 +-- test/unit/permission_test.rb | 2 +- test/unit/recent_view_test.rb | 2 +- test/unit/role_test.rb | 2 +- test/unit/role_validate_agent_limit_test.rb | 4 +- test/unit/session_basic_test.rb | 24 +- test/unit/session_basic_ticket_test.rb | 4 +- test/unit/session_collections_test.rb | 18 +- test/unit/session_enhanced_test.rb | 6 +- test/unit/stats_ticket_waiting_time_test.rb | 2 +- test/unit/store_test.rb | 12 +- test/unit/tag_test.rb | 2 +- test/unit/ticket_article_communicate_test.rb | 2 +- test/unit/ticket_article_dos_test.rb | 2 +- test/unit/ticket_article_store_empty.rb | 2 +- .../ticket_article_time_accouting_test.rb | 2 +- test/unit/ticket_article_twitter_test.rb | 2 +- ...icket_customer_organization_update_test.rb | 2 +- test/unit/ticket_escalation_test.rb | 2 +- test/unit/ticket_last_owner_update_test.rb | 2 +- test/unit/ticket_notification_test.rb | 4 +- test/unit/ticket_null_byte_test.rb | 2 +- .../ticket_overview_out_of_office_test.rb | 20 +- test/unit/ticket_overview_test.rb | 50 +-- test/unit/ticket_priority_test.rb | 2 +- test/unit/ticket_ref_object_touch_test.rb | 2 +- test/unit/ticket_selector_test.rb | 2 +- test/unit/ticket_sla_test.rb | 14 +- test/unit/ticket_state_test.rb | 2 +- test/unit/ticket_test.rb | 2 +- test/unit/ticket_trigger_test.rb | 24 +- test/unit/ticket_xss_test.rb | 2 +- test/unit/token_test.rb | 2 +- test/unit/user_ref_object_touch_test.rb | 2 +- test/unit/user_test.rb | 56 ++- test/unit/user_validate_agent_limit_test.rb | 2 +- 421 files changed, 1792 insertions(+), 1867 deletions(-) mode change 100644 => 100755 Rakefile delete mode 100644 lib/core_ext/integer.rb delete mode 100644 lib/core_ext/nil_class.rb diff --git a/.rubocop.yml b/.rubocop.yml index f9156d529..6e91d3296 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -45,29 +45,29 @@ Style/TrailingCommaInArguments: StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-trailing-array-commas' Enabled: false -Style/SpaceInsideParens: +Layout/SpaceInsideParens: Description: 'No spaces after ( or before ).' StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-spaces-braces' Enabled: false -Style/SpaceAfterMethodName: +Layout/SpaceAfterMethodName: Description: >- Do not put a space between a method name and the opening parenthesis in a method definition. StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#parens-no-spaces' Enabled: false -Style/LeadingCommentSpace: +Layout/LeadingCommentSpace: Description: 'Comments should start with a space.' StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#hash-space' Enabled: false -Style/MethodCallParentheses: +Style/MethodCallWithoutArgsParentheses: Description: 'Do not use parentheses for method calls with no arguments.' StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-args-no-parens' Enabled: false -Style/SpaceInsideBrackets: +Layout/SpaceInsideBrackets: Description: 'No spaces after [ or before ].' StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-spaces-braces' Enabled: false @@ -83,19 +83,19 @@ Style/MethodDefParentheses: StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#method-parens' Enabled: false -Style/EmptyLinesAroundClassBody: +Layout/EmptyLinesAroundClassBody: Description: "Keeps track of empty lines around class bodies." Enabled: false -Style/EmptyLinesAroundMethodBody: +Layout/EmptyLinesAroundMethodBody: Description: "Keeps track of empty lines around method bodies." Enabled: false -Style/EmptyLinesAroundBlockBody: +Layout/EmptyLinesAroundBlockBody: Description: "Keeps track of empty lines around block bodies." Enabled: false -Style/EmptyLinesAroundModuleBody: +Layout/EmptyLinesAroundModuleBody: Description: "Keeps track of empty lines around module bodies." Enabled: false @@ -143,17 +143,29 @@ Rails/HasAndBelongsToMany: # StyleGuide: 'https://github.com/bbatsov/rails-style-guide#has-many-through' Enabled: false +Rails/SkipsModelValidations: + Description: >- + Use methods that skips model validations with caution. + See reference for more information. + Reference: 'http://guides.rubyonrails.org/active_record_validations.html#skipping-validations' + Enabled: true + Exclude: + - test/**/* + Style/ClassAndModuleChildren: Description: 'Checks style of children classes and modules.' Enabled: false -Style/FileName: +Naming/FileName: Description: 'Use snake_case for source file names.' StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#snake-case-files' Enabled: true Exclude: - 'script/websocket-server.rb' +Naming/VariableNumber: + Description: 'Use the configured style when numbering variables.' + Enabled: false # 2.0 @@ -184,8 +196,23 @@ Metrics/ModuleLength: Description: 'Avoid modules longer than 100 lines of code.' Enabled: false +Metrics/BlockLength: + Enabled: false + +Lint/RescueWithoutErrorClass: + Enabled: false + +Rails/ApplicationRecord: + Enabled: false + # TODO +Rails/HasManyOrHasOneDependent: + Enabled: false + +Style/DateTime: + Enabled: false + Style/Documentation: Description: 'Document classes and non-namespace modules.' Enabled: false @@ -193,7 +220,7 @@ Style/Documentation: Lint/UselessAssignment: Enabled: false -Style/ExtraSpacing: +Layout/ExtraSpacing: Description: 'Do not use unnecessary spacing.' Enabled: false @@ -215,4 +242,14 @@ Style/NumericPredicate: AutoCorrect: false Enabled: true Exclude: - - "**/*_spec.rb" \ No newline at end of file + - "**/*_spec.rb" + +Lint/AmbiguousBlockAssociation: + Description: >- + Checks for ambiguous block association with method when param passed without + parentheses. + StyleGuide: '#syntax' + Enabled: true + Exclude: + - "**/*_spec.rb" + - "**/*_examples.rb" diff --git a/Gemfile b/Gemfile index 394f766f1..047a01bb1 100644 --- a/Gemfile +++ b/Gemfile @@ -1,112 +1,131 @@ source 'https://rubygems.org' +# core - base ruby '2.4.1' - gem 'rails', '5.1.4' -gem 'rails-observers' + +# core - rails additions gem 'activerecord-session_store' - -# Bundle edge Rails instead: -#gem 'rails', :git => 'git://github.com/rails/rails.git' - +gem 'composite_primary_keys' gem 'json' +gem 'rails-observers' -# Supported DBs +# core - application servers +gem 'puma', group: :puma +gem 'unicorn', group: :unicorn + +# core - supported ORMs gem 'activerecord-nulldb-adapter', group: :nulldb gem 'mysql2', group: :mysql gem 'pg', group: :postgres +# core - asynchrous task execution +gem 'daemons' +gem 'delayed_job_active_record' + +# core - websocket +gem 'em-websocket' +gem 'eventmachine' + +# core - password security +gem 'argon2' + +# performance - Memcached +gem 'dalli' + +# asset handling group :assets do - gem 'sass-rails' #, github: 'rails/sass-rails' + # asset handling - coffee-script gem 'coffee-rails' gem 'coffee-script-source' - gem 'sprockets' - - gem 'uglifier' + # asset handling - frontend templating gem 'eco' + + # asset handling - SASS + gem 'sass-rails' + + # asset handling - pipeline + gem 'sprockets' + gem 'uglifier' end gem 'autoprefixer-rails' +# asset handling - javascript execution for e.g. linux +gem 'execjs' +gem 'libv8' +gem 'therubyracer' + +# authentication - provider gem 'doorkeeper' gem 'oauth2' +# authentication - third party gem 'omniauth' -gem 'omniauth-oauth2' gem 'omniauth-facebook' gem 'omniauth-github' gem 'omniauth-gitlab' gem 'omniauth-google-oauth2' gem 'omniauth-linkedin-oauth2' -gem 'omniauth-twitter' gem 'omniauth-microsoft-office365' +gem 'omniauth-oauth2' +gem 'omniauth-twitter' gem 'omniauth-weibo-oauth2' -gem 'twitter' -gem 'telegramAPI' +# channels gem 'koala' -gem 'mail' -gem 'valid_email2' +gem 'telegramAPI' +gem 'twitter' + +# channels - email additions gem 'htmlentities' - +gem 'mail', '2.6.6' gem 'mime-types' +gem 'valid_email2' +# feature - business hours gem 'biz' -gem 'composite_primary_keys' -gem 'delayed_job_active_record' -gem 'daemons' - -gem 'simple-rss' - -# e. g. on linux we need a javascript execution -gem 'libv8' -gem 'execjs' -gem 'therubyracer' - -require 'erb' -require 'yaml' - -gem 'net-ldap' - -# password security -gem 'argon2' +# feature - signature diffing +gem 'diffy' +# feature - excel output gem 'writeexcel' -gem 'icalendar' -gem 'icalendar-recurrence' + +# feature - device logging gem 'browser' +# feature - iCal export +gem 'icalendar' +gem 'icalendar-recurrence' + # integrations -gem 'slack-notifier' gem 'clearbit' +gem 'net-ldap' +gem 'slack-notifier' gem 'zendesk_api' -gem 'viewpoint' -gem 'rubyntlm', git: 'https://github.com/wimm/rubyntlm.git' + +# integrations - exchange gem 'autodiscover', git: 'https://github.com/thorsteneckel/autodiscover.git' - -# event machine -gem 'eventmachine' -gem 'em-websocket' - -gem 'diffy' -gem 'dalli' +gem 'rubyntlm', git: 'https://github.com/wimm/rubyntlm.git' +gem 'viewpoint' # Gems used only for develop/test and not required # in production environments by default. group :development, :test do + # test frameworks gem 'rspec-rails' gem 'test-unit' - gem 'spring' - gem 'spring-commands-rspec' + + # test DB gem 'sqlite3' # code coverage + gem 'coveralls', require: false gem 'simplecov' gem 'simplecov-rcov' - gem 'coveralls', require: false # UI tests w/ Selenium gem 'selenium-webdriver', '2.53.4' @@ -121,9 +140,9 @@ group :development, :test do gem 'guard-symlink', require: false # code QA + gem 'coffeelint' gem 'pre-commit' gem 'rubocop' - gem 'coffeelint' # changelog generation gem 'github_changelog_generator' @@ -138,10 +157,7 @@ group :development, :test do gem 'webmock' end -gem 'puma', group: :puma -gem 'unicorn', group: :unicorn - -# load onw gem's +# load onw gems for development and testing purposes local_gemfile = File.join(File.dirname(__FILE__), 'Gemfile.local') if File.exist?(local_gemfile) eval_gemfile local_gemfile diff --git a/Gemfile.lock b/Gemfile.lock index bc2c0bf51..a5ae0d62c 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -217,13 +217,12 @@ GEM crass (~> 1.0.2) nokogiri (>= 1.5.9) lumberjack (1.0.12) - mail (2.7.0) - mini_mime (>= 0.1.1) + mail (2.6.6) + mime-types (>= 1.16, < 4) memoizable (0.4.2) thread_safe (~> 0.3, >= 0.3.1) method_source (0.9.0) mime-types (2.99.3) - mini_mime (1.0.0) mini_portile2 (2.3.0) minitest (5.10.3) multi_json (1.12.2) @@ -389,7 +388,6 @@ GEM rubyzip (~> 1.0) websocket (~> 1.0) shellany (0.0.1) - simple-rss (1.3.1) simple_oauth (0.3.1) simplecov (0.15.1) docile (~> 1.1.0) @@ -399,10 +397,6 @@ GEM simplecov-rcov (0.2.3) simplecov (>= 0.4.1) slack-notifier (2.3.1) - spring (2.0.2) - activesupport (>= 4.2) - spring-commands-rspec (1.0.4) - spring (>= 0.9.1) sprockets (3.7.1) concurrent-ruby (~> 1.0) rack (> 1, < 3) @@ -508,7 +502,7 @@ DEPENDENCIES json koala libv8 - mail + mail (= 2.6.6) mime-types mysql2 net-ldap @@ -535,12 +529,9 @@ DEPENDENCIES rubyntlm! sass-rails selenium-webdriver (= 2.53.4) - simple-rss simplecov simplecov-rcov slack-notifier - spring - spring-commands-rspec sprockets sqlite3 telegramAPI diff --git a/Rakefile b/Rakefile old mode 100644 new mode 100755 diff --git a/app/controllers/application_controller/authenticates.rb b/app/controllers/application_controller/authenticates.rb index 9d5703dbb..c0b1ff341 100644 --- a/app/controllers/application_controller/authenticates.rb +++ b/app/controllers/application_controller/authenticates.rb @@ -18,7 +18,7 @@ module ApplicationController::Authenticates raise Exceptions::NotAuthorized, 'Not authorized (token)!' end - return false if current_user && current_user.permissions?(key) + return false if current_user&.permissions?(key) raise Exceptions::NotAuthorized, 'Not authorized (user)!' end diff --git a/app/controllers/application_controller/handles_devices.rb b/app/controllers/application_controller/handles_devices.rb index 9bead8f45..718dae82e 100644 --- a/app/controllers/application_controller/handles_devices.rb +++ b/app/controllers/application_controller/handles_devices.rb @@ -26,8 +26,7 @@ module ApplicationController::HandlesDevices if user_device_updated_at # check if entry exists / only if write action diff = Time.zone.now - 10.minutes - method = request.method - if method == 'GET' || method == 'OPTIONS' || method == 'HEAD' + if %w[GET OPTIONS HEAD].include?(request.method) diff = Time.zone.now - 30.minutes end diff --git a/app/controllers/application_controller/handles_errors.rb b/app/controllers/application_controller/handles_errors.rb index 1ec299704..98c1728f7 100644 --- a/app/controllers/application_controller/handles_errors.rb +++ b/app/controllers/application_controller/handles_errors.rb @@ -72,7 +72,7 @@ module ApplicationController::HandlesErrors data[:error_human] = data[:error] end - if Rails.env.production? && !data[:error_human].empty? + if Rails.env.production? && data[:error_human].present? data[:error] = data.delete(:error_human) end data diff --git a/app/controllers/application_controller/renders_models.rb b/app/controllers/application_controller/renders_models.rb index a4eb681d1..09fd9db7d 100644 --- a/app/controllers/application_controller/renders_models.rb +++ b/app/controllers/application_controller/renders_models.rb @@ -146,7 +146,7 @@ module ApplicationController::RendersModels def model_references_check(object, params) generic_object = object.find(params[:id]) result = Models.references(object, generic_object.id) - return false if result.empty? + return false if result.blank? raise Exceptions::UnprocessableEntity, 'Can\'t delete, object has references.' rescue => e raise Exceptions::UnprocessableEntity, e diff --git a/app/controllers/channels_email_controller.rb b/app/controllers/channels_email_controller.rb index 633d13dfb..0dc1ac72a 100644 --- a/app/controllers/channels_email_controller.rb +++ b/app/controllers/channels_email_controller.rb @@ -226,7 +226,7 @@ class ChannelsEmailController < ApplicationController Channel.where(area: 'Email::Notification').each do |channel| active = false - if adapter =~ /^#{channel.options[:outbound][:adapter]}$/i + if adapter.match?(/^#{channel.options[:outbound][:adapter]}$/i) active = true channel.options = { outbound: { diff --git a/app/controllers/form_controller.rb b/app/controllers/form_controller.rb index 22693a203..18ab83c70 100644 --- a/app/controllers/form_controller.rb +++ b/app/controllers/form_controller.rb @@ -44,7 +44,7 @@ class FormController < ApplicationController errors['email'] = 'required' elsif params[:email] !~ /@/ errors['email'] = 'invalid' - elsif params[:email] =~ /(>|<|\||\!|"|§|'|\$|%|&|\(|\)|\?|\s|\.\.)/ + elsif params[:email].match?(/(>|<|\||\!|"|§|'|\$|%|&|\(|\)|\?|\s|\.\.)/) errors['email'] = 'invalid' end if params[:title].blank? @@ -126,19 +126,16 @@ class FormController < ApplicationController internal: false, ) - if params[:file] - - params[:file].each do |file| - Store.add( - object: 'Ticket::Article', - o_id: article.id, - data: file.read, - filename: file.original_filename, - preferences: { - 'Mime-Type' => file.content_type, - } - ) - end + params[:file]&.each do |file| + Store.add( + object: 'Ticket::Article', + o_id: article.id, + data: file.read, + filename: file.original_filename, + preferences: { + 'Mime-Type' => file.content_type, + } + ) end UserInfo.current_user_id = 1 diff --git a/app/controllers/getting_started_controller.rb b/app/controllers/getting_started_controller.rb index c074b928e..91b542d4a 100644 --- a/app/controllers/getting_started_controller.rb +++ b/app/controllers/getting_started_controller.rb @@ -66,7 +66,7 @@ curl http://localhost/api/v1/getting_started -v -u #{login}:#{password} # verify auto wizard file auto_wizard_data = AutoWizard.data - if !auto_wizard_data || auto_wizard_data.empty? + if auto_wizard_data.blank? render json: { auto_wizard: true, auto_wizard_success: false, @@ -132,7 +132,7 @@ curl http://localhost/api/v1/getting_started -v -u #{login}:#{password} end # validate organization - if !params[:organization] || params[:organization].empty? + if params[:organization].blank? messages[:organization] = 'Invalid!' else settings[:organization] = params[:organization] @@ -146,7 +146,7 @@ curl http://localhost/api/v1/getting_started -v -u #{login}:#{password} end end - if !messages.empty? + if messages.present? render json: { result: 'invalid', messages: messages, diff --git a/app/controllers/import_otrs_controller.rb b/app/controllers/import_otrs_controller.rb index 9177de868..289d9e7ca 100644 --- a/app/controllers/import_otrs_controller.rb +++ b/app/controllers/import_otrs_controller.rb @@ -26,7 +26,7 @@ class ImportOtrsController < ApplicationController if !response.success? && response.code.to_s !~ /^40.$/ message_human = '' translation_map.each do |key, message| - if response.error.to_s =~ /#{Regexp.escape(key)}/i + if response.error.to_s.match?(/#{Regexp.escape(key)}/i) message_human = message end end @@ -39,7 +39,7 @@ class ImportOtrsController < ApplicationController end result = {} - if response.body =~ /zammad migrator/ + if response.body.match?(/zammad migrator/) migrator_response = JSON.parse(response.body) @@ -86,7 +86,7 @@ class ImportOtrsController < ApplicationController message_human: migrator_response['Error'] } end - elsif response.body =~ /(otrs\sag|otrs\.com|otrs\.org)/i + elsif response.body.match?(/(otrs\sag|otrs\.com|otrs\.org)/i) result = { result: 'invalid', message_human: 'Host found, but no OTRS migrator is installed!' @@ -144,7 +144,7 @@ class ImportOtrsController < ApplicationController end result = 'ok' - if !issues.empty? + if issues.present? result = 'failed' end render json: { diff --git a/app/controllers/import_zendesk_controller.rb b/app/controllers/import_zendesk_controller.rb index 2b2f23541..28bdbd609 100644 --- a/app/controllers/import_zendesk_controller.rb +++ b/app/controllers/import_zendesk_controller.rb @@ -28,7 +28,7 @@ class ImportZendeskController < ApplicationController if !response.success? message_human = '' translation_map.each do |key, message| - if response.error.to_s =~ /#{Regexp.escape(key)}/i + if response.error.to_s.match?(/#{Regexp.escape(key)}/i) message_human = message end end diff --git a/app/controllers/integration/check_mk_controller.rb b/app/controllers/integration/check_mk_controller.rb index 4335af3a6..2c62c7fe3 100644 --- a/app/controllers/integration/check_mk_controller.rb +++ b/app/controllers/integration/check_mk_controller.rb @@ -133,6 +133,8 @@ UserAgent: #{request.env['HTTP_USER_AGENT']} if Setting.get('check_mk_token') != params[:token] raise Exceptions::UnprocessableEntity, 'Invalid token!' end + + true end end diff --git a/app/controllers/integration/idoit_controller.rb b/app/controllers/integration/idoit_controller.rb index c217de073..39ea03361 100644 --- a/app/controllers/integration/idoit_controller.rb +++ b/app/controllers/integration/idoit_controller.rb @@ -1,9 +1,9 @@ # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/ class Integration::IdoitController < ApplicationController - prepend_before_action -> { authentication_check(permission: ['agent.integration.idoit', 'admin.integration.idoit']) }, except: [:verify, :query, :update] + prepend_before_action -> { authentication_check(permission: ['agent.integration.idoit', 'admin.integration.idoit']) }, except: %i[verify query update] prepend_before_action -> { authentication_check(permission: ['admin.integration.idoit']) }, only: [:verify] - prepend_before_action -> { authentication_check(permission: ['ticket.agent']) }, only: [:query, :update] + prepend_before_action -> { authentication_check(permission: ['ticket.agent']) }, only: %i[query update] def verify response = ::Idoit.verify(params[:api_token], params[:endpoint], params[:client_id]) diff --git a/app/controllers/integration/sipgate_controller.rb b/app/controllers/integration/sipgate_controller.rb index 10545e891..4359c16d5 100644 --- a/app/controllers/integration/sipgate_controller.rb +++ b/app/controllers/integration/sipgate_controller.rb @@ -93,6 +93,8 @@ class Integration::SipgateController < ApplicationController xml_error('Feature not configured, please contact your admin!') return end + + true end def config_integration diff --git a/app/controllers/long_polling_controller.rb b/app/controllers/long_polling_controller.rb index 1bc6b1937..5ac74de82 100644 --- a/app/controllers/long_polling_controller.rb +++ b/app/controllers/long_polling_controller.rb @@ -18,7 +18,7 @@ class LongPollingController < ApplicationController params['data'] = {} end session_data = {} - if current_user && current_user.id + if current_user&.id session_data = { 'id' => current_user.id } end @@ -61,13 +61,12 @@ class LongPollingController < ApplicationController # check queue to send begin - # update last ping 4.times do sleep 0.25 end #sleep 1 - Sessions.touch(client_id) + Sessions.touch(client_id) # rubocop:disable Rails/SkipsModelValidations # set max loop time to 24 sec. because of 30 sec. timeout of mod_proxy count = 3 diff --git a/app/controllers/monitoring_controller.rb b/app/controllers/monitoring_controller.rb index 22f8f319f..2d30de077 100644 --- a/app/controllers/monitoring_controller.rb +++ b/app/controllers/monitoring_controller.rb @@ -1,7 +1,7 @@ # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/ class MonitoringController < ApplicationController - prepend_before_action -> { authentication_check(permission: 'admin.monitoring') }, except: [:health_check, :status] + prepend_before_action -> { authentication_check(permission: 'admin.monitoring') }, except: %i[health_check status] skip_before_action :verify_csrf_token =begin @@ -39,7 +39,7 @@ curl http://localhost/api/v1/monitoring/health_check?token=XXX # inbound channel if channel.status_in == 'error' message = "Channel: #{channel.area} in " - %w(host user uid).each do |key| + %w[host user uid].each do |key| next if channel.options[key].blank? message += "key:#{channel.options[key]};" end @@ -52,7 +52,7 @@ 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 do |key| + %w[host user uid].each do |key| next if channel.options[key].blank? message += "key:#{channel.options[key]};" end @@ -60,7 +60,7 @@ curl http://localhost/api/v1/monitoring/health_check?token=XXX end # unprocessable mail check - directory = "#{Rails.root}/tmp/unprocessable_mail" + directory = Rails.root.join('tmp', 'unprocessable_mail').to_s if File.exist?(directory) count = 0 Dir.glob("#{directory}/*.eml") do |_entry| @@ -161,9 +161,7 @@ curl http://localhost/api/v1/monitoring/status?token=XXX 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 + status[:last_created_at][key] = last&.created_at end render json: status diff --git a/app/controllers/object_manager_attributes_controller.rb b/app/controllers/object_manager_attributes_controller.rb index 33e1ad304..15bace68d 100644 --- a/app/controllers/object_manager_attributes_controller.rb +++ b/app/controllers/object_manager_attributes_controller.rb @@ -98,20 +98,20 @@ class ObjectManagerAttributesController < ApplicationController private def check_params - if params[:data_type] =~ /^(boolean)$/ + if params[:data_type].match?(/^(boolean)$/) if params[:data_option][:options] + # rubocop:disable Lint/BooleanSymbol if params[:data_option][:options][:false] - params[:data_option][:options][false] = params[:data_option][:options][:false] - params[:data_option][:options].delete(:false) + params[:data_option][:options][false] = params[:data_option][:options].delete(:false) end if params[:data_option][:options][:true] - params[:data_option][:options][true] = params[:data_option][:options][:true] - params[:data_option][:options].delete(:true) + params[:data_option][:options][true] = params[:data_option][:options].delete(:true) end + # rubocop:enable Lint/BooleanSymbol end end if params[:data_option] && !params[:data_option].key?(:default) - params[:data_option][:default] = if params[:data_type] =~ /^(input|select|tree_select)$/ + params[:data_option][:default] = if params[:data_type].match?(/^(input|select|tree_select)$/) '' end end diff --git a/app/controllers/organizations_controller.rb b/app/controllers/organizations_controller.rb index 5ba533af3..d42096466 100644 --- a/app/controllers/organizations_controller.rb +++ b/app/controllers/organizations_controller.rb @@ -237,12 +237,16 @@ curl http://localhost/api/v1/organization/{id} -v -u #{login}:#{password} -H "Co params[:limit].to_i = 500 end + query = params[:query] + if query.respond_to?(:permit!) + query = query.permit!.to_h + end query_params = { - query: params[:query], + query: query, limit: params[:limit], current_user: current_user, } - if params[:role_ids] && !params[:role_ids].empty? + if params[:role_ids].present? query_params[:role_ids] = params[:role_ids] end diff --git a/app/controllers/search_controller.rb b/app/controllers/search_controller.rb index af280d34a..1ec9c76f8 100644 --- a/app/controllers/search_controller.rb +++ b/app/controllers/search_controller.rb @@ -16,6 +16,9 @@ class SearchController < ApplicationController # get params query = params[:query] + if query.respond_to?(:permit!) + query = query.permit!.to_h + end limit = params[:limit] || 10 # convert objects string into array of class names diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index fbcc7ad05..d65a9711c 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -1,8 +1,8 @@ # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/ class SessionsController < ApplicationController - prepend_before_action :authentication_check, only: [:switch_to_user, :list, :delete] - skip_before_action :verify_csrf_token, only: [:create, :show, :destroy, :create_omniauth, :create_sso] + prepend_before_action :authentication_check, only: %i[switch_to_user list delete] + skip_before_action :verify_csrf_token, only: %i[create show destroy create_omniauth create_sso] # "Create" a login, aka "log the user in" def create diff --git a/app/controllers/settings_controller.rb b/app/controllers/settings_controller.rb index d9288d6c0..6d332edb0 100644 --- a/app/controllers/settings_controller.rb +++ b/app/controllers/settings_controller.rb @@ -93,11 +93,11 @@ class SettingsController < ApplicationController def keep_certain_attributes setting = Setting.find(params[:id]) - [:name, :area, :state_initial, :frontend, :options].each do |key| + %i[name area state_initial frontend options].each do |key| params.delete(key) end - if !params[:preferences].empty? - [:online_service_disable, :permission, :render].each do |key| + if params[:preferences].present? + %i[online_service_disable permission render].each do |key| params[:preferences].delete(key) end params[:preferences].merge!(setting.preferences) diff --git a/app/controllers/ticket_articles_controller.rb b/app/controllers/ticket_articles_controller.rb index bb10603da..6585a43e0 100644 --- a/app/controllers/ticket_articles_controller.rb +++ b/app/controllers/ticket_articles_controller.rb @@ -266,7 +266,7 @@ class TicketArticlesController < ApplicationController def sanitized_disposition disposition = params.fetch(:disposition, 'inline') - valid_disposition = %w(inline attachment) + valid_disposition = %w[inline attachment] return disposition if valid_disposition.include?(disposition) raise Exceptions::NotAuthorized, "Invalid disposition #{disposition} requested. Only #{valid_disposition.join(', ')} are valid." end diff --git a/app/controllers/tickets_controller.rb b/app/controllers/tickets_controller.rb index 5f289bb01..dbf33b33f 100644 --- a/app/controllers/tickets_controller.rb +++ b/app/controllers/tickets_controller.rb @@ -80,7 +80,7 @@ class TicketsController < ApplicationController # overwrite params if !current_user.permissions?('ticket.agent') - [:owner, :owner_id, :customer, :customer_id, :organization, :organization_id, :preferences].each do |key| + %i[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 @@ -186,7 +186,7 @@ class TicketsController < ApplicationController # overwrite params if !current_user.permissions?('ticket.agent') - [:owner, :owner_id, :customer, :customer_id, :organization, :organization_id, :preferences].each do |key| + %i[owner owner_id customer customer_id organization organization_id preferences].each do |key| clean_params.delete(key) end end @@ -270,7 +270,7 @@ class TicketsController < ApplicationController .limit(6) # if we do not have open related tickets, search for any tickets - if ticket_lists.empty? + if ticket_lists.blank? ticket_lists = Ticket .where( customer_id: ticket.customer_id, @@ -389,11 +389,16 @@ class TicketsController < ApplicationController params[:limit].to_i = 100 end + query = params[:query] + if query.respond_to?(:permit!) + query = query.permit!.to_h + end + # build result list tickets = Ticket.search( + query: query, + condition: params[:condition].to_h, limit: params[:limit], - query: params[:query], - condition: params[:condition], current_user: current_user, ) @@ -435,11 +440,9 @@ class TicketsController < ApplicationController assets = {} ticket_ids = [] - if tickets - tickets.each do |ticket| - ticket_ids.push ticket.id - assets = ticket.assets(assets) - end + tickets&.each do |ticket| + ticket_ids.push ticket.id + assets = ticket.assets(assets) end # return result @@ -504,7 +507,7 @@ class TicketsController < ApplicationController # lookup open org tickets org_tickets = {} - if params[:organization_id] && !params[:organization_id].empty? + if params[:organization_id].present? organization = Organization.lookup(id: params[:organization_id]) if !organization raise "No such organization with id #{params[:organization_id]}" diff --git a/app/controllers/time_accountings_controller.rb b/app/controllers/time_accountings_controller.rb index 2c93797f6..ec353dd22 100644 --- a/app/controllers/time_accountings_controller.rb +++ b/app/controllers/time_accountings_controller.rb @@ -164,7 +164,7 @@ class TimeAccountingsController < ApplicationController ] result = [] results.each do |row| - row[:ticket].keys.each do |field| + row[:ticket].each_key do |field| next if row[:ticket][field].blank? next if !row[:ticket][field].is_a?(ActiveSupport::TimeWithZone) @@ -250,7 +250,7 @@ class TimeAccountingsController < ApplicationController customers[ticket.customer_id][:time_unit] += local_time_unit[:time_unit] end results = [] - customers.each do |_customer_id, content| + customers.each_value do |content| results.push content end @@ -326,7 +326,7 @@ class TimeAccountingsController < ApplicationController organizations[ticket.organization_id][:time_unit] += local_time_unit[:time_unit] end results = [] - organizations.each do |_customer_id, content| + organizations.each_value do |content| results.push content end diff --git a/app/controllers/user_access_token_controller.rb b/app/controllers/user_access_token_controller.rb index 8b1f5aeec..f00227db7 100644 --- a/app/controllers/user_access_token_controller.rb +++ b/app/controllers/user_access_token_controller.rb @@ -14,7 +14,7 @@ class UserAccessTokenController < ApplicationController end local_permissions = current_user.permissions local_permissions_new = {} - local_permissions.each do |key, _value| + local_permissions.each_key do |key| keys = Object.const_get('Permission').with_parents(key) keys.each do |local_key| next if local_permissions_new.key?([local_key]) diff --git a/app/controllers/user_devices_controller.rb b/app/controllers/user_devices_controller.rb index b419b336c..4b9efccc3 100644 --- a/app/controllers/user_devices_controller.rb +++ b/app/controllers/user_devices_controller.rb @@ -8,7 +8,7 @@ class UserDevicesController < ApplicationController devices_full = [] devices.each do |device| attributes = device.attributes - if device.location_details['city_name'] && !device.location_details['city_name'].empty? + if device.location_details['city_name'].present? attributes['location'] += ", #{device.location_details['city_name']}" end attributes.delete('created_at') diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index bad343c3e..c356a51ce 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -1,7 +1,7 @@ # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/ class UsersController < ApplicationController - prepend_before_action :authentication_check, except: [:create, :password_reset_send, :password_reset_verify, :image] + prepend_before_action :authentication_check, except: %i[create password_reset_send password_reset_verify image] prepend_before_action :authentication_check_only, only: [:create] # @path [GET] /users @@ -145,7 +145,7 @@ class UsersController < ApplicationController group_ids = [] role_ids = [] if count <= 2 - Role.where(name: %w(Admin Agent)).each do |role| + Role.where(name: %w[Admin Agent]).each do |role| role_ids.push role.id end Group.all().each do |group| @@ -363,12 +363,17 @@ class UsersController < ApplicationController params[:limit].to_i = 500 end + query = params[:query] + if query.respond_to?(:permit!) + query = query.permit!.to_h + end + query_params = { - query: params[:query], + query: query, limit: params[:limit], current_user: current_user, } - [:role_ids, :permissions].each do |key| + %i[role_ids permissions].each do |key| next if params[key].blank? query_params[key] = params[key] end @@ -1046,7 +1051,7 @@ curl http://localhost/api/v1/users/avatar -v -u #{login}:#{password} -H "Content def permission_check_by_permission(params) return true if current_user.permissions?('admin.user') - %i(role_ids roles).each do |key| + %i[role_ids roles].each do |key| next if !params[key] if current_user.permissions?('ticket.agent') params.delete(key) @@ -1059,7 +1064,7 @@ curl http://localhost/api/v1/users/avatar -v -u #{login}:#{password} -H "Content params[:role_ids] = Role.signup_role_ids end - %i(group_ids groups).each do |key| + %i[group_ids groups].each do |key| next if !params[key] if current_user.permissions?('ticket.agent') params.delete(key) diff --git a/app/models/activity_stream.rb b/app/models/activity_stream.rb index 957e7ff2a..882f36126 100644 --- a/app/models/activity_stream.rb +++ b/app/models/activity_stream.rb @@ -99,7 +99,7 @@ return all activity entries of an user permission_ids = user.permissions_with_child_ids group_ids = user.group_ids_access('read') - stream = if group_ids.empty? + stream = if group_ids.blank? ActivityStream.where('(permission_id IN (?) AND group_id is NULL)', permission_ids) .order('created_at DESC, id DESC') .limit(limit) diff --git a/app/models/application_model/can_assets.rb b/app/models/application_model/can_assets.rb index c66c563c7..802e6afd4 100644 --- a/app/models/application_model/can_assets.rb +++ b/app/models/application_model/can_assets.rb @@ -33,7 +33,7 @@ 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 do |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 ]) diff --git a/app/models/application_model/can_associations.rb b/app/models/application_model/can_associations.rb index 058087300..2a625f19e 100644 --- a/app/models/application_model/can_associations.rb +++ b/app/models/application_model/can_associations.rb @@ -109,7 +109,7 @@ returns return cache if cache attributes = self.attributes - relevant = %i(has_and_belongs_to_many has_many) + relevant = %i[has_and_belongs_to_many has_many] eager_load = [] pluck = [] keys = [] @@ -180,7 +180,7 @@ returns next if !item[:name] attributes[assoc.name.to_s].push item[:name] end - if ref.count.positive? && attributes[assoc.name.to_s].empty? + if ref.count.positive? && attributes[assoc.name.to_s].blank? attributes.delete(assoc.name.to_s) end next @@ -216,7 +216,7 @@ returns def filter_attributes(attributes) # remove forbitten attributes - %w(password token tokens token_ids).each do |item| + %w[password token tokens token_ids].each do |item| attributes.delete(item) end end @@ -237,7 +237,7 @@ returns def association_id_validation(attribute_id, value) return true if value.nil? - attributes.each do |key, _value| + attributes.each_key do |key| next if key != attribute_id # check if id is assigned @@ -339,16 +339,15 @@ returns class_object = assoc.klass lookup = nil if class_object == User - if value.instance_of?(String) - if !lookup - lookup = class_object.lookup(login: value) - end - if !lookup - lookup = class_object.lookup(email: value) - end - else + if !value.instance_of?(String) raise ArgumentError, "String is needed as ref value #{value.inspect} for '#{assoc_name}'" end + if !lookup + lookup = class_object.lookup(login: value) + end + if !lookup + lookup = class_object.lookup(email: value) + end else lookup = class_object.lookup(name: value) end @@ -367,7 +366,7 @@ returns end next if !value.instance_of?(Array) - next if value.empty? + next if value.blank? next if !value[0].instance_of?(String) # handle _ids values @@ -383,16 +382,15 @@ returns value.each do |item| lookup = nil if class_object == User - if item.instance_of?(String) - if !lookup - lookup = class_object.lookup(login: item) - end - if !lookup - lookup = class_object.lookup(email: item) - end - else + if !item.instance_of?(String) raise ArgumentError, "String is needed in array ref as ref value #{value.inspect} for '#{assoc_name}'" end + if !lookup + lookup = class_object.lookup(login: item) + end + if !lookup + lookup = class_object.lookup(email: item) + end else lookup = class_object.lookup(name: item) end diff --git a/app/models/application_model/can_cleanup_param.rb b/app/models/application_model/can_cleanup_param.rb index d6bc032e0..46b3f7999 100644 --- a/app/models/application_model/can_cleanup_param.rb +++ b/app/models/application_model/can_cleanup_param.rb @@ -43,7 +43,7 @@ returns # only use object attributes clean_params = {} - new.attributes.each do |attribute, _value| + new.attributes.each_key do |attribute| next if !data.key?(attribute.to_sym) # check reference records, referenced by _id attributes @@ -80,7 +80,7 @@ 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 do |key| + %i[action controller updated_at created_at updated_by_id created_by_id updated_by created_by].each do |key| data.delete(key) end diff --git a/app/models/application_model/can_creates_and_updates.rb b/app/models/application_model/can_creates_and_updates.rb index d31417821..34e7dd041 100644 --- a/app/models/application_model/can_creates_and_updates.rb +++ b/app/models/application_model/can_creates_and_updates.rb @@ -123,8 +123,8 @@ returns return record end record = new(data) - record.save - return record + record.save! + record elsif data[:name] # do lookup with == to handle case insensitive databases @@ -140,8 +140,8 @@ returns end end record = new(data) - record.save - return record + record.save! + record elsif data[:login] # do lookup with == to handle case insensitive databases @@ -157,8 +157,8 @@ returns end end record = new(data) - record.save - return record + record.save! + record elsif data[:email] # do lookup with == to handle case insensitive databases @@ -174,8 +174,8 @@ returns end end record = new(data) - record.save - return record + record.save! + record elsif data[:locale] # do lookup with == to handle case insensitive databases @@ -191,8 +191,8 @@ returns end end record = new(data) - record.save - return record + record.save! + record else raise ArgumentError, 'Need name, login, email or locale for create_or_update()' end diff --git a/app/models/application_model/can_touch_references.rb b/app/models/application_model/can_touch_references.rb index b73eeac6b..23eba980a 100644 --- a/app/models/application_model/can_touch_references.rb +++ b/app/models/application_model/can_touch_references.rb @@ -21,7 +21,7 @@ touch references by params object_class = Kernel.const_get(data[:object]) object = object_class.lookup(id: data[:o_id]) return if !object - object.touch + object.touch # rubocop:disable Rails/SkipsModelValidations rescue => e logger.error e end diff --git a/app/models/application_model/has_attachments.rb b/app/models/application_model/has_attachments.rb index c3ca0da15..eea4f1540 100644 --- a/app/models/application_model/has_attachments.rb +++ b/app/models/application_model/has_attachments.rb @@ -37,7 +37,7 @@ store attachments for this object self.attachments_buffer = attachments # update if object already exists - return if !(id && id.nonzero?) + return if !(id&.nonzero?) attachments_buffer_check end diff --git a/app/models/authorization.rb b/app/models/authorization.rb index ab0a2acdd..8e61d99b9 100644 --- a/app/models/authorization.rb +++ b/app/models/authorization.rb @@ -90,7 +90,7 @@ class Authorization < ApplicationModel def delete_user_cache return if !user - user.touch + user.touch # rubocop:disable Rails/SkipsModelValidations end end diff --git a/app/models/avatar.rb b/app/models/avatar.rb index 76456b1a7..3bc1a9984 100644 --- a/app/models/avatar.rb +++ b/app/models/avatar.rb @@ -105,16 +105,16 @@ add avatar by url # fetch image based on http url if data[:url].present? - if data[:url] =~ /^http/ + if data[:url].match?(/^http/) # check if source ist already updated within last 2 minutes - if avatar_already_exists && avatar_already_exists.source_url == data[:url] + if avatar_already_exists&.source_url == data[:url] return if avatar_already_exists.updated_at > 2.minutes.ago end # twitter workaround to get bigger avatar images # see also https://dev.twitter.com/overview/general/user-profile-images-and-banners - if data[:url] =~ %r{//pbs.twimg.com/}i + if data[:url].match?(%r{//pbs.twimg.com/}i) data[:url].sub!(/normal\.(png|jpg|gif)$/, 'bigger.\1') end @@ -134,10 +134,10 @@ add avatar by url end logger.info "Fetchd image '#{data[:url]}', http code: #{response.code}" mime_type = 'image' - if data[:url] =~ /\.png/i + if data[:url].match?(/\.png/i) mime_type = 'image/png' end - if data[:url] =~ /\.(jpg|jpeg)/i + if data[:url].match?(/\.(jpg|jpeg)/i) mime_type = 'image/jpeg' end if !data[:resize] @@ -150,10 +150,10 @@ add avatar by url data[:full][:mime_type] = mime_type # try zammad backend to find image based on email - elsif data[:url] =~ /@/ + elsif data[:url].match?(/@/) # check if source ist already updated within last 3 minutes - if avatar_already_exists && avatar_already_exists.source_url == data[:url] + if avatar_already_exists&.source_url == data[:url] return if avatar_already_exists.updated_at > 2.minutes.ago end @@ -170,8 +170,8 @@ add avatar by url # check if avatar need to be updated if data[:resize].present? && data[:resize][:content].present? record[:store_hash] = Digest::MD5.hexdigest(data[:resize][:content]) - if avatar_already_exists && avatar_already_exists.store_hash == record[:store_hash] - avatar_already_exists.touch + if avatar_already_exists&.store_hash == record[:store_hash] + avatar_already_exists.touch # rubocop:disable Rails/SkipsModelValidations return avatar_already_exists end end diff --git a/app/models/calendar.rb b/app/models/calendar.rb index 93a23fea1..9cd2a670a 100644 --- a/app/models/calendar.rb +++ b/app/models/calendar.rb @@ -83,11 +83,11 @@ returns =end def self.ical_feeds - data = YAML.load_file(Rails.root.join('config/holiday_calendars.yml')) + data = YAML.load_file(Rails.root.join('config', 'holiday_calendars.yml')) url = data['url'] data['countries'].map do |country, domain| - [(url % { domain: domain }), country] + [format(url, domain: domain), country] end.to_h end @@ -210,7 +210,7 @@ returns end def self.fetch_parse(location) - if location =~ /^http/i + if location.match?(/^http/i) result = UserAgent.get(location) if !result.success? raise result.error @@ -257,7 +257,7 @@ returns end # ignore daylight saving time entries - return if comment =~ /(daylight saving|sommerzeit|summertime)/i + return if comment.match?(/(daylight saving|sommerzeit|summertime)/i) [day, comment] end diff --git a/app/models/channel.rb b/app/models/channel.rb index d3c8a63c4..faf8752f4 100644 --- a/app/models/channel.rb +++ b/app/models/channel.rb @@ -50,7 +50,6 @@ fetch one account end begin - # we need to require each channel backend individually otherwise we get a # 'warning: toplevel constant Twitter referenced by Channel::Driver::Twitter' error e.g. # so we have to convert the channel name to the filename via Rails String.underscore @@ -94,7 +93,6 @@ stream instance of account adapter = options[:adapter] begin - # we need to require each channel backend individually otherwise we get a # 'warning: toplevel constant Twitter referenced by Channel::Driver::Twitter' error e.g. # so we have to convert the channel name to the filename via Rails String.underscore @@ -264,7 +262,6 @@ send via account result = nil begin - # we need to require each channel backend individually otherwise we get a # 'warning: toplevel constant Twitter referenced by Channel::Driver::Twitter' error e.g. # so we have to convert the channel name to the filename via Rails String.underscore diff --git a/app/models/channel/assets.rb b/app/models/channel/assets.rb index 46c044fbd..f6f7af0b3 100644 --- a/app/models/channel/assets.rb +++ b/app/models/channel/assets.rb @@ -40,7 +40,7 @@ returns end end if !access - %w(inbound outbound).each do |key| + %w[inbound outbound].each do |key| if attributes['options'] && attributes['options'][key] && attributes['options'][key]['options'] attributes['options'][key]['options'].delete('password') end @@ -51,7 +51,7 @@ returns end return data if !self['created_by_id'] && !self['updated_by_id'] - %w(created_by_id updated_by_id).each do |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 ]) diff --git a/app/models/channel/driver/facebook.rb b/app/models/channel/driver/facebook.rb index 3d46638e6..75809da88 100644 --- a/app/models/channel/driver/facebook.rb +++ b/app/models/channel/driver/facebook.rb @@ -60,8 +60,7 @@ class Channel::Driver::Facebook true end - def disconnect - end + def disconnect; end =begin diff --git a/app/models/channel/driver/imap.rb b/app/models/channel/driver/imap.rb index 5a609f957..8986753ab 100644 --- a/app/models/channel/driver/imap.rb +++ b/app/models/channel/driver/imap.rb @@ -104,7 +104,7 @@ example # sort messages by date on server (if not supported), if not fetch messages via search (first in, first out) filter = ['ALL'] if keep_on_server && check_type != 'check' && check_type != 'verify' - filter = %w(NOT SEEN) + filter = %w[NOT SEEN] end begin message_ids = @imap.sort(['DATE'], filter, 'US-ASCII') @@ -254,7 +254,7 @@ returns # verify if message is already imported via same channel, if not, import it again ticket = article.ticket - if ticket && ticket.preferences && ticket.preferences[:channel_id].present? && channel.present? + if ticket&.preferences && ticket.preferences[:channel_id].present? && channel.present? return false if ticket.preferences[:channel_id] != channel[:id] end diff --git a/app/models/channel/driver/smtp.rb b/app/models/channel/driver/smtp.rb index d678a40f0..27beb797d 100644 --- a/app/models/channel/driver/smtp.rb +++ b/app/models/channel/driver/smtp.rb @@ -27,7 +27,7 @@ class Channel::Driver::Smtp return if Setting.get('import_mode') # set smtp defaults - if !options.key?(:port) || options[:port].empty? + if !options.key?(:port) || options[:port].blank? options[:port] = 25 end if !options.key?(:ssl) diff --git a/app/models/channel/driver/twitter.rb b/app/models/channel/driver/twitter.rb index 97d72734f..406f9a9f8 100644 --- a/app/models/channel/driver/twitter.rb +++ b/app/models/channel/driver/twitter.rb @@ -119,8 +119,8 @@ returns end def disconnect - @stream_client.disconnect if @stream_client - @rest_client.disconnect if @rest_client + @stream_client&.disconnect + @rest_client&.disconnect end =begin @@ -203,12 +203,11 @@ returns stream_start rescue Twitter::Error::Unauthorized => e Rails.logger.info "Unable to stream, try #{loop_count}, error #{e.inspect}" - if loop_count < 2 - Rails.logger.info "wait for #{sleep_on_unauthorized} sec. and try it again" - sleep sleep_on_unauthorized - else + if loop_count >= 2 raise "Unable to stream, try #{loop_count}, error #{e.inspect}" end + Rails.logger.info "wait for #{sleep_on_unauthorized} sec. and try it again" + sleep sleep_on_unauthorized end end end @@ -233,7 +232,7 @@ returns filter[:replies] = 'all' end - return if filter.empty? + return if filter.blank? @stream_client.client.user(filter) do |tweet| next if tweet.class != Twitter::Tweet && tweet.class != Twitter::DirectMessage @@ -258,11 +257,9 @@ returns # check if it's mention if sync['mentions'] && sync['mentions']['group_id'].present? hit = false - if tweet.user_mentions - tweet.user_mentions.each do |user| - if user.id.to_s == @channel.options['user']['id'].to_s - hit = true - end + tweet.user_mentions&.each do |user| + if user.id.to_s == @channel.options['user']['id'].to_s + hit = true end end if hit @@ -299,7 +296,7 @@ returns next if item['term'].blank? next if item['term'] == '#' next if item['group_id'].blank? - if body =~ /#{item['term']}/ + if body.match?(/#{item['term']}/) hit = item end end diff --git a/app/models/channel/email_build.rb b/app/models/channel/email_build.rb index b0692648f..ae8f12959 100644 --- a/app/models/channel/email_build.rb +++ b/app/models/channel/email_build.rb @@ -69,7 +69,7 @@ module Channel::EmailBuild end # build email without any attachments - if !html_alternative && ( !attr[:attachments] || attr[:attachments].empty? ) + if !html_alternative && attr[:attachments].blank? mail.content_type 'text/plain; charset=UTF-8' mail.body attr[:body] return mail @@ -84,19 +84,17 @@ module Channel::EmailBuild html_container.add_part html_alternative # place to add inline attachments related to html alternative - if attr[:attachments] - attr[:attachments].each do |attachment| - next if attachment.class == Hash - next if attachment.preferences['Content-ID'].empty? - attachment = Mail::Part.new do - content_type attachment.preferences['Content-Type'] - content_id "<#{attachment.preferences['Content-ID']}>" - content_disposition attachment.preferences['Content-Disposition'] || 'inline' - content_transfer_encoding 'binary' - body attachment.content.force_encoding('BINARY') - end - html_container.add_part attachment + attr[:attachments]&.each do |attachment| + next if attachment.class == Hash + next if attachment.preferences['Content-ID'].blank? + attachment = Mail::Part.new do + content_type attachment.preferences['Content-Type'] + content_id "<#{attachment.preferences['Content-ID']}>" + content_disposition attachment.preferences['Content-Disposition'] || 'inline' + content_transfer_encoding 'binary' + body attachment.content.force_encoding('BINARY') end + html_container.add_part attachment end alternative_bodies.add_part html_container end @@ -104,23 +102,21 @@ module Channel::EmailBuild mail.add_part alternative_bodies # add attachments - if attr[:attachments] - attr[:attachments].each do |attachment| - if attachment.class == Hash - attachment['content-id'] = nil - mail.attachments[ attachment[:filename] ] = attachment - else - next if !attachment.preferences['Content-ID'].empty? - filename = attachment.filename - encoded_filename = Mail::Encodings.decode_encode filename, :encode - disposition = attachment.preferences['Content-Disposition'] || 'attachment' - content_type = attachment.preferences['Content-Type'] || 'application/octet-stream' - mail.attachments[attachment.filename] = { - content_disposition: "#{disposition}; filename=\"#{encoded_filename}\"", - content_type: "#{content_type}; filename=\"#{encoded_filename}\"", - content: attachment.content - } - end + attr[:attachments]&.each do |attachment| + if attachment.class == Hash + attachment['content-id'] = nil + mail.attachments[ attachment[:filename] ] = attachment + else + next if attachment.preferences['Content-ID'].present? + filename = attachment.filename + encoded_filename = Mail::Encodings.decode_encode filename, :encode + disposition = attachment.preferences['Content-Disposition'] || 'attachment' + content_type = attachment.preferences['Content-Type'] || 'application/octet-stream' + mail.attachments[attachment.filename] = { + content_disposition: "#{disposition}; filename=\"#{encoded_filename}\"", + content_type: "#{content_type}; filename=\"#{encoded_filename}\"", + content: attachment.content + } end end mail @@ -137,7 +133,7 @@ returns =end def self.recipient_line(realname, email) - return "#{realname} <#{email}>" if realname =~ /^[A-z]+$/i + return "#{realname} <#{email}>" if realname.match?(/^[A-z]+$/i) "\"#{realname.gsub('"', '\"')}\" <#{email}>" end @@ -154,7 +150,7 @@ Check if string is a complete html document. If not, add head and css styles. # apply mail client fixes html = Channel::EmailBuild.html_mail_client_fixes(html) - return html if html =~ //i + return html if html.match?(//i) # use block form because variable html could contain backslashes and e. g. '\1' that # must not be handled as back-references for regular expressions diff --git a/app/models/channel/email_parser.rb b/app/models/channel/email_parser.rb index 9496572dd..b4092f593 100644 --- a/app/models/channel/email_parser.rb +++ b/app/models/channel/email_parser.rb @@ -94,7 +94,7 @@ class Channel::EmailParser # verify content, ignore recipients with non email address ['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] =~ /@/ + next if data[field.to_sym].match?(/@/) data[field.to_sym] = '' end @@ -146,7 +146,7 @@ class Channel::EmailParser if mail.multipart? # html attachment/body may exists and will be converted to strict html - if mail.html_part && mail.html_part.body + if mail.html_part&.body data[:body] = mail.html_part.body.to_s data[:body] = Encode.conv(mail.html_part.charset.to_s, data[:body]) data[:body] = data[:body].html2html_strict.to_s.force_encoding('utf-8') @@ -196,17 +196,15 @@ class Channel::EmailParser end # get attachments - if mail.parts - mail.parts.each do |part| + mail.parts&.each do |part| - # protect process to work fine with spam emails, see test/fixtures/mail15.box - begin - attachs = _get_attachment(part, data[:attachments], mail) - data[:attachments].concat(attachs) - rescue - attachs = _get_attachment(part, data[:attachments], mail) - data[:attachments].concat(attachs) - end + # protect process to work fine with spam emails, see test/fixtures/mail15.box + begin + attachs = _get_attachment(part, data[:attachments], mail) + data[:attachments].concat(attachs) + rescue + attachs = _get_attachment(part, data[:attachments], mail) + data[:attachments].concat(attachs) end end @@ -306,10 +304,10 @@ class Channel::EmailParser end # ignore text/plain attachments - already shown in view - return [] if mail.text_part && mail.text_part.body.to_s == file.body.to_s + return [] if mail.text_part&.body.to_s == file.body.to_s # ignore text/html - html part, already shown in view - return [] if mail.html_part && mail.html_part.body.to_s == file.body.to_s + return [] if mail.html_part&.body.to_s == file.body.to_s # get file preferences headers_store = {} @@ -376,7 +374,7 @@ class Channel::EmailParser # generate file name based on content type if filename.blank? && headers_store['Content-Type'].present? - if headers_store['Content-Type'] =~ %r{^message/rfc822}i + if headers_store['Content-Type'].match?(%r{^message/rfc822}i) begin parser = Channel::EmailParser.new mail_local = parser.parse(file.body.to_s) @@ -406,13 +404,13 @@ class Channel::EmailParser if filename.blank? map = { 'message/delivery-status': ['txt', 'delivery-status'], - 'text/plain': %w(txt document), - 'text/html': %w(html document), - 'video/quicktime': %w(mov video), - 'image/jpeg': %w(jpg image), - 'image/jpg': %w(jpg image), - 'image/png': %w(png image), - 'image/gif': %w(gif image), + 'text/plain': %w[txt document], + 'text/html': %w[html document], + 'video/quicktime': %w[mov video], + 'image/jpeg': %w[jpg image], + 'image/jpg': %w[jpg image], + 'image/png': %w[png image], + 'image/gif': %w[gif image], } map.each do |type, ext| next if headers_store['Content-Type'] !~ /^#{Regexp.quote(type)}/i @@ -454,12 +452,12 @@ class Channel::EmailParser end # get mime type - if file.header[:content_type] && file.header[:content_type].string + if file.header[:content_type]&.string headers_store['Mime-Type'] = file.header[:content_type].string end # get charset - if file.header && file.header.charset + if file.header&.charset headers_store['Charset'] = file.header.charset end @@ -503,9 +501,8 @@ returns _process(channel, msg) rescue => e - # store unprocessable email for bug reporting - path = "#{Rails.root}/tmp/unprocessable_mail/" + path = Rails.root.join('tmp', 'unprocessable_mail') FileUtils.mkpath path md5 = Digest::MD5.hexdigest(msg) filename = "#{path}/#{md5}.eml" @@ -532,7 +529,7 @@ returns Setting.where(area: 'Postmaster::PreFilter').order(:name).each do |setting| filters[setting.name] = Kernel.const_get(Setting.get(setting.name)) end - filters.each do |_prio, backend| + filters.each_value do |backend| Rails.logger.debug "run postmaster pre filter #{backend}" begin backend.run(channel, mail) @@ -663,16 +660,14 @@ returns article.save_as_raw(msg) # store attachments - if mail[:attachments] - mail[:attachments].each do |attachment| - Store.add( - object: 'Ticket::Article', - o_id: article.id, - data: attachment[:data], - filename: attachment[:filename], - preferences: attachment[:preferences] - ) - end + mail[:attachments]&.each do |attachment| + Store.add( + object: 'Ticket::Article', + o_id: article.id, + data: attachment[:data], + filename: attachment[:filename], + preferences: attachment[:preferences] + ) end end end @@ -682,7 +677,7 @@ returns Setting.where(area: 'Postmaster::PostFilter').order(:name).each do |setting| filters[setting.name] = Kernel.const_get(Setting.get(setting.name)) end - filters.each do |_prio, backend| + filters.each_value do |backend| Rails.logger.debug "run postmaster post filter #{backend}" begin backend.run(channel, mail, ticket, article, session_user) @@ -765,7 +760,7 @@ returns def set_attributes_by_x_headers(item_object, header_name, mail, suffix = false) # loop all x-zammad-header-* headers - item_object.attributes.each do |key, _value| + item_object.attributes.each_key do |key| # ignore read only attributes next if key == 'updated_by_id' @@ -862,9 +857,9 @@ module Mail .+?(?=\=\?|$) # Plain String )/xmi).map do |matches| string, method = *matches - if method == 'b' || method == 'B' + if method == 'b' || method == 'B' # rubocop:disable Style/MultipleComparison b_value_decode(string) - elsif method == 'q' || method == 'Q' + elsif method == 'q' || method == 'Q' # rubocop:disable Style/MultipleComparison q_value_decode(string) else string diff --git a/app/models/channel/filter/auto_response_check.rb b/app/models/channel/filter/auto_response_check.rb index 588094802..ed7be0c86 100644 --- a/app/models/channel/filter/auto_response_check.rb +++ b/app/models/channel/filter/auto_response_check.rb @@ -25,7 +25,7 @@ module Channel::Filter::AutoResponseCheck message_id = mail[ 'message_id'.to_sym ] if message_id fqdn = Setting.get('fqdn') - return if message_id =~ /@#{Regexp.quote(fqdn)}/i + return if message_id.match?(/@#{Regexp.quote(fqdn)}/i) end mail[ 'x-zammad-send-auto-response'.to_sym ] = true diff --git a/app/models/channel/filter/bounce_delivery_permanent_failed.rb b/app/models/channel/filter/bounce_delivery_permanent_failed.rb index b7b535f90..7def43640 100644 --- a/app/models/channel/filter/bounce_delivery_permanent_failed.rb +++ b/app/models/channel/filter/bounce_delivery_permanent_failed.rb @@ -28,7 +28,7 @@ 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 do |line| + %w[to cc].each do |line| next if article[line].blank? recipients = [] begin diff --git a/app/models/channel/filter/follow_up_check.rb b/app/models/channel/filter/follow_up_check.rb index 179978187..739f69df1 100644 --- a/app/models/channel/filter/follow_up_check.rb +++ b/app/models/channel/filter/follow_up_check.rb @@ -104,5 +104,6 @@ module Channel::Filter::FollowUpCheck end end + true end end diff --git a/app/models/channel/filter/identify_sender.rb b/app/models/channel/filter/identify_sender.rb index 94cfd6139..1b67d1709 100644 --- a/app/models/channel/filter/identify_sender.rb +++ b/app/models/channel/filter/identify_sender.rb @@ -30,7 +30,7 @@ module Channel::Filter::IdentifySender # get first recipient and set customer begin to = 'raw-to'.to_sym - if mail[to] && mail[to].addrs + if mail[to]&.addrs items = mail[to].addrs items.each do |item| @@ -83,6 +83,8 @@ module Channel::Filter::IdentifySender if session_user mail[ 'x-zammad-session-user-id'.to_sym ] = session_user.id end + + true end # create to and cc user @@ -159,7 +161,7 @@ module Channel::Filter::IdentifySender role_ids = Role.signup_role_ids # fillup - %w(firstname lastname).each do |item| + %w[firstname lastname].each do |item| if data[item.to_sym].nil? data[item.to_sym] = '' end diff --git a/app/models/channel/filter/match/email_regex.rb b/app/models/channel/filter/match/email_regex.rb index 185f48be0..cf5dead02 100644 --- a/app/models/channel/filter/match/email_regex.rb +++ b/app/models/channel/filter/match/email_regex.rb @@ -9,12 +9,12 @@ module Channel::Filter::Match::EmailRegex if regexp == false match_rule_quoted = Regexp.quote(match_rule).gsub(/\\\*/, '.*') - return true if value =~ /#{match_rule_quoted}/i + return true if value.match?(/#{match_rule_quoted}/i) return false end begin - return true if value =~ /#{match_rule}/i + return true if value.match?(/#{match_rule}/i) return false rescue => e message = "Can't use regex '#{match_rule}' on '#{value}': #{e.message}" diff --git a/app/models/channel/filter/monitoring_base.rb b/app/models/channel/filter/monitoring_base.rb index 9ab171bc1..c7304fa8d 100644 --- a/app/models/channel/filter/monitoring_base.rb +++ b/app/models/channel/filter/monitoring_base.rb @@ -36,9 +36,7 @@ class Channel::Filter::MonitoringBase key = key.downcase end value = $2 - if value - value.strip! - end + value&.strip! result[key] = value end @@ -70,9 +68,9 @@ class Channel::Filter::MonitoringBase # possible event types https://mmonit.com/monit/documentation/#Setting-an-event-filter if result['state'].blank? - result['state'] = if mail[:body] =~ /\s(done|recovery|succeeded|bytes\sok|packets\sok)\s/ + result['state'] = if mail[:body].match?(/\s(done|recovery|succeeded|bytes\sok|packets\sok)\s/) 'OK' - elsif mail[:body] =~ /(instance\schanged\snot|Link\sup|Exists|Saturation\sok|Speed\sok)/ + elsif mail[:body].match?(/(instance\schanged\snot|Link\sup|Exists|Saturation\sok|Speed\sok)/) 'OK' else 'CRITICAL' @@ -132,5 +130,6 @@ class Channel::Filter::MonitoringBase return true end + true end end diff --git a/app/models/channel/filter/out_of_office_check.rb b/app/models/channel/filter/out_of_office_check.rb index 089ec785d..bed49ef9e 100644 --- a/app/models/channel/filter/out_of_office_check.rb +++ b/app/models/channel/filter/out_of_office_check.rb @@ -18,12 +18,12 @@ module Channel::Filter::OutOfOfficeCheck if mail[ 'auto-submitted'.to_sym ] # check zimbra out of office characteristics - if mail[ 'auto-submitted'.to_sym ] =~ /vacation/i + if mail[ 'auto-submitted'.to_sym ].match?(/vacation/i) mail[ 'x-zammad-out-of-office'.to_sym ] = true end # check cloud out of office characteristics - if mail[ 'auto-submitted'.to_sym ] =~ /auto-replied;\sowner-email=/i + if mail[ 'auto-submitted'.to_sym ].match?(/auto-replied;\sowner-email=/i) mail[ 'x-zammad-out-of-office'.to_sym ] = true end @@ -35,6 +35,7 @@ module Channel::Filter::OutOfOfficeCheck return end + true end end diff --git a/app/models/channel/filter/trusted.rb b/app/models/channel/filter/trusted.rb index 812c4ac68..e118dc3da 100644 --- a/app/models/channel/filter/trusted.rb +++ b/app/models/channel/filter/trusted.rb @@ -7,7 +7,7 @@ module Channel::Filter::Trusted # check if trust x-headers if !channel[:trusted] - mail.each do |key, _value| + mail.each_key do |key| next if key !~ /^x-zammad/i mail.delete(key) end diff --git a/app/models/chat.rb b/app/models/chat.rb index f1736329a..858cd76b4 100644 --- a/app/models/chat.rb +++ b/app/models/chat.rb @@ -9,7 +9,7 @@ class Chat < ApplicationModel # reconnect if session_id - chat_session = Chat::Session.find_by(session_id: session_id, state: %w(waiting running)) + chat_session = Chat::Session.find_by(session_id: session_id, state: %w[waiting running]) if chat_session if chat_session.state == 'running' @@ -126,7 +126,7 @@ class Chat < ApplicationModel end def self.active_chat_count - Chat::Session.where(state: %w(waiting running)).count + Chat::Session.where(state: %w[waiting running]).count end def self.available_agents(diff = 2.minutes) @@ -153,7 +153,7 @@ class Chat < ApplicationModel def self.seads_total(diff = 2.minutes) total = 0 - available_agents(diff).each do |_user_id, concurrent| + available_agents(diff).each_value do |concurrent| total += concurrent end total diff --git a/app/models/chat/agent.rb b/app/models/chat/agent.rb index 99ea9be48..fdcd1ff12 100644 --- a/app/models/chat/agent.rb +++ b/app/models/chat/agent.rb @@ -5,7 +5,7 @@ class Chat::Agent < ApplicationModel end def active_chat_count - Chat::Session.where(state: %w(waiting running), user_id: updated_by_id).count + Chat::Session.where(state: %w[waiting running], user_id: updated_by_id).count end def self.state(user_id, state = nil) diff --git a/app/models/concerns/can_seed.rb b/app/models/concerns/can_seed.rb index 89fd7d879..6b51f3e1a 100644 --- a/app/models/concerns/can_seed.rb +++ b/app/models/concerns/can_seed.rb @@ -17,7 +17,7 @@ module CanSeed end def seedfile - "#{Rails.root}/db/seeds/#{name.pluralize.underscore.tr('/', '_')}.rb" + Rails.root.join('db', 'seeds', "#{name.pluralize.underscore.tr('/', '_')}.rb").to_s end end end diff --git a/app/models/concerns/has_activity_stream_log.rb b/app/models/concerns/has_activity_stream_log.rb index a4a4cdee6..f07b872d0 100644 --- a/app/models/concerns/has_activity_stream_log.rb +++ b/app/models/concerns/has_activity_stream_log.rb @@ -35,12 +35,11 @@ log object update activity stream, if configured - will be executed automaticall return true if !saved_changes? ignored_attributes = self.class.instance_variable_get(:@activity_stream_attributes_ignored) || [] - ignored_attributes += %i(created_at updated_at created_by_id updated_by_id) + ignored_attributes += %i[created_at updated_at created_by_id updated_by_id] log = false - saved_changes.each do |key, _value| + saved_changes.each_key do |key| next if ignored_attributes.include?(key.to_sym) - log = true end return true if !log diff --git a/app/models/concerns/has_history.rb b/app/models/concerns/has_history.rb index a351fe16b..543550aab 100644 --- a/app/models/concerns/has_history.rb +++ b/app/models/concerns/has_history.rb @@ -40,11 +40,9 @@ 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 do |key, value| - if changes.key?(key) && changes[key] == value - changes.delete(key) - end + history_changes_last_done&.each do |key, value| + if changes.key?(key) && changes[key] == value + changes.delete(key) end end self.history_changes_last_done = changes @@ -53,7 +51,7 @@ log object update history with all updated attributes, if configured - will be e return if changes['id'] && !changes['id'][0] ignored_attributes = self.class.instance_variable_get(:@history_attributes_ignored) || [] - ignored_attributes += %i(created_at updated_at created_by_id updated_by_id) + ignored_attributes += %i[created_at updated_at created_by_id updated_by_id] changes.each do |key, value| diff --git a/app/models/concerns/has_search_index_backend.rb b/app/models/concerns/has_search_index_backend.rb index 7e4bb998b..283928e9b 100644 --- a/app/models/concerns/has_search_index_backend.rb +++ b/app/models/concerns/has_search_index_backend.rb @@ -84,7 +84,7 @@ returns def search_index_data attributes = {} - %w(name note).each do |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] diff --git a/app/models/cti/caller_id.rb b/app/models/cti/caller_id.rb index ad8930044..caf7beea6 100644 --- a/app/models/cti/caller_id.rb +++ b/app/models/cti/caller_id.rb @@ -108,11 +108,11 @@ returns # get caller ids caller_ids = [] attributes = record.attributes - attributes.each do |_attribute, value| + attributes.each_value do |value| next if value.class != String - next if value.empty? + next if value.blank? local_caller_ids = Cti::CallerId.extract_numbers(value) - next if local_caller_ids.empty? + next if local_caller_ids.blank? caller_ids = caller_ids.concat(local_caller_ids) end @@ -233,23 +233,23 @@ returns if user comment += user.fullname end - elsif !record.comment.empty? + elsif record.comment.present? comment += record.comment end if record.level == 'known' - if !from_comment_known.empty? + if from_comment_known.present? from_comment_known += ',' end from_comment_known += comment else - if !from_comment_maybe.empty? + if from_comment_maybe.present? from_comment_maybe += ',' 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? + return [from_comment_known, preferences_known] if from_comment_known.present? + return ["maybe #{from_comment_maybe}", preferences_maybe] if from_comment_maybe.present? nil end diff --git a/app/models/cti/log.rb b/app/models/cti/log.rb index 4f03057b4..9b043207f 100644 --- a/app/models/cti/log.rb +++ b/app/models/cti/log.rb @@ -249,7 +249,7 @@ returns assets = {} list.each do |item| next if !item.preferences - %w(from to).each do |direction| + %w[from to].each do |direction| next if !item.preferences[direction] item.preferences[direction].each do |caller_id| next if !caller_id['user_id'] diff --git a/app/models/email_address.rb b/app/models/email_address.rb index dc2affea8..0441f4431 100644 --- a/app/models/email_address.rb +++ b/app/models/email_address.rb @@ -47,7 +47,7 @@ check and if channel not exists reset configured channels for email addresses return true if email.blank? self.email = email.downcase.strip raise Exceptions::UnprocessableEntity, 'Invalid email' if email !~ /@/ - raise Exceptions::UnprocessableEntity, 'Invalid email' if email =~ /\s/ + raise Exceptions::UnprocessableEntity, 'Invalid email' if email.match?(/\s/) true end diff --git a/app/models/external_sync.rb b/app/models/external_sync.rb index b43bbe5c5..1eff33857 100644 --- a/app/models/external_sync.rb +++ b/app/models/external_sync.rb @@ -68,7 +68,7 @@ class ExternalSync < ApplicationModel break if !value storable = value.class.ancestors.any? do |ancestor| - %w(String Integer Float Bool Array).include?(ancestor.to_s) + %w[String Integer Float Bool Array].include?(ancestor.to_s) end if storable diff --git a/app/models/job.rb b/app/models/job.rb index 9d5b422a1..027a1de35 100644 --- a/app/models/job.rb +++ b/app/models/job.rb @@ -78,11 +78,9 @@ job.run(true) self.running = true save! - if tickets - tickets.each do |ticket| - Transaction.execute(disable_notification: disable_notification, reset_user_id: true) do - ticket.perform_changes(perform, 'job') - end + tickets&.each do |ticket| + Transaction.execute(disable_notification: disable_notification, reset_user_id: true) do + ticket.perform_changes(perform, 'job') end end diff --git a/app/models/job/assets.rb b/app/models/job/assets.rb index fbfd4a15f..3e0c0a656 100644 --- a/app/models/job/assets.rb +++ b/app/models/job/assets.rb @@ -36,7 +36,7 @@ returns data = assets_of_selector('condition', data) data = assets_of_selector('perform', data) end - %w(created_by_id updated_by_id).each do |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 ]) diff --git a/app/models/locale.rb b/app/models/locale.rb index fa597f189..e183cd904 100644 --- a/app/models/locale.rb +++ b/app/models/locale.rb @@ -71,7 +71,7 @@ all: def self.load_from_file version = Version.get - file = Rails.root.join("config/locales-#{version}.yml") + file = Rails.root.join('config', "locales-#{version}.yml") return false if !File.exist?(file) data = YAML.load_file(file) to_database(data) @@ -107,7 +107,7 @@ all: raise "Can't load locales from #{url}" if !result raise "Can't load locales from #{url}: #{result.error}" if !result.success? - file = Rails.root.join("config/locales-#{version}.yml") + file = Rails.root.join('config', "locales-#{version}.yml") File.open(file, 'w') do |out| YAML.dump(result.data, out) end diff --git a/app/models/object_manager.rb b/app/models/object_manager.rb index e6d1b5f5a..306122924 100644 --- a/app/models/object_manager.rb +++ b/app/models/object_manager.rb @@ -11,7 +11,7 @@ list all backend managed object =end def self.list_objects - %w(Ticket TicketArticle User Organization Group) + %w[Ticket TicketArticle User Organization Group] end =begin @@ -23,7 +23,7 @@ list all frontend managed object =end def self.list_frontend_objects - %w(Ticket User Organization Group) + %w[Ticket User Organization Group] end end diff --git a/app/models/object_manager/attribute.rb b/app/models/object_manager/attribute.rb index 97183e5c1..56ae893ed 100644 --- a/app/models/object_manager/attribute.rb +++ b/app/models/object_manager/attribute.rb @@ -279,7 +279,7 @@ possible types # if data_option has changed, store it for next migration if !force - [:name, :display, :data_type, :position, :active].each do |key| + %i[name display data_type position active].each do |key| next if record[key] == data[key] data[:to_config] = true break @@ -441,7 +441,7 @@ returns: tag: item.data_type, #:null => item.null, } - if item.data_option[:permission] && item.data_option[:permission].any? + if item.data_option[:permission]&.any? next if !user hint = false item.data_option[:permission].each do |permission| @@ -459,7 +459,7 @@ returns: permission_options.each do |permission, options| if permission == '-all-' data[:screen][screen] = options - elsif user && user.permissions?(permission) + elsif user&.permissions?(permission) data[:screen][screen] = options end end @@ -535,7 +535,7 @@ returns =end def self.pending_migration? - return false if migrations.empty? + return false if migrations.blank? true end @@ -601,21 +601,21 @@ to send no browser reload event, pass false end data_type = nil - if attribute.data_type =~ /^input|select|tree_select|richtext|textarea|checkbox$/ + if attribute.data_type.match?(/^input|select|tree_select|richtext|textarea|checkbox$/) data_type = :string - elsif attribute.data_type =~ /^integer|user_autocompletion$/ + elsif attribute.data_type.match?(/^integer|user_autocompletion$/) data_type = :integer - elsif attribute.data_type =~ /^boolean|active$/ + elsif attribute.data_type.match?(/^boolean|active$/) data_type = :boolean - elsif attribute.data_type =~ /^datetime$/ + elsif attribute.data_type.match?(/^datetime$/) data_type = :datetime - elsif attribute.data_type =~ /^date$/ + elsif attribute.data_type.match?(/^date$/) data_type = :date end # change field if model.column_names.include?(attribute.name) - if attribute.data_type =~ /^input|select|tree_select|richtext|textarea|checkbox$/ + if attribute.data_type.match?(/^input|select|tree_select|richtext|textarea|checkbox$/) ActiveRecord::Migration.change_column( model.table_name, attribute.name, @@ -623,7 +623,7 @@ to send no browser reload event, pass false limit: attribute.data_option[:maxlength], null: true ) - elsif attribute.data_type =~ /^integer|user_autocompletion|datetime|date$/ + elsif attribute.data_type.match?(/^integer|user_autocompletion|datetime|date$/) ActiveRecord::Migration.change_column( model.table_name, attribute.name, @@ -631,7 +631,7 @@ to send no browser reload event, pass false default: attribute.data_option[:default], null: true ) - elsif attribute.data_type =~ /^boolean|active$/ + elsif attribute.data_type.match?(/^boolean|active$/) ActiveRecord::Migration.change_column( model.table_name, attribute.name, @@ -654,7 +654,7 @@ to send no browser reload event, pass false end # create field - if attribute.data_type =~ /^input|select|tree_select|richtext|textarea|checkbox$/ + if attribute.data_type.match?(/^input|select|tree_select|richtext|textarea|checkbox$/) ActiveRecord::Migration.add_column( model.table_name, attribute.name, @@ -662,7 +662,7 @@ to send no browser reload event, pass false limit: attribute.data_option[:maxlength], null: true ) - elsif attribute.data_type =~ /^integer|user_autocompletion$/ + elsif attribute.data_type.match?(/^integer|user_autocompletion$/) ActiveRecord::Migration.add_column( model.table_name, attribute.name, @@ -670,7 +670,7 @@ to send no browser reload event, pass false default: attribute.data_option[:default], null: true ) - elsif attribute.data_type =~ /^boolean|active$/ + elsif attribute.data_type.match?(/^boolean|active$/) ActiveRecord::Migration.add_column( model.table_name, attribute.name, @@ -678,7 +678,7 @@ to send no browser reload event, pass false default: attribute.data_option[:default], null: true ) - elsif attribute.data_type =~ /^datetime|date$/ + elsif attribute.data_type.match?(/^datetime|date$/) ActiveRecord::Migration.add_column( model.table_name, attribute.name, @@ -727,26 +727,20 @@ to send no browser reload event, pass false def check_name return if !name - if name =~ /_(id|ids)$/i || name =~ /^id$/i - raise 'Name can\'t get used, *_id and *_ids are not allowed' - elsif name =~ /\s/ - raise 'Spaces in name are not allowed' - elsif name !~ /^[a-z0-9_]+$/ - raise 'Only letters from a-z, numbers from 0-9, and _ are allowed' - elsif name !~ /[a-z]/ - raise 'At least one letters is needed' - elsif name =~ /^(destroy|true|false|integer|select|drop|create|alter|index|table|varchar|blob|date|datetime|timestamp)$/ - raise "#{name} is a reserved word, please choose a different one" + + raise 'Name can\'t get used, *_id and *_ids are not allowed' if name.match?(/_(id|ids)$/i) || name.match?(/^id$/i) + raise 'Spaces in name are not allowed' if name.match?(/\s/) + raise 'Only letters from a-z, numbers from 0-9, and _ are allowed' if !name.match?(/^[a-z0-9_]+$/) + raise 'At least one letters is needed' if !name.match?(/[a-z]/) # do not allow model method names as attributes - else - model = Kernel.const_get(object_lookup.name) - record = model.new - if record.respond_to?(name.to_sym) && !record.attributes.key?(name) - raise "#{name} is a reserved word, please choose a different one" - end - end - true + reserved_words = %w[destroy true false integer select drop create alter index table varchar blob date datetime timestamp] + raise "#{name} is a reserved word, please choose a different one" if name.match?(/^(#{reserved_words.join('|')})$/) + + record = object_lookup.name.constantize.new + return true if !record.respond_to?(name.to_sym) + return true if record.attributes.key?(name) + raise "#{name} is a reserved word, please choose a different one" end def check_editable @@ -783,7 +777,7 @@ to send no browser reload event, pass false end if data_type == 'integer' - [:min, :max].each do |item| + %i[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 @@ -817,6 +811,7 @@ to send no browser reload event, pass false raise 'Need data_option[:diff] param in days' if data_option[:diff].nil? end + true end end diff --git a/app/models/observer/chat/leave/background_job.rb b/app/models/observer/chat/leave/background_job.rb index 1e9eb9a15..1a681eb38 100644 --- a/app/models/observer/chat/leave/background_job.rb +++ b/app/models/observer/chat/leave/background_job.rb @@ -1,5 +1,3 @@ -# encoding: utf-8 - class Observer::Chat::Leave::BackgroundJob def initialize(chat_session_id, client_id, session) @chat_session_id = chat_session_id diff --git a/app/models/observer/organization/ref_object_touch.rb b/app/models/observer/organization/ref_object_touch.rb index 3571ae50b..c5e934d29 100644 --- a/app/models/observer/organization/ref_object_touch.rb +++ b/app/models/observer/organization/ref_object_touch.rb @@ -27,7 +27,7 @@ class Observer::Organization::RefObjectTouch < ActiveRecord::Observer 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 + ticket.touch # rubocop:disable Rails/SkipsModelValidations end end @@ -35,7 +35,7 @@ class Observer::Organization::RefObjectTouch < ActiveRecord::Observer 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 + user.touch # rubocop:disable Rails/SkipsModelValidations end end true diff --git a/app/models/observer/sla/ticket_rebuild_escalation.rb b/app/models/observer/sla/ticket_rebuild_escalation.rb index 37503fc11..761dfd10e 100644 --- a/app/models/observer/sla/ticket_rebuild_escalation.rb +++ b/app/models/observer/sla/ticket_rebuild_escalation.rb @@ -33,9 +33,9 @@ class Observer::Sla::TicketRebuildEscalation < ActiveRecord::Observer changed = false fields_to_check = nil fields_to_check = if record.class == Sla - %w(condition calendar_id first_response_time update_time solution_time) + %w[condition calendar_id first_response_time update_time solution_time] else - %w(timezone business_hours default ical_url public_holidays) + %w[timezone business_hours default ical_url public_holidays] end fields_to_check.each do |item| next if !record.saved_change_to_attribute(item) diff --git a/app/models/observer/sla/ticket_rebuild_escalation/background_job.rb b/app/models/observer/sla/ticket_rebuild_escalation/background_job.rb index 763844571..002d7ab2d 100644 --- a/app/models/observer/sla/ticket_rebuild_escalation/background_job.rb +++ b/app/models/observer/sla/ticket_rebuild_escalation/background_job.rb @@ -1,6 +1,5 @@ class Observer::Sla::TicketRebuildEscalation::BackgroundJob - def initialize(_sla_id) - end + def initialize(_sla_id); end def perform Cache.delete('SLA::List::Active') diff --git a/app/models/observer/ticket/article/communicate_email.rb b/app/models/observer/ticket/article/communicate_email.rb index 1f159bb09..a369706d7 100644 --- a/app/models/observer/ticket/article/communicate_email.rb +++ b/app/models/observer/ticket/article/communicate_email.rb @@ -10,7 +10,7 @@ class Observer::Ticket::Article::CommunicateEmail < ActiveRecord::Observer # only do send email if article got created via application_server (e. g. not # if article and sender type is set via *.postmaster) - return if ApplicationHandleInfo.current.split('.')[1] == 'postmaster' + return if ApplicationHandleInfo.postmaster? # if sender is customer, do not communicate return if !record.sender_id 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 15d4d6d97..87c4ceaef 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 do |key| + %i[to cc].each do |key| next if !record[key] next if record[key] == '' @@ -130,7 +130,7 @@ class Observer::Ticket::Article::CommunicateEmail::BackgroundJob if local_record.preferences['delivery_retry'] > 3 recipient_list = '' - [:to, :cc].each do |key| + %i[to cc].each do |key| next if !local_record[key] next if local_record[key] == '' diff --git a/app/models/observer/ticket/article/communicate_facebook.rb b/app/models/observer/ticket/article/communicate_facebook.rb index d318c9079..0285f7de9 100644 --- a/app/models/observer/ticket/article/communicate_facebook.rb +++ b/app/models/observer/ticket/article/communicate_facebook.rb @@ -12,7 +12,7 @@ class Observer::Ticket::Article::CommunicateFacebook < ActiveRecord::Observer # only do send email if article got created via application_server (e. g. not # if article and sender type is set via *.postmaster) - return if ApplicationHandleInfo.current.split('.')[1] == 'postmaster' + return if ApplicationHandleInfo.postmaster? # if sender is customer, do not communicate return if !record.sender_id diff --git a/app/models/observer/ticket/article/communicate_twitter.rb b/app/models/observer/ticket/article/communicate_twitter.rb index 96340826a..b05048c4b 100644 --- a/app/models/observer/ticket/article/communicate_twitter.rb +++ b/app/models/observer/ticket/article/communicate_twitter.rb @@ -10,7 +10,7 @@ class Observer::Ticket::Article::CommunicateTwitter < ActiveRecord::Observer # only do send email if article got created via application_server (e. g. not # if article and sender type is set via *.postmaster) - return if ApplicationHandleInfo.current.split('.')[1] == 'postmaster' + return if ApplicationHandleInfo.postmaster? # if sender is customer, do not communicate return if !record.sender_id diff --git a/app/models/observer/ticket/article/fillup_from_email.rb b/app/models/observer/ticket/article/fillup_from_email.rb index 1fc206ecd..c44c7fcd9 100644 --- a/app/models/observer/ticket/article/fillup_from_email.rb +++ b/app/models/observer/ticket/article/fillup_from_email.rb @@ -10,7 +10,7 @@ class Observer::Ticket::Article::FillupFromEmail < ActiveRecord::Observer # only do fill of email from if article got created via application_server (e. g. not # if article and sender type is set via *.postmaster) - return true if ApplicationHandleInfo.current.split('.')[1] == 'postmaster' + return if ApplicationHandleInfo.postmaster? # if sender is customer, do not change anything return true if !record.sender_id diff --git a/app/models/observer/ticket/article/fillup_from_general.rb b/app/models/observer/ticket/article/fillup_from_general.rb index 7c6ce9166..c4fc8d960 100644 --- a/app/models/observer/ticket/article/fillup_from_general.rb +++ b/app/models/observer/ticket/article/fillup_from_general.rb @@ -10,7 +10,7 @@ class Observer::Ticket::Article::FillupFromGeneral < ActiveRecord::Observer # only do fill of from if article got created via application_server (e. g. not # if article and sender type is set via *.postmaster) - return true if ApplicationHandleInfo.current.split('.')[1] == 'postmaster' + return if ApplicationHandleInfo.postmaster? # set from on all article types excluding email|twitter status|twitter direct-message|facebook feed post|facebook feed comment return true if !record.type_id diff --git a/app/models/observer/ticket/article/fillup_from_origin_by_id.rb b/app/models/observer/ticket/article/fillup_from_origin_by_id.rb index fa77cf3d5..b636a9ae0 100644 --- a/app/models/observer/ticket/article/fillup_from_origin_by_id.rb +++ b/app/models/observer/ticket/article/fillup_from_origin_by_id.rb @@ -10,7 +10,7 @@ class Observer::Ticket::Article::FillupFromOriginById < ActiveRecord::Observer # only do fill of from if article got created via application_server (e. g. not # if article and sender type is set via *.postmaster) - return if ApplicationHandleInfo.current.split('.')[1] == 'postmaster' + return if ApplicationHandleInfo.postmaster? # check if origin_by_id exists return if record.origin_by_id.present? diff --git a/app/models/observer/ticket/article_changes.rb b/app/models/observer/ticket/article_changes.rb index 85e721803..a62ad9e88 100644 --- a/app/models/observer/ticket/article_changes.rb +++ b/app/models/observer/ticket/article_changes.rb @@ -24,7 +24,7 @@ class Observer::Ticket::ArticleChanges < ActiveRecord::Observer # save ticket if !changed - record.ticket.touch + record.ticket.touch # rubocop:disable Rails/SkipsModelValidations return end record.ticket.save @@ -38,7 +38,7 @@ class Observer::Ticket::ArticleChanges < ActiveRecord::Observer # save ticket if !changed - record.ticket.touch + record.ticket.touch # rubocop:disable Rails/SkipsModelValidations return end record.ticket.save! diff --git a/app/models/observer/ticket/ref_object_touch.rb b/app/models/observer/ticket/ref_object_touch.rb index 242de0ed9..85d529c57 100644 --- a/app/models/observer/ticket/ref_object_touch.rb +++ b/app/models/observer/ticket/ref_object_touch.rb @@ -24,26 +24,24 @@ class Observer::Ticket::RefObjectTouch < ActiveRecord::Observer cutomer_id_changed = record.saved_changes['customer_id'] if cutomer_id_changed && cutomer_id_changed[0] != cutomer_id_changed[1] if cutomer_id_changed[0] - User.find(cutomer_id_changed[0]).touch + User.find(cutomer_id_changed[0]).touch # rubocop:disable Rails/SkipsModelValidations end end # touch new/current customer - if record.customer - record.customer.touch - end + record.customer&.touch # touch old organization if changed organization_id_changed = record.saved_changes['organization_id'] if organization_id_changed && organization_id_changed[0] != organization_id_changed[1] if organization_id_changed[0] - Organization.find(organization_id_changed[0]).touch + Organization.find(organization_id_changed[0]).touch # rubocop:disable Rails/SkipsModelValidations end end # touch new/current organization return true if !record.organization - record.organization.touch + record.organization.touch # rubocop:disable Rails/SkipsModelValidations end end diff --git a/app/models/observer/ticket/reset_new_state.rb b/app/models/observer/ticket/reset_new_state.rb index c676b0391..05e20ada3 100644 --- a/app/models/observer/ticket/reset_new_state.rb +++ b/app/models/observer/ticket/reset_new_state.rb @@ -9,7 +9,7 @@ class Observer::Ticket::ResetNewState < ActiveRecord::Observer return if Setting.get('import_mode') # only change state if not processed via postmaster - return if ApplicationHandleInfo.current.split('.')[1] == 'postmaster' + return if ApplicationHandleInfo.postmaster? # if article in internal return true if record.internal diff --git a/app/models/observer/transaction.rb b/app/models/observer/transaction.rb index 15254620b..3dfe47690 100644 --- a/app/models/observer/transaction.rb +++ b/app/models/observer/transaction.rb @@ -33,14 +33,14 @@ class Observer::Transaction < ActiveRecord::Observer sync_backends = [] Setting.where(area: 'Transaction::Backend::Sync').order(:name).each do |setting| backend = Setting.get(setting.name) - next if params[:disable] && params[:disable].include?(backend) + next if params[:disable]&.include?(backend) sync_backends.push Kernel.const_get(backend) end # get uniq objects list_objects = get_uniq_changes(list) - list_objects.each do |_object, objects| - objects.each do |_id, item| + list_objects.each_value do |objects| + objects.each_value do |item| # execute sync backends sync_backends.each do |backend| @@ -215,7 +215,7 @@ class Observer::Transaction < ActiveRecord::Observer end # do not send anything if nothing has changed - return true if real_changes.empty? + return true if real_changes.blank? changed_by_id = nil changed_by_id = if record.respond_to?('updated_by_id') diff --git a/app/models/observer/user/geo.rb b/app/models/observer/user/geo.rb index c65c00923..8cb6b9a68 100644 --- a/app/models/observer/user/geo.rb +++ b/app/models/observer/user/geo.rb @@ -16,7 +16,7 @@ class Observer::User::Geo < ActiveRecord::Observer # check if geo need to be updated def check_geo(record) - location = %w(address street zip city country) + location = %w[address street zip city country] # check if geo update is needed based on old/new location if record.id @@ -45,7 +45,7 @@ class Observer::User::Geo < ActiveRecord::Observer # update geo data of user def geo_update(record) address = '' - location = %w(address street zip city country) + location = %w[address street zip city country] location.each do |item| next if record[item].blank? if address.present? diff --git a/app/models/observer/user/ref_object_touch.rb b/app/models/observer/user/ref_object_touch.rb index 3c828cb5d..07a380ec7 100644 --- a/app/models/observer/user/ref_object_touch.rb +++ b/app/models/observer/user/ref_object_touch.rb @@ -29,7 +29,7 @@ class Observer::User::RefObjectTouch < ActiveRecord::Observer # featrue used for different propose, do not touch references if User.where(organization_id: organization_id_changed[0]).count < 100 organization = Organization.find(organization_id_changed[0]) - organization.touch + organization.touch # rubocop:disable Rails/SkipsModelValidations member_ids = organization.member_ids end end @@ -40,7 +40,7 @@ class Observer::User::RefObjectTouch < ActiveRecord::Observer # featrue used for different propose, do not touch references if User.where(organization_id: record.organization_id).count < 100 - record.organization.touch + record.organization.touch # rubocop:disable Rails/SkipsModelValidations member_ids += record.organization.member_ids end end @@ -48,7 +48,7 @@ class Observer::User::RefObjectTouch < ActiveRecord::Observer # touch old/current customer member_ids.uniq.each do |user_id| next if user_id == record.id - User.find(user_id).touch + User.find(user_id).touch # rubocop:disable Rails/SkipsModelValidations end true end diff --git a/app/models/organization/assets.rb b/app/models/organization/assets.rb index d500a5392..d0db37fe0 100644 --- a/app/models/organization/assets.rb +++ b/app/models/organization/assets.rb @@ -55,7 +55,7 @@ returns data[ app_model_organization ][ id ] = local_attributes end - %w(created_by_id updated_by_id).each do |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 ]) diff --git a/app/models/overview.rb b/app/models/overview.rb index ffadc7cb6..c6e604323 100644 --- a/app/models/overview.rb +++ b/app/models/overview.rb @@ -45,14 +45,14 @@ class Overview < ApplicationModel local_link = local_link.parameterize(separator: '_') local_link.gsub!(/\s/, '_') local_link.gsub!(/_+/, '_') - local_link = URI.escape(local_link) + local_link = CGI.escape(local_link) if local_link.blank? local_link = id || rand(999) end check = true while check exists = Overview.find_by(link: local_link) - if exists && exists.id != id + if exists&.id != id local_link = "#{local_link}_#{rand(999)}" else check = false diff --git a/app/models/overview/assets.rb b/app/models/overview/assets.rb index 9698a07f3..15f252a66 100644 --- a/app/models/overview/assets.rb +++ b/app/models/overview/assets.rb @@ -34,19 +34,17 @@ returns end if !data[ app_model_overview ][ id ] data[ app_model_overview ][ id ] = attributes_with_association_ids - if user_ids - 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 + 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 data = assets_of_selector('condition', data) end - %w(created_by_id updated_by_id).each do |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 ]) diff --git a/app/models/package.rb b/app/models/package.rb index 221896a0e..361108685 100644 --- a/app/models/package.rb +++ b/app/models/package.rb @@ -166,7 +166,7 @@ link files + execute migration up file = file.sub(%r{^/}, '') # ignore files - if file =~ /^README/ + if file.match?(/^README/) logger.info "NOTICE: Ignore #{file}" next end @@ -185,10 +185,9 @@ link files + execute migration up backup_file = dest.to_s + '.link_backup' if File.exist?(backup_file) raise "Can't link #{entry} -> #{dest}, destination and .link_backup already exists!" - else - logger.info "Create backup file of #{dest} -> #{backup_file}." - File.rename(dest.to_s, backup_file) end + logger.info "Create backup file of #{dest} -> #{backup_file}." + File.rename(dest.to_s, backup_file) end if File.file?(entry) @@ -528,21 +527,18 @@ execute all pending package migrations at once end # down + done = Package::Migration.find_by(name: package.underscore, version: version) if direction == 'reverse' - done = Package::Migration.find_by(name: package.underscore, version: version) next if !done logger.info "NOTICE: down package migration '#{migration}'" load "#{location}/#{migration}" classname = name.camelcase classname.constantize.down record = Package::Migration.find_by(name: package.underscore, version: version) - if record - record.destroy - end + record&.destroy # up else - done = Package::Migration.find_by(name: package.underscore, version: version) next if done logger.info "NOTICE: up package migration '#{migration}'" load "#{location}/#{migration}" diff --git a/app/models/postmaster_filter.rb b/app/models/postmaster_filter.rb index 9a5f72361..172cb32f0 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 do |_key, meta| + match.each_value do |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 diff --git a/app/models/report.rb b/app/models/report.rb index d969b8342..f2d130b8b 100644 --- a/app/models/report.rb +++ b/app/models/report.rb @@ -1,7 +1,7 @@ class Report def self.enabled? - !Setting.get('es_url').empty? + Setting.get('es_url').present? end def self.config diff --git a/app/models/role/assets.rb b/app/models/role/assets.rb index f046d12c7..cb42d7575 100644 --- a/app/models/role/assets.rb +++ b/app/models/role/assets.rb @@ -35,7 +35,7 @@ returns # loops, will be updated with lookup attributes later data[ app_model ][ id ] = local_attributes - local_attributes['group_ids'].each do |group_id, _access| + local_attributes['group_ids'].each_key do |group_id| group = Group.lookup(id: group_id) next if !group data = group.assets(data) @@ -44,7 +44,7 @@ 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 do |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 ]) diff --git a/app/models/scheduler.rb b/app/models/scheduler.rb index 2ed876d12..8397032fd 100644 --- a/app/models/scheduler.rb +++ b/app/models/scheduler.rb @@ -69,7 +69,7 @@ class Scheduler < ApplicationModel # return [nil] def self.cleanup(force: false) - if !force && caller_locations.first.label != 'threads' + if !force && caller_locations(1..1).first.label != 'threads' raise 'This method should only get called when Scheduler.threads are initialized. Use `force: true` to start anyway.' end @@ -175,7 +175,7 @@ class Scheduler < ApplicationModel ) logger.info "execute #{job.method} (try_count #{try_count})..." - eval job.method() # rubocop:disable Lint/Eval + eval job.method() # rubocop:disable Security/Eval rescue => e logger.error "execute #{job.method} (try_count #{try_count}) exited with error #{e.inspect}" diff --git a/app/models/sla/assets.rb b/app/models/sla/assets.rb index 796eb9e5c..b24d0f88d 100644 --- a/app/models/sla/assets.rb +++ b/app/models/sla/assets.rb @@ -42,7 +42,7 @@ returns end end end - %w(created_by_id updated_by_id).each do |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 ]) diff --git a/app/models/store.rb b/app/models/store.rb index 76fea4961..45200c455 100644 --- a/app/models/store.rb +++ b/app/models/store.rb @@ -178,7 +178,7 @@ returns raise "No such file #{store_file_id}!" end if !path - path = "#{Rails.root}/tmp/#{filename}" + path = Rails.root.join('tmp', filename) end ::File.open(path, 'wb') do |handle| handle.write file.content diff --git a/app/models/store/file.rb b/app/models/store/file.rb index 9c6ae18bf..c056a4be8 100644 --- a/app/models/store/file.rb +++ b/app/models/store/file.rb @@ -90,7 +90,7 @@ in case of fixing sha hash use: store = Store.find_by(store_file_id: item.id) logger.error "STORE: #{store.inspect}" if fix_it - item.update_attribute(:sha, sha) + item.update_attribute(:sha, sha) # rubocop:disable Rails/SkipsModelValidations end end success @@ -128,7 +128,7 @@ nice move to keep system responsive adapter_target.add(content, item.sha) # update meta data - item.update_attribute(:provider, target) + item.update_attribute(:provider, target) # rubocop:disable Rails/SkipsModelValidations # remove from old provider adapter_source.delete(item.sha) diff --git a/app/models/store/provider/file.rb b/app/models/store/provider/file.rb index 82b1a48ec..3d8b4f76d 100644 --- a/app/models/store/provider/file.rb +++ b/app/models/store/provider/file.rb @@ -51,12 +51,11 @@ class Store::Provider::File end # check if dir need to be removed - base = "#{Rails.root}/storage/fs" locations = location.split('/') (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? + break if local_location.match?(%r{storage/fs/{0,4}$}) + break if Dir["#{local_location}/*"].present? FileUtils.rmdir(local_location) end end @@ -65,8 +64,8 @@ class Store::Provider::File def self.get_location(sha) # generate directory - base = "#{Rails.root}/storage/fs/" - parts = [] + base = Rails.root.join('storage', 'fs').to_s + parts = [] length1 = 4 length2 = 5 length3 = 7 diff --git a/app/models/taskbar.rb b/app/models/taskbar.rb index 8aac94cee..ba4c64fe8 100644 --- a/app/models/taskbar.rb +++ b/app/models/taskbar.rb @@ -14,9 +14,9 @@ class Taskbar < ApplicationModel def state_changed? return false if state.blank? - state.each do |_key, value| + state.each_value do |value| if value.is_a? Hash - value.each do |_key1, value1| + value.each_value do |value1| next if value1.blank? return true end @@ -32,10 +32,10 @@ class Taskbar < ApplicationModel def update_last_contact return true if local_update - return true if changes.empty? + return true if changes.blank? if changes['notify'] count = 0 - changes.each do |attribute, _value| + changes.each_key do |attribute| next if attribute == 'updated_at' next if attribute == 'created_at' count += 1 diff --git a/app/models/ticket.rb b/app/models/ticket.rb index e930201ae..83aa9a5b3 100644 --- a/app/models/ticket.rb +++ b/app/models/ticket.rb @@ -300,7 +300,7 @@ returns Ticket::Article.where(ticket_id: id).each(&:touch) # quiet update of reassign of articles - Ticket::Article.where(ticket_id: id).update_all(['ticket_id = ?', data[:ticket_id]]) + Ticket::Article.where(ticket_id: id).update_all(['ticket_id = ?', data[:ticket_id]]) # rubocop:disable Rails/SkipsModelValidations # update history @@ -318,6 +318,7 @@ returns # add history to both # reassign links to the new ticket + # rubocop:disable Rails/SkipsModelValidations Link.where( link_object_source_id: Link::Object.find_by(name: 'Ticket').id, link_object_source_value: id, @@ -326,6 +327,7 @@ returns link_object_target_id: Link::Object.find_by(name: 'Ticket').id, link_object_target_value: id, ).update_all(link_object_target_value: data[:ticket_id]) + # rubocop:enable Rails/SkipsModelValidations # link tickets Link.add( @@ -346,7 +348,7 @@ returns save! # touch new ticket (to broadcast change) - target_ticket.touch + target_ticket.touch # rubocop:disable Rails/SkipsModelValidations end true end @@ -500,9 +502,13 @@ condition example bind_params = [] like = Rails.application.config.db_like + if selectors.respond_to?(:permit!) + selectors = selectors.permit!.to_h + end + # get tables to join tables = '' - selectors.each do |attribute, selector| + selectors.each_key do |attribute| selector = attribute.split(/\./) next if !selector[1] next if selector[0] == 'ticket' @@ -537,7 +543,7 @@ condition example raise "Invalid selector, operator missing #{selector.inspect}" if !selector['operator'] # validate value / allow blank but only if pre_condition exists and is not specific - if !selector.key?('value') || ((selector['value'].class == String || selector['value'].class == Array) && (selector['value'].respond_to?(:empty?) && selector['value'].empty?)) + if !selector.key?('value') || ((selector['value'].class == String || selector['value'].class == Array) && (selector['value'].respond_to?(:blank?) && selector['value'].blank?)) return nil if selector['pre_condition'].nil? return nil if selector['pre_condition'].respond_to?(:blank?) && selector['pre_condition'].blank? return nil if selector['pre_condition'] == 'specific' @@ -565,7 +571,7 @@ condition example if selector['operator'] == 'is' if selector['pre_condition'] == 'not_set' - if attributes[1] =~ /^(created_by|updated_by|owner|customer|user)_id/ + if attributes[1].match?(/^(created_by|updated_by|owner|customer|user)_id/) query += "#{attribute} IN (?)" bind_params.push 1 else @@ -573,11 +579,10 @@ condition example end elsif selector['pre_condition'] == 'current_user.id' raise "Use current_user.id in selector, but no current_user is set #{selector.inspect}" if !current_user_id + query += "#{attribute} IN (?)" if attributes[1] == 'out_of_office_replacement_id' - query += "#{attribute} IN (?)" bind_params.push User.find(current_user_id).out_of_office_agent_of.pluck(:id) else - query += "#{attribute} IN (?)" bind_params.push current_user_id end elsif selector['pre_condition'] == 'current_user.organization_id' @@ -590,11 +595,10 @@ condition example if selector['value'].nil? query += "#{attribute} IS NULL" else + query += "#{attribute} IN (?)" if attributes[1] == 'out_of_office_replacement_id' - query += "#{attribute} IN (?)" bind_params.push User.find(selector['value']).out_of_office_agent_of.pluck(:id) else - query += "#{attribute} IN (?)" bind_params.push selector['value'] end end @@ -602,18 +606,17 @@ condition example end elsif selector['operator'] == 'is not' if selector['pre_condition'] == 'not_set' - if attributes[1] =~ /^(created_by|updated_by|owner|customer|user)_id/ + if attributes[1].match?(/^(created_by|updated_by|owner|customer|user)_id/) query += "#{attribute} NOT IN (?)" bind_params.push 1 else query += "#{attribute} IS NOT NULL" end elsif selector['pre_condition'] == 'current_user.id' + query += "#{attribute} NOT IN (?)" if attributes[1] == 'out_of_office_replacement_id' - query += "#{attribute} NOT IN (?)" bind_params.push User.find(current_user_id).out_of_office_agent_of.pluck(:id) else - query += "#{attribute} NOT IN (?)" bind_params.push current_user_id end elsif selector['pre_condition'] == 'current_user.organization_id' @@ -625,11 +628,10 @@ condition example if selector['value'].nil? query += "#{attribute} IS NOT NULL" else + query += "#{attribute} NOT IN (?)" if attributes[1] == 'out_of_office_replacement_id' - query += "#{attribute} NOT IN (?)" bind_params.push User.find(selector['value']).out_of_office_agent_of.pluck(:id) else - query += "#{attribute} NOT IN (?)" bind_params.push selector['value'] end end @@ -806,7 +808,7 @@ perform changes on ticket # if the configuration contains the deletion of the ticket then # we skip all other ticket changes because they does not matter if perform['ticket.action'].present? && perform['ticket.action']['value'] == 'delete' - perform.each do |key, _value| + perform.each_key do |key| (object_name, attribute) = key.split('.', 2) next if object_name != 'ticket' next if attribute == 'action' @@ -892,17 +894,17 @@ perform changes on ticket # do not sent notifications to this recipients send_no_auto_response_reg_exp = Setting.get('send_no_auto_response_reg_exp') begin - next if recipient_email =~ /#{send_no_auto_response_reg_exp}/i + next if recipient_email.match?(/#{send_no_auto_response_reg_exp}/i) rescue => e logger.error "ERROR: Invalid regex '#{send_no_auto_response_reg_exp}' in setting send_no_auto_response_reg_exp" logger.error 'ERROR: ' + e.inspect - next if recipient_email =~ /(mailer-daemon|postmaster|abuse|root|noreply|noreply.+?|no-reply|no-reply.+?)@.+?/i + next if recipient_email.match?(/(mailer-daemon|postmaster|abuse|root|noreply|noreply.+?|no-reply|no-reply.+?)@.+?/i) end # check if notification should be send because of customer emails if item && item[:article_id] article = Ticket::Article.lookup(id: item[:article_id]) - if article && article.preferences['is-auto-response'] == true && article.from && article.from =~ /#{Regexp.quote(recipient_email)}/i + if article&.preferences&.fetch('is-auto-response', false) == true && article.from && article.from =~ /#{Regexp.quote(recipient_email)}/i logger.info "Send no trigger based notification to #{recipient_email} because of auto response tagged incoming email" next end @@ -1037,9 +1039,9 @@ perform changes on ticket # lookup pre_condition if value['pre_condition'] - if value['pre_condition'] =~ /^not_set/ + if value['pre_condition'].match?(/^not_set/) value['value'] = 1 - elsif value['pre_condition'] =~ /^current_user\./ + elsif value['pre_condition'].match?(/^current_user\./) raise 'Unable to use current_user, got no current_user_id for ticket.perform_changes' if !current_user_id value['value'] = current_user_id end @@ -1079,11 +1081,10 @@ result def get_references(ignore = []) references = [] Ticket::Article.select('in_reply_to, message_id').where(ticket_id: id).each do |article| - if !article.in_reply_to.empty? + if article.in_reply_to.present? references.push article.in_reply_to end - next if !article.message_id - next if article.message_id.empty? + next if article.message_id.blank? references.push article.message_id end ignore.each do |item| @@ -1169,7 +1170,7 @@ result current_state_type = Ticket::StateType.lookup(id: current_state.state_type_id) # in case, set pending_time to nil - return true if current_state_type.name =~ /^pending/i + return true if current_state_type.name.match?(/^pending/i) self.pending_time = nil true end diff --git a/app/models/ticket/article.rb b/app/models/ticket/article.rb index 96213f2d8..64ebcb1d9 100644 --- a/app/models/ticket/article.rb +++ b/app/models/ticket/article.rb @@ -148,7 +148,7 @@ get body as text def body_as_text return '' if !body - return body if !content_type || content_type.empty? || content_type =~ %r{text/plain}i + return body if content_type.blank? || content_type =~ %r{text/plain}i body.html2text end @@ -290,15 +290,12 @@ returns return true if body.blank? limit = 1_500_000 current_length = body.length - if body.length > limit - if ApplicationHandleInfo.current.present? && ApplicationHandleInfo.current.split('.')[1] == 'postmaster' - logger.warn "WARNING: cut string because of database length #{self.class}.body(#{limit} but is #{current_length})" - self.body = body[0, limit] - else - raise Exceptions::UnprocessableEntity, "body if article is to large, #{current_length} chars - only #{limit} allowed" - end - end - true + return true if body.length <= limit + + raise Exceptions::UnprocessableEntity, "body if article is to large, #{current_length} chars - only #{limit} allowed" if !ApplicationHandleInfo.postmaster? + + logger.warn "WARNING: cut string because of database length #{self.class}.body(#{limit} but is #{current_length})" + self.body = body[0, limit] end def history_log_attributes diff --git a/app/models/ticket/article/assets.rb b/app/models/ticket/article/assets.rb index 88c6e2fe1..e2efaf92d 100644 --- a/app/models/ticket/article/assets.rb +++ b/app/models/ticket/article/assets.rb @@ -42,7 +42,7 @@ returns data[ app_model_article ][ id ] = attributes_with_association_ids end - %w(created_by_id updated_by_id origin_by_id).each do |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 ]) diff --git a/app/models/ticket/assets.rb b/app/models/ticket/assets.rb index 4fdd1424d..c247949c6 100644 --- a/app/models/ticket/assets.rb +++ b/app/models/ticket/assets.rb @@ -31,7 +31,7 @@ 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 do |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 ]) diff --git a/app/models/ticket/escalation.rb b/app/models/ticket/escalation.rb index 66152a6a4..816d2fde0 100644 --- a/app/models/ticket/escalation.rb +++ b/app/models/ticket/escalation.rb @@ -169,13 +169,11 @@ returns # get holidays holidays = [] - if calendar.public_holidays - calendar.public_holidays.each do |day, meta| - next if !meta - next if !meta['active'] - next if meta['removed'] - holidays.push Date.parse(day) - end + calendar.public_holidays&.each do |day, meta| + next if !meta + next if !meta['active'] + next if meta['removed'] + holidays.push Date.parse(day) end config.holidays = holidays config.time_zone = calendar.timezone @@ -294,7 +292,7 @@ returns Cache.write('SLA::List::Active', sla_list, { expires_in: 1.hour }) end sla_list.each do |sla| - if !sla.condition || sla.condition.empty? + if sla.condition.blank? sla_selected = sla elsif sla.condition query_condition, bind_condition, tables = Ticket.selector2sql(sla.condition) diff --git a/app/models/ticket/overviews.rb b/app/models/ticket/overviews.rb index de060ac01..344b2e7c3 100644 --- a/app/models/ticket/overviews.rb +++ b/app/models/ticket/overviews.rb @@ -27,7 +27,7 @@ returns overviews_list = [] overviews.each do |overview| user_ids = overview.user_ids - next if !user_ids.empty? && !user_ids.include?(current_user.id) + next if user_ids.present? && !user_ids.include?(current_user.id) overviews_list.push overview end return overviews_list diff --git a/app/models/ticket/priority.rb b/app/models/ticket/priority.rb index be3a780b5..5481e226c 100644 --- a/app/models/ticket/priority.rb +++ b/app/models/ticket/priority.rb @@ -10,16 +10,16 @@ class Ticket::Priority < ApplicationModel attr_accessor :callback_loop def ensure_defaults - return if callback_loop + return true if callback_loop priorities_with_default = Ticket::Priority.where(default_create: true) - return if priorities_with_default.count == 1 + return true if priorities_with_default.count == 1 if priorities_with_default.count.zero? priority = Ticket::Priority.where(active: true).order(id: :asc).first priority.default_create = true priority.callback_loop = true priority.save! - return + return true end if priorities_with_default.count > 1 @@ -30,5 +30,6 @@ class Ticket::Priority < ApplicationModel local_priority.save! end end + true end end diff --git a/app/models/ticket/screen_options.rb b/app/models/ticket/screen_options.rb index f490b4dda..c15b2ae81 100644 --- a/app/models/ticket/screen_options.rb +++ b/app/models/ticket/screen_options.rb @@ -68,7 +68,7 @@ returns type_ids = [] if params[:ticket] - types = %w(note phone) + types = %w[note phone] if params[:ticket].group.email_address_id types.push 'email' end diff --git a/app/models/ticket/search_index.rb b/app/models/ticket/search_index.rb index dbd0ecf8a..c5ff8361b 100644 --- a/app/models/ticket/search_index.rb +++ b/app/models/ticket/search_index.rb @@ -40,7 +40,7 @@ returns article_attributes = article.search_index_attribute_lookup # remove note needed attributes - ignore = %w(message_id_md5 ticket) + ignore = %w[message_id_md5 ticket] ignore.each do |attribute| article_attributes.delete(attribute) end diff --git a/app/models/ticket/state.rb b/app/models/ticket/state.rb index 7adb18dd4..9f75ef380 100644 --- a/app/models/ticket/state.rb +++ b/app/models/ticket/state.rb @@ -36,7 +36,7 @@ returns: when :pending state_types = ['pending reminder', 'pending action'] when :work_on - state_types = %w(new open) + state_types = %w[new open] when :work_on_all state_types = ['new', 'open', 'pending reminder'] when :viewable @@ -46,13 +46,13 @@ returns: when :viewable_agent_edit state_types = ['open', 'pending reminder', 'pending action', 'closed'] when :viewable_customer_new - state_types = %w(new closed) + state_types = %w[new closed] when :viewable_customer_edit - state_types = %w(open closed) + state_types = %w[open closed] when :closed - state_types = %w(closed) + state_types = %w[closed] when :merged - state_types = %w(merged) + state_types = %w[merged] end raise "Unknown category '#{category}'" if state_types.blank? @@ -84,7 +84,7 @@ returns: def ensure_defaults return if callback_loop - %w(default_create default_follow_up).each do |default_field| + %w[default_create default_follow_up].each do |default_field| states_with_default = Ticket::State.where(default_field => true) next if states_with_default.count == 1 diff --git a/app/models/transaction/background_job.rb b/app/models/transaction/background_job.rb index f37c99846..4d92c6017 100644 --- a/app/models/transaction/background_job.rb +++ b/app/models/transaction/background_job.rb @@ -25,7 +25,7 @@ class Transaction::BackgroundJob def perform Setting.where(area: 'Transaction::Backend::Async').order(:name).each do |setting| backend = Setting.get(setting.name) - next if @params[:disable] && @params[:disable].include?(backend) + next if @params[:disable]&.include?(backend) backend = Kernel.const_get(backend) Observer::Transaction.execute_singel_backend(backend, @item, @params) end diff --git a/app/models/transaction/cti_caller_id_detection.rb b/app/models/transaction/cti_caller_id_detection.rb index 186d4f8e6..959ba4a26 100644 --- a/app/models/transaction/cti_caller_id_detection.rb +++ b/app/models/transaction/cti_caller_id_detection.rb @@ -48,6 +48,7 @@ class Transaction::CtiCallerIdDetection Cti::CallerId.build(user) end + true end end diff --git a/app/models/transaction/karma.rb b/app/models/transaction/karma.rb index 07a43b73f..c5fa1d082 100644 --- a/app/models/transaction/karma.rb +++ b/app/models/transaction/karma.rb @@ -98,6 +98,7 @@ class Transaction::Karma Karma::ActivityLog.add('ticket pending state', user, 'Ticket', ticket.id) end + true end def ticket_article_karma(user) @@ -132,11 +133,7 @@ class Transaction::Karma return false if !local_sender next if local_sender.name == 'System' - last_sender_customer = if local_sender.name == 'Customer' - true - else - false - end + last_sender_customer = local_sender.name == 'Customer' next if local_sender.name != 'Customer' last_customer_contact = local_article.created_at @@ -158,9 +155,11 @@ class Transaction::Karma end ### text module - if article.preferences[:text_module_ids] && !article.preferences[:text_module_ids].empty? + if article.preferences[:text_module_ids].present? Karma::ActivityLog.add('text module', user, 'Ticket', @item[:object_id]) end + + true end def tagging(user) diff --git a/app/models/transaction/notification.rb b/app/models/transaction/notification.rb index 8c5a74539..bbcad80d4 100644 --- a/app/models/transaction/notification.rb +++ b/app/models/transaction/notification.rb @@ -36,7 +36,7 @@ class Transaction::Notification # ignore notifications sender = Ticket::Article::Sender.lookup(id: article.sender_id) - if sender && sender.name == 'System' + if sender&.name == 'System' return if @item[:changes].blank? && article.preferences[:notification] != true if article.preferences[:notification] != true article = nil @@ -91,7 +91,7 @@ class Transaction::Notification # ignore user who changed it by him self via web if @params[:interface_handle] == 'application_server' - next if article && article.updated_by_id == user.id + next if article&.updated_by_id == user.id next if !article && @item[:user_id] == user.id end @@ -213,7 +213,7 @@ class Transaction::Notification end def add_recipient_list(ticket, user, channels, type) - return if channels.empty? + return if channels.blank? identifier = user.email if !identifier || identifier == '' identifier = user.login @@ -240,7 +240,7 @@ class Transaction::Notification @item[:changes].each do |key, value| # if no config exists, use all attributes - if !attribute_list || attribute_list.empty? + if attribute_list.blank? user_related_changes[key] = value # if config exists, just use existing attributes for user diff --git a/app/models/transaction/slack.rb b/app/models/transaction/slack.rb index aac7d393a..3c49a61a3 100644 --- a/app/models/transaction/slack.rb +++ b/app/models/transaction/slack.rb @@ -43,15 +43,15 @@ class Transaction::Slack # ignore notifications sender = Ticket::Article::Sender.lookup(id: article.sender_id) - if sender && sender.name == 'System' - return if @item[:changes].empty? + if sender&.name == 'System' + return if @item[:changes].blank? article = nil end end # ignore if no changes has been done changes = human_changes(ticket) - return if @item[:type] == 'update' && !article && (!changes || changes.empty?) + return if @item[:type] == 'update' && !article && changes.blank? # get user based notification template # if create, send create message / block update messages @@ -101,14 +101,14 @@ class Transaction::Slack if ticket.pending_time && ticket.pending_time < Time.zone.now color = '#faab00' end - elsif ticket_state_type =~ /^(new|open)$/ + elsif ticket_state_type.match?(/^(new|open)$/) color = '#faab00' elsif ticket_state_type == 'closed' color = '#38ad69' end config['items'].each do |local_config| - next if local_config['webhook'].empty? + next if local_config['webhook'].blank? # check if reminder_reached/escalation/escalation_warning is already sent today md5_webhook = Digest::MD5.hexdigest(local_config['webhook']) @@ -155,7 +155,7 @@ class Transaction::Slack end logo_url = 'https://zammad.com/assets/images/logo-200x200.png' - if !local_config['logo_url'].empty? + if local_config['logo_url'].present? logo_url = local_config['logo_url'] end @@ -206,7 +206,7 @@ class Transaction::Slack @item[:changes].each do |key, value| # if no config exists, use all attributes - if !attribute_list || attribute_list.empty? + if attribute_list.blank? user_related_changes[key] = value # if config exists, just use existing attributes for user diff --git a/app/models/transaction/trigger.rb b/app/models/transaction/trigger.rb index 24322ceb8..66e8cb468 100644 --- a/app/models/transaction/trigger.rb +++ b/app/models/transaction/trigger.rb @@ -34,7 +34,7 @@ class Transaction::Trigger else Trigger.where(active: true).order(:name) end - return if triggers.empty? + return if triggers.blank? ticket = Ticket.lookup(id: @item[:object_id]) return if !ticket @@ -51,7 +51,7 @@ class Transaction::Trigger # check if one article attribute is used one_has_changed_done = false article_selector = false - trigger.condition.each do |key, _value| + trigger.condition.each_key do |key| (object_name, attribute) = key.split('.', 2) next if object_name != 'article' next if attribute == 'id' @@ -81,7 +81,7 @@ class Transaction::Trigger end # check if we have not matching "has changed" attributes - condition.each do |_key, value| + condition.each_value do |value| next if !value next if !value['operator'] next if !value['operator']['has changed'] @@ -102,7 +102,7 @@ class Transaction::Trigger if @item[:type] == 'update' # verify if ticket condition exists - condition.each do |key, _value| + condition.each_key do |key| (object_name, attribute) = key.split('.', 2) next if object_name != 'ticket' one_has_changed_condition = true diff --git a/app/models/translation.rb b/app/models/translation.rb index dbb013345..4d1a4253a 100644 --- a/app/models/translation.rb +++ b/app/models/translation.rb @@ -168,7 +168,7 @@ get list of translations # 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 do |presort| + %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 @@ -227,9 +227,9 @@ all: def self.load_from_file(dedicated_locale = nil) version = Version.get - directory = Rails.root.join('config/translations') + directory = Rails.root.join('config', 'translations') locals_to_sync(dedicated_locale).each do |locale| - file = Rails.root.join("#{directory}/#{locale}-#{version}.yml") + file = Rails.root.join(directory, "#{locale}-#{version}.yml") return false if !File.exist?(file) data = YAML.load_file(file) to_database(locale, data) @@ -271,11 +271,11 @@ all: ) raise "Can't load translations from #{url}: #{result.error}" if !result.success? - directory = Rails.root.join('config/translations') + directory = Rails.root.join('config', 'translations') if !File.directory?(directory) Dir.mkdir(directory, 0o755) end - file = Rails.root.join("#{directory}/#{locale}-#{version}.yml") + file = Rails.root.join(directory, "#{locale}-#{version}.yml") File.open(file, 'w') do |out| YAML.dump(result.data, out) end @@ -359,7 +359,7 @@ Get source file at https://i18n.zammad.com/api/v1/translations_empty_translation # verify if update is needed update_needed = false - translation_raw.each do |key, _value| + translation_raw.each_key do |key| # if translation target has changes next unless translation_raw[key] != translation.target diff --git a/app/models/user.rb b/app/models/user.rb index 21c32d86a..ac6dac3cf 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -45,7 +45,7 @@ class User < ApplicationModel after_update :avatar_for_email_check after_destroy :avatar_destroy, :user_device_destroy - has_and_belongs_to_many :roles, after_add: [:cache_update, :check_notifications], after_remove: :cache_update, before_add: [:validate_agent_limit_by_role, :validate_roles], before_remove: :last_admin_check_by_role, class_name: 'Role' + has_and_belongs_to_many :roles, after_add: %i[cache_update check_notifications], after_remove: :cache_update, before_add: %i[validate_agent_limit_by_role validate_roles], before_remove: :last_admin_check_by_role, class_name: 'Role' has_and_belongs_to_many :organizations, after_add: :cache_update, after_remove: :cache_update, class_name: 'Organization' #has_many :permissions, class_name: 'Permission', through: :roles, class_name: 'Role' has_many :tokens, after_add: :cache_update, after_remove: :cache_update @@ -368,12 +368,9 @@ returns role_ids = Role.signup_role_ids url = '' - if hash['info']['urls'] - hash['info']['urls'].each do |_name, local_url| - next if !local_url - next if local_url.empty? - url = local_url - end + hash['info']['urls']&.each_value do |local_url| + next if local_url.blank? + url = local_url end create( login: hash['info']['nickname'] || hash['uid'], @@ -441,13 +438,13 @@ returns end keys.each do |local_key| list = [] - if local_key =~ /\.\*$/ + if local_key.match?(/\.\*$/) local_key.sub!('.*', '.%') permissions = ::Permission.with_parents(local_key) list = ::Permission.select('preferences').joins(:roles).where('roles.id IN (?) AND roles.active = ? AND (permissions.name IN (?) OR permissions.name LIKE ?) AND permissions.active = ?', role_ids, true, permissions, local_key, true).pluck(:preferences) else permission = ::Permission.lookup(name: local_key) - break if permission && permission.active == false + break if permission&.active == false permissions = ::Permission.with_parents(local_key) list = ::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 @@ -472,7 +469,7 @@ returns def permissions_with_child_ids where = '' where_bind = [true] - permissions.each do |permission_name, _value| + permissions.each_key do |permission_name| where += ' OR ' if where != '' where += 'permissions.name = ? OR permissions.name LIKE ?' where_bind.push permission_name @@ -511,13 +508,13 @@ returns next if !permission permission_ids.push permission.id end - next if permission_ids.empty? + next if permission_ids.blank? 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? + return [] if total_role_ids.blank? condition = '' total_role_ids.each do |_role_ids| if condition != '' @@ -792,7 +789,7 @@ returns true end - def check_notifications(o, shouldSave = true) + def check_notifications(o, should_save = true) default = Rails.configuration.preferences_default_by_permission return if !default default.deep_stringify_keys! @@ -808,7 +805,7 @@ returns return true if !has_changed - if id && shouldSave + if id && should_save save! return true end @@ -908,7 +905,7 @@ returns self.email = email.downcase.strip return true if id == 1 raise Exceptions::UnprocessableEntity, 'Invalid email' if email !~ /@/ - raise Exceptions::UnprocessableEntity, 'Invalid email' if email =~ /\s/ + raise Exceptions::UnprocessableEntity, 'Invalid email' if email.match?(/\s/) true end @@ -936,7 +933,7 @@ returns check = true while check exists = User.find_by(login: login) - if exists && exists.id != id + if exists && exists.id != id # rubocop:disable Style/SafeNavigation self.login = "#{login}#{rand(999)}" else check = false @@ -1109,7 +1106,7 @@ raise 'Minimum one user need to have admin permissions' # update user link return true if !avatar - update_column(:image, avatar.store_hash) + update_column(:image, avatar.store_hash) # rubocop:disable Rails/SkipsModelValidations cache_delete true end diff --git a/app/models/user/assets.rb b/app/models/user/assets.rb index 77dcd8473..2be614b5f 100644 --- a/app/models/user/assets.rb +++ b/app/models/user/assets.rb @@ -56,32 +56,26 @@ returns local_attributes['accounts'] = local_accounts # get roles - if local_attributes['role_ids'] - local_attributes['role_ids'].each do |role_id| - next if data[:Role] && data[:Role][role_id] - role = Role.lookup(id: role_id) - data = role.assets(data) - end + local_attributes['role_ids']&.each do |role_id| + next if data[:Role] && data[:Role][role_id] + role = Role.lookup(id: role_id) + data = role.assets(data) end # get groups - if local_attributes['group_ids'] - local_attributes['group_ids'].each do |group_id, _access| - next if data[:Group] && data[:Group][group_id] - group = Group.lookup(id: group_id) - next if !group - data = group.assets(data) - end + local_attributes['group_ids']&.each do |group_id, _access| + next if data[:Group] && data[:Group][group_id] + group = Group.lookup(id: group_id) + next if !group + data = group.assets(data) end # get organizations - if local_attributes['organization_ids'] - local_attributes['organization_ids'].each do |organization_id| - next if data[:Organization] && data[:Organization][organization_id] - organization = Organization.lookup(id: organization_id) - next if !organization - data = organization.assets(data) - end + local_attributes['organization_ids']&.each do |organization_id| + next if data[:Organization] && data[:Organization][organization_id] + organization = Organization.lookup(id: organization_id) + next if !organization + data = organization.assets(data) end data[ app_model ][ id ] = local_attributes @@ -96,7 +90,7 @@ returns end end end - %w(created_by_id updated_by_id).each do |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 ]) diff --git a/app/models/user_device.rb b/app/models/user_device.rb index cecc0cc1c..4edb36d03 100644 --- a/app/models/user_device.rb +++ b/app/models/user_device.rb @@ -48,7 +48,7 @@ store new device for user if device not already known # for basic_auth|token_auth search for user agent device_exists_by_user_agent = false - if type == 'basic_auth' || type == 'token_auth' + if %w[basic_auth token_auth].include?(type) user_devices = UserDevice.where( user_id: user_id, user_agent: user_agent, diff --git a/config/application.rb b/config/application.rb index 79eef32c8..1e2444552 100644 --- a/config/application.rb +++ b/config/application.rb @@ -13,8 +13,8 @@ module Zammad # -- all .rb files in that directory are automatically loaded. # Custom directories with classes and modules you want to be autoloadable. - config.autoload_paths += %W(#{config.root}/lib) - config.eager_load_paths += %W(#{config.root}/lib) + config.autoload_paths += %W[#{config.root}/lib] + config.eager_load_paths += %W[#{config.root}/lib] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer @@ -47,7 +47,7 @@ module Zammad config.api_path = '/api/v1' # define cache store - config.cache_store = :file_store, "#{Rails.root}/tmp/cache_file_store_#{Rails.env}" + config.cache_store = :file_store, Rails.root.join('tmp', "cache_file_store_#{Rails.env}") # default preferences by permission config.preferences_default_by_permission = { diff --git a/config/initializers/assets.rb b/config/initializers/assets.rb index 09feafbf1..110972dae 100644 --- a/config/initializers/assets.rb +++ b/config/initializers/assets.rb @@ -8,5 +8,5 @@ Rails.application.config.assets.version = '1.0' # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. -Rails.application.config.assets.precompile += %w(application-print.css) -Rails.application.config.assets.precompile += %w(print.css) +Rails.application.config.assets.precompile += %w[application-print.css] +Rails.application.config.assets.precompile += %w[print.css] diff --git a/config/initializers/core_ext.rb b/config/initializers/core_ext.rb index 86258f99e..e4c09d57e 100644 --- a/config/initializers/core_ext.rb +++ b/config/initializers/core_ext.rb @@ -1,5 +1,5 @@ # load all core_ext extentions -Dir.glob("#{Rails.root}/lib/core_ext/**/*").each do |file| +Dir.glob( Rails.root.join('lib', 'core_ext', '**', '*') ).each do |file| if File.file?(file) require file end diff --git a/config/initializers/doorkeeper.rb b/config/initializers/doorkeeper.rb index a1bc85d76..be3dd4cd2 100644 --- a/config/initializers/doorkeeper.rb +++ b/config/initializers/doorkeeper.rb @@ -7,7 +7,7 @@ Doorkeeper.configure do # fail "Please configure doorkeeper resource_owner_authenticator block located in #{__FILE__}" # Put your resource owner authentication logic here. # Example implementation: - User.find_by_id(session[:user_id]) || redirect_to(new_user_session_url) + User.find_by(id: session[:user_id]) || redirect_to(new_user_session_url) end # If you want to restrict access to the web interface for adding oauth authorized applications, you need to declare the block below. diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb index 6c009f1e7..66d608e63 100644 --- a/config/initializers/filter_parameter_logging.rb +++ b/config/initializers/filter_parameter_logging.rb @@ -1,4 +1,4 @@ # Be sure to restart your server when you modify this file. # Configure sensitive parameters which will be filtered from the log file. -Rails.application.config.filter_parameters += [:password, :bind_pw] +Rails.application.config.filter_parameters += %i[password bind_pw] diff --git a/config/initializers/html_email_style.rb b/config/initializers/html_email_style.rb index b963a13dd..8561d3a7e 100644 --- a/config/initializers/html_email_style.rb +++ b/config/initializers/html_email_style.rb @@ -1,81 +1,81 @@ Rails.application.config.html_email_css_font = "font-family:'Helvetica Neue', Helvetica, Arial, Geneva, sans-serif; font-size: 12px;" -Rails.application.config.html_email_body = < - - - - - - - ###html### - +Rails.application.config.html_email_body = <<~HERE + + + + + + + + ###html### + HERE diff --git a/config/initializers/html_sanitizer.rb b/config/initializers/html_sanitizer.rb index 387fd5fdd..5d7716340 100644 --- a/config/initializers/html_sanitizer.rb +++ b/config/initializers/html_sanitizer.rb @@ -1,16 +1,16 @@ # content of this tags will also be removed -Rails.application.config.html_sanitizer_tags_remove_content = %w( +Rails.application.config.html_sanitizer_tags_remove_content = %w[ style -) +] # content of this tags will will be inserted html quoted -Rails.application.config.html_sanitizer_tags_quote_content = %w( +Rails.application.config.html_sanitizer_tags_quote_content = %w[ script -) +] # only this tags are allowed -Rails.application.config.html_sanitizer_tags_whitelist = %w( +Rails.application.config.html_sanitizer_tags_whitelist = %w[ a abbr acronym address area article aside audio b bdi bdo big blockquote br canvas caption center cite code col colgroup command @@ -20,44 +20,44 @@ Rails.application.config.html_sanitizer_tags_whitelist = %w( ol output optgroup option p pre q s samp section small span strike strong sub summary sup text table tbody td tfoot th thead time tr tt u ul var video -) +] # attributes allowed for tags Rails.application.config.html_sanitizer_attributes_whitelist = { - :all => %w(class dir lang title translate data-signature data-signature-id), - 'a' => %w(href hreflang name rel), - 'abbr' => %w(title), - 'blockquote' => %w(type cite), - 'col' => %w(span width), - 'colgroup' => %w(span width), - 'data' => %w(value), - 'del' => %w(cite datetime), - 'dfn' => %w(title), - 'img' => %w(align alt border height src srcset width style), - 'ins' => %w(cite datetime), - 'li' => %w(value), - 'ol' => %w(reversed start type), - 'table' => %w(align bgcolor border cellpadding cellspacing frame rules sortable summary width style), - 'td' => %w(abbr align axis colspan headers rowspan valign width style), - 'th' => %w(abbr align axis colspan headers rowspan scope sorted valign width style), - 'tr' => %w(width style), - 'ul' => %w(type), - 'q' => %w(cite), - 'span' => %w(style), - 'time' => %w(datetime pubdate), + :all => %w[class dir lang title translate data-signature data-signature-id], + 'a' => %w[href hreflang name rel], + 'abbr' => %w[title], + 'blockquote' => %w[type cite], + 'col' => %w[span width], + 'colgroup' => %w[span width], + 'data' => %w[value], + 'del' => %w[cite datetime], + 'dfn' => %w[title], + 'img' => %w[align alt border height src srcset width style], + 'ins' => %w[cite datetime], + 'li' => %w[value], + 'ol' => %w[reversed start type], + 'table' => %w[align bgcolor border cellpadding cellspacing frame rules sortable summary width style], + 'td' => %w[abbr align axis colspan headers rowspan valign width style], + 'th' => %w[abbr align axis colspan headers rowspan scope sorted valign width style], + 'tr' => %w[width style], + 'ul' => %w[type], + 'q' => %w[cite], + 'span' => %w[style], + 'time' => %w[datetime pubdate], } # only this css properties are allowed Rails.application.config.html_sanitizer_css_properties_whitelist = { - 'img' => %w( + 'img' => %w[ width height max-width min-width max-height min-height - ), - 'span' => %w( + ], + 'span' => %w[ color - ), - 'table' => %w( + ], + 'table' => %w[ background background-color color font-size vertical-align margin margin-top margin-right margin-bottom margin-left padding padding-top padding-right padding-bottom padding-left @@ -73,8 +73,8 @@ Rails.application.config.html_sanitizer_css_properties_whitelist = { border-right-color border-bottom-color border-left-color - ), - 'th' => %w( + ], + 'th' => %w[ background background-color color font-size vertical-align margin margin-top margin-right margin-bottom margin-left padding padding-top padding-right padding-bottom padding-left @@ -90,8 +90,8 @@ Rails.application.config.html_sanitizer_css_properties_whitelist = { border-right-color border-bottom-color border-left-color - ), - 'tr' => %w( + ], + 'tr' => %w[ background background-color color font-size vertical-align margin margin-top margin-right margin-bottom margin-left padding padding-top padding-right padding-bottom padding-left @@ -107,8 +107,8 @@ Rails.application.config.html_sanitizer_css_properties_whitelist = { border-right-color border-bottom-color border-left-color - ), - 'td' => %w( + ], + 'td' => %w[ background background-color color font-size vertical-align margin margin-top margin-right margin-bottom margin-left padding padding-top padding-right padding-bottom padding-left @@ -124,5 +124,5 @@ Rails.application.config.html_sanitizer_css_properties_whitelist = { border-right-color border-bottom-color border-left-color - ), + ], } diff --git a/config/initializers/vendor_lib.rb b/config/initializers/vendor_lib.rb index 9367719f8..73c004c7a 100644 --- a/config/initializers/vendor_lib.rb +++ b/config/initializers/vendor_lib.rb @@ -1,5 +1,5 @@ # load all vendor/lib extentions -Dir["#{Rails.root}/vendor/lib/*"].each do |file| +Dir[ Rails.root.join('vendor', 'lib', '*') ].each do |file| if File.file?(file) require file end diff --git a/config/routes.rb b/config/routes.rb index 93f9a8a50..d523fcc7f 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -18,6 +18,6 @@ Rails.application.routes.draw do end end - match '*a', to: 'errors#routing', via: [:get, :post, :put, :delete] + match '*a', to: 'errors#routing', via: %i[get post put delete] end diff --git a/config/routes/auth.rb b/config/routes/auth.rb index 50a77195f..b6fc7a6ea 100644 --- a/config/routes/auth.rb +++ b/config/routes/auth.rb @@ -2,15 +2,15 @@ Zammad::Application.routes.draw do api_path = Rails.configuration.api_path # omniauth - match '/auth/:provider/callback', to: 'sessions#create_omniauth', via: [:post, :get, :puts, :delete] + match '/auth/:provider/callback', to: 'sessions#create_omniauth', via: %i[post get puts delete] # sso - match '/auth/sso', to: 'sessions#create_sso', via: [:post, :get] + match '/auth/sso', to: 'sessions#create_sso', via: %i[post get] # sessions match api_path + '/signin', to: 'sessions#create', via: :post - match api_path + '/signshow', to: 'sessions#show', via: [:get, :post] - match api_path + '/signout', to: 'sessions#destroy', via: [:get, :delete] + match api_path + '/signshow', to: 'sessions#show', via: %i[get post] + match api_path + '/signout', to: 'sessions#destroy', via: %i[get delete] match api_path + '/available', to: 'sessions#available', via: :get diff --git a/config/routes/message.rb b/config/routes/message.rb index 67b748557..6d44d39f5 100644 --- a/config/routes/message.rb +++ b/config/routes/message.rb @@ -2,7 +2,7 @@ Zammad::Application.routes.draw do api_path = Rails.configuration.api_path # messages - match api_path + '/message_send', to: 'long_polling#message_send', via: [ :get, :post ] - match api_path + '/message_receive', to: 'long_polling#message_receive', via: [ :get, :post ] + match api_path + '/message_send', to: 'long_polling#message_send', via: %i[get post] + match api_path + '/message_receive', to: 'long_polling#message_receive', via: %i[get post] end diff --git a/config/routes/organization.rb b/config/routes/organization.rb index b7c95c5d2..930a6c393 100644 --- a/config/routes/organization.rb +++ b/config/routes/organization.rb @@ -2,7 +2,7 @@ Zammad::Application.routes.draw do api_path = Rails.configuration.api_path # organizations - match api_path + '/organizations/search', to: 'organizations#search', via: [:get, :post] + match api_path + '/organizations/search', to: 'organizations#search', via: %i[get post] match api_path + '/organizations', to: 'organizations#index', via: :get match api_path + '/organizations/:id', to: 'organizations#show', via: :get match api_path + '/organizations', to: 'organizations#create', via: :post diff --git a/config/routes/report.rb b/config/routes/report.rb index 8fe454b89..5784d775b 100644 --- a/config/routes/report.rb +++ b/config/routes/report.rb @@ -4,7 +4,7 @@ Zammad::Application.routes.draw do # reports match api_path + '/reports/config', to: 'reports#reporting_config', via: :get match api_path + '/reports/generate', to: 'reports#generate', via: :post - match api_path + '/reports/sets', to: 'reports#sets', via: [:post, :get] + match api_path + '/reports/sets', to: 'reports#sets', via: %i[post get] # report_profiles match api_path + '/report_profiles', to: 'report_profiles#index', via: :get diff --git a/config/routes/search.rb b/config/routes/search.rb index fd4b0fb94..df1382f79 100644 --- a/config/routes/search.rb +++ b/config/routes/search.rb @@ -2,6 +2,6 @@ Zammad::Application.routes.draw do api_path = Rails.configuration.api_path # search - match api_path + '/search', to: 'search#search_generic', via: [:get, :post] - match api_path + '/search/:objects', to: 'search#search_generic', via: [:get, :post] + match api_path + '/search', to: 'search#search_generic', via: %i[get post] + match api_path + '/search/:objects', to: 'search#search_generic', via: %i[get post] end diff --git a/config/routes/ticket.rb b/config/routes/ticket.rb index 6dc60d9b3..0e12e66e0 100644 --- a/config/routes/ticket.rb +++ b/config/routes/ticket.rb @@ -2,7 +2,7 @@ Zammad::Application.routes.draw do api_path = Rails.configuration.api_path # tickets - match api_path + '/tickets/search', to: 'tickets#search', via: [:get, :post] + match api_path + '/tickets/search', to: 'tickets#search', via: %i[get post] match api_path + '/tickets/selector', to: 'tickets#selector', via: :post match api_path + '/tickets', to: 'tickets#index', via: :get match api_path + '/tickets/:id', to: 'tickets#show', via: :get diff --git a/config/routes/user.rb b/config/routes/user.rb index 0f66db41c..7847d30e3 100644 --- a/config/routes/user.rb +++ b/config/routes/user.rb @@ -2,8 +2,8 @@ Zammad::Application.routes.draw do api_path = Rails.configuration.api_path # users - match api_path + '/users/search', to: 'users#search', via: [:get, :post] - match api_path + '/users/recent', to: 'users#recent', via: [:get, :post] + match api_path + '/users/search', to: 'users#search', via: %i[get post] + match api_path + '/users/recent', to: 'users#recent', via: %i[get post] match api_path + '/users/password_reset', to: 'users#password_reset_send', via: :post match api_path + '/users/password_reset_verify', to: 'users#password_reset_verify', via: :post match api_path + '/users/password_change', to: 'users#password_change', via: :post diff --git a/db/migrate/20120101000001_create_base.rb b/db/migrate/20120101000001_create_base.rb index ea1212388..c74f50836 100644 --- a/db/migrate/20120101000001_create_base.rb +++ b/db/migrate/20120101000001_create_base.rb @@ -58,7 +58,7 @@ class CreateBase < ActiveRecord::Migration[4.2] add_index :users, [:phone] add_index :users, [:fax] add_index :users, [:mobile] - add_index :users, [:out_of_office, :out_of_office_start_at, :out_of_office_end_at], name: 'index_out_of_office' + add_index :users, %i[out_of_office out_of_office_start_at out_of_office_end_at], name: 'index_out_of_office' add_index :users, [:out_of_office_replacement_id] add_index :users, [:source] add_index :users, [:created_by_id] @@ -207,7 +207,7 @@ class CreateBase < ActiveRecord::Migration[4.2] t.references :user, null: false t.timestamps limit: 3, null: false end - add_index :authorizations, [:uid, :provider] + add_index :authorizations, %i[uid provider] add_index :authorizations, [:user_id] add_index :authorizations, [:username] add_foreign_key :authorizations, :users @@ -262,7 +262,7 @@ class CreateBase < ActiveRecord::Migration[4.2] t.timestamps limit: 3, null: false end add_index :tokens, :user_id - add_index :tokens, [:name, :action], unique: true + add_index :tokens, %i[name action], unique: true add_index :tokens, :created_at add_index :tokens, :persistent add_foreign_key :tokens, :users @@ -454,7 +454,7 @@ class CreateBase < ActiveRecord::Migration[4.2] t.integer :created_by_id, null: false t.timestamps limit: 3, null: false end - add_index :stores, [:store_object_id, :o_id] + add_index :stores, %i[store_object_id o_id] add_foreign_key :stores, :store_objects add_foreign_key :stores, :store_files add_foreign_key :stores, :users, column: :created_by_id @@ -481,7 +481,7 @@ class CreateBase < ActiveRecord::Migration[4.2] t.integer :created_by_id, null: false t.timestamps limit: 3, null: false end - add_index :avatars, [:o_id, :object_lookup_id] + add_index :avatars, %i[o_id object_lookup_id] add_index :avatars, [:store_hash] add_index :avatars, [:source] add_index :avatars, [:default] @@ -556,7 +556,7 @@ class CreateBase < ActiveRecord::Migration[4.2] t.timestamps limit: 3, null: false end add_index :user_devices, [:user_id] - add_index :user_devices, [:os, :browser, :location] + add_index :user_devices, %i[os browser location] add_index :user_devices, [:fingerprint] add_index :user_devices, [:updated_at] add_index :user_devices, [:created_at] @@ -587,7 +587,7 @@ class CreateBase < ActiveRecord::Migration[4.2] t.integer :updated_by_id, null: false t.timestamps limit: 3, null: false end - add_index :object_manager_attributes, [:object_lookup_id, :name], unique: true + add_index :object_manager_attributes, %i[object_lookup_id name], unique: true add_index :object_manager_attributes, [:object_lookup_id] add_foreign_key :object_manager_attributes, :object_lookups add_foreign_key :object_manager_attributes, :users, column: :created_by_id @@ -606,7 +606,7 @@ class CreateBase < ActiveRecord::Migration[4.2] t.timestamps limit: 3, null: false end - add_index :delayed_jobs, [:priority, :run_at], name: 'delayed_jobs_priority' + add_index :delayed_jobs, %i[priority run_at], name: 'delayed_jobs_priority' create_table :external_syncs do |t| t.string :source, limit: 100, null: false @@ -616,9 +616,9 @@ class CreateBase < ActiveRecord::Migration[4.2] t.text :last_payload, limit: 500.kilobytes + 1, null: true t.timestamps limit: 3, null: false end - add_index :external_syncs, [:source, :source_id], unique: true - add_index :external_syncs, [:source, :source_id, :object, :o_id], name: 'index_external_syncs_on_source_and_source_id_and_object_o_id' - add_index :external_syncs, [:object, :o_id] + add_index :external_syncs, %i[source source_id], unique: true + add_index :external_syncs, %i[source source_id object o_id], name: 'index_external_syncs_on_source_and_source_id_and_object_o_id' + add_index :external_syncs, %i[object o_id] create_table :import_jobs do |t| t.string :name, limit: 250, null: false @@ -664,9 +664,9 @@ class CreateBase < ActiveRecord::Migration[4.2] t.timestamps limit: 3, null: false end add_index :cti_caller_ids, [:caller_id] - add_index :cti_caller_ids, [:caller_id, :level] - add_index :cti_caller_ids, [:caller_id, :user_id] - add_index :cti_caller_ids, [:object, :o_id] + add_index :cti_caller_ids, %i[caller_id level] + add_index :cti_caller_ids, %i[caller_id user_id] + add_index :cti_caller_ids, %i[object o_id] add_foreign_key :cti_caller_ids, :users create_table :stats_stores do |t| diff --git a/db/migrate/20120101000010_create_ticket.rb b/db/migrate/20120101000010_create_ticket.rb index c7d5c9bbb..726eede9f 100644 --- a/db/migrate/20120101000010_create_ticket.rb +++ b/db/migrate/20120101000010_create_ticket.rb @@ -127,8 +127,8 @@ class CreateTicket < ActiveRecord::Migration[4.2] t.column :created_by_id, :integer, null: false t.timestamps limit: 3, null: false end - add_index :ticket_flags, [:ticket_id, :created_by_id] - add_index :ticket_flags, [:ticket_id, :key] + add_index :ticket_flags, %i[ticket_id created_by_id] + add_index :ticket_flags, %i[ticket_id key] add_index :ticket_flags, [:ticket_id] add_index :ticket_flags, [:created_by_id] add_foreign_key :ticket_flags, :tickets, column: :ticket_id @@ -182,7 +182,7 @@ class CreateTicket < ActiveRecord::Migration[4.2] end add_index :ticket_articles, [:ticket_id] add_index :ticket_articles, [:message_id_md5] - add_index :ticket_articles, [:message_id_md5, :type_id], name: 'index_ticket_articles_message_id_md5_type_id' + add_index :ticket_articles, %i[message_id_md5 type_id], name: 'index_ticket_articles_message_id_md5_type_id' add_index :ticket_articles, [:created_by_id] add_index :ticket_articles, [:created_at] add_index :ticket_articles, [:internal] @@ -202,8 +202,8 @@ class CreateTicket < ActiveRecord::Migration[4.2] t.column :created_by_id, :integer, null: false t.timestamps limit: 3, null: false end - add_index :ticket_article_flags, [:ticket_article_id, :created_by_id], name: 'index_ticket_article_flags_on_articles_id_and_created_by_id' - add_index :ticket_article_flags, [:ticket_article_id, :key] + add_index :ticket_article_flags, %i[ticket_article_id created_by_id], name: 'index_ticket_article_flags_on_articles_id_and_created_by_id' + add_index :ticket_article_flags, %i[ticket_article_id key] add_index :ticket_article_flags, [:ticket_article_id] add_index :ticket_article_flags, [:created_by_id] add_foreign_key :ticket_article_flags, :ticket_articles, column: :ticket_article_id @@ -346,7 +346,7 @@ class CreateTicket < ActiveRecord::Migration[4.2] t.column :link_object_target_value, :integer, null: false t.timestamps limit: 3, null: false end - add_index :links, [:link_object_source_id, :link_object_source_value, :link_object_target_id, :link_object_target_value, :link_type_id], unique: true, name: 'links_uniq_total' + add_index :links, %i[link_object_source_id link_object_source_value link_object_target_id link_object_target_value link_type_id], unique: true, name: 'links_uniq_total' add_foreign_key :links, :link_types create_table :postmaster_filters do |t| @@ -572,7 +572,7 @@ class CreateTicket < ActiveRecord::Migration[4.2] end add_index :karma_activity_logs, [:user_id] add_index :karma_activity_logs, [:created_at] - add_index :karma_activity_logs, [:o_id, :object_lookup_id] + add_index :karma_activity_logs, %i[o_id object_lookup_id] add_foreign_key :karma_activity_logs, :users add_foreign_key :karma_activity_logs, :karma_activities, column: :activity_id end diff --git a/db/migrate/20150979000001_update_timestamps.rb b/db/migrate/20150979000001_update_timestamps.rb index 075a73528..3f476ac0c 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 do |_model, value| + Models.all.each_value do |value| next if !value next if !value[:attributes] if value[:attributes].include?('changed_at') diff --git a/db/migrate/20160217000001_object_manager_update_user.rb b/db/migrate/20160217000001_object_manager_update_user.rb index e9a0f007b..5d307ae1e 100644 --- a/db/migrate/20160217000001_object_manager_update_user.rb +++ b/db/migrate/20160217000001_object_manager_update_user.rb @@ -1,3 +1,4 @@ +# rubocop:disable Lint/BooleanSymbol class ObjectManagerUpdateUser < ActiveRecord::Migration[4.2] def up diff --git a/db/migrate/20161112000001_organization_domain_based_assignment.rb b/db/migrate/20161112000001_organization_domain_based_assignment.rb index 7ca282bc2..afce02e32 100644 --- a/db/migrate/20161112000001_organization_domain_based_assignment.rb +++ b/db/migrate/20161112000001_organization_domain_based_assignment.rb @@ -1,3 +1,4 @@ +# rubocop:disable Lint/BooleanSymbol class OrganizationDomainBasedAssignment < ActiveRecord::Migration[4.2] def up # return if it's a new setup diff --git a/db/migrate/20161117000002_ticket_number_generator_issue_427.rb b/db/migrate/20161117000002_ticket_number_generator_issue_427.rb index 05f440bcb..0200184e2 100644 --- a/db/migrate/20161117000002_ticket_number_generator_issue_427.rb +++ b/db/migrate/20161117000002_ticket_number_generator_issue_427.rb @@ -5,7 +5,7 @@ class TicketNumberGeneratorIssue427 < ActiveRecord::Migration[4.2] setting = Setting.find_by(name: 'ticket_number') setting.preferences = { - settings_included: %w(ticket_number_increment ticket_number_date), + settings_included: %w[ticket_number_increment ticket_number_date], controller: 'SettingsAreaTicketNumber', permission: ['admin.ticket'], } diff --git a/db/migrate/20170403000001_fixed_admin_user_permission_920.rb b/db/migrate/20170403000001_fixed_admin_user_permission_920.rb index 8209aaeb3..c1387387b 100644 --- a/db/migrate/20170403000001_fixed_admin_user_permission_920.rb +++ b/db/migrate/20170403000001_fixed_admin_user_permission_920.rb @@ -1,3 +1,4 @@ +# rubocop:disable Lint/BooleanSymbol class FixedAdminUserPermission920 < ActiveRecord::Migration[4.2] def up @@ -337,7 +338,10 @@ class FixedAdminUserPermission920 < ActiveRecord::Migration[4.2] display: 'Visibility', data_type: 'select', data_option: { - options: { true: 'internal', false: 'public' }, + options: { + true: 'internal', + false: 'public' + }, nulloption: false, multiple: false, null: true, diff --git a/db/migrate/20170419000001_ldap_support.rb b/db/migrate/20170419000001_ldap_support.rb index 1429e6627..5984098d0 100644 --- a/db/migrate/20170419000001_ldap_support.rb +++ b/db/migrate/20170419000001_ldap_support.rb @@ -32,7 +32,7 @@ class LdapSupport < ActiveRecord::Migration[4.2] }, state: { adapter: 'Auth::Ldap', - login_attributes: %w(login email), + login_attributes: %w[login email], }, frontend: false ) diff --git a/db/migrate/20170531144425_foreign_keys.rb b/db/migrate/20170531144425_foreign_keys.rb index 696b79134..71699646e 100644 --- a/db/migrate/20170531144425_foreign_keys.rb +++ b/db/migrate/20170531144425_foreign_keys.rb @@ -13,7 +13,7 @@ class ForeignKeys < ActiveRecord::Migration[4.2] # add missing foreign keys foreign_keys = [ # Base - [:users, :organizations], + %i[users organizations], [:users, :users, column: :created_by_id], [:users, :users, column: :updated_by_id], @@ -23,8 +23,8 @@ class ForeignKeys < ActiveRecord::Migration[4.2] [:email_addresses, :users, column: :created_by_id], [:email_addresses, :users, column: :updated_by_id], - [:groups, :signatures], - [:groups, :email_addresses], + %i[groups signatures], + %i[groups email_addresses], [:groups, :users, column: :created_by_id], [:groups, :users, column: :updated_by_id], @@ -34,29 +34,29 @@ class ForeignKeys < ActiveRecord::Migration[4.2] [:organizations, :users, column: :created_by_id], [:organizations, :users, column: :updated_by_id], - [:roles_users, :users], - [:roles_users, :roles], + %i[roles_users users], + %i[roles_users roles], - [:groups_users, :users], - [:groups_users, :groups], + %i[groups_users users], + %i[groups_users groups], - [:organizations_users, :users], - [:organizations_users, :organizations], + %i[organizations_users users], + %i[organizations_users organizations], - [:authorizations, :users], + %i[authorizations users], [:translations, :users, column: :created_by_id], [:translations, :users, column: :updated_by_id], - [:tokens, :users], + %i[tokens users], [:packages, :users, column: :created_by_id], [:packages, :users, column: :updated_by_id], - [:taskbars, :users], + %i[taskbars users], - [:tags, :tag_items], - [:tags, :tag_objects], + %i[tags tag_items], + %i[tags tag_objects], [:tags, :users, column: :created_by_id], [:recent_views, :object_lookups, column: :recent_view_object_id], @@ -64,17 +64,17 @@ class ForeignKeys < ActiveRecord::Migration[4.2] [:activity_streams, :type_lookups, column: :activity_stream_type_id], [:activity_streams, :object_lookups, column: :activity_stream_object_id], - [:activity_streams, :permissions], - [:activity_streams, :groups], + %i[activity_streams permissions], + %i[activity_streams groups], [:activity_streams, :users, column: :created_by_id], - [:histories, :history_types], - [:histories, :history_objects], - [:histories, :history_attributes], + %i[histories history_types], + %i[histories history_objects], + %i[histories history_attributes], [:histories, :users, column: :created_by_id], - [:stores, :store_objects], - [:stores, :store_files], + %i[stores store_objects], + %i[stores store_files], [:stores, :users, column: :created_by_id], [:avatars, :users, column: :created_by_id], @@ -89,13 +89,13 @@ class ForeignKeys < ActiveRecord::Migration[4.2] [:calendars, :users, column: :created_by_id], [:calendars, :users, column: :updated_by_id], - [:user_devices, :users], + %i[user_devices users], - [:object_manager_attributes, :object_lookups], + %i[object_manager_attributes object_lookups], [:object_manager_attributes, :users, column: :created_by_id], [:object_manager_attributes, :users, column: :updated_by_id], - [:cti_caller_ids, :users], + %i[cti_caller_ids users], [:stats_stores, :users, column: :created_by_id], @@ -113,12 +113,12 @@ class ForeignKeys < ActiveRecord::Migration[4.2] [:ticket_priorities, :users, column: :created_by_id], [:ticket_priorities, :users, column: :updated_by_id], - [:tickets, :groups], + %i[tickets groups], [:tickets, :users, column: :owner_id], [:tickets, :users, column: :customer_id], [:tickets, :ticket_priorities, column: :priority_id], [:tickets, :ticket_states, column: :state_id], - [:tickets, :organizations], + %i[tickets organizations], [:tickets, :users, column: :created_by_id], [:tickets, :users, column: :updated_by_id], @@ -131,7 +131,7 @@ class ForeignKeys < ActiveRecord::Migration[4.2] [:ticket_article_senders, :users, column: :created_by_id], [:ticket_article_senders, :users, column: :updated_by_id], - [:ticket_articles, :tickets], + %i[ticket_articles tickets], [:ticket_articles, :ticket_article_types, column: :type_id], [:ticket_articles, :ticket_article_senders, column: :sender_id], [:ticket_articles, :users, column: :created_by_id], @@ -141,21 +141,21 @@ class ForeignKeys < ActiveRecord::Migration[4.2] [:ticket_article_flags, :ticket_articles, column: :ticket_article_id], [:ticket_article_flags, :users, column: :created_by_id], - [:ticket_time_accountings, :tickets], - [:ticket_time_accountings, :ticket_articles], + %i[ticket_time_accountings tickets], + %i[ticket_time_accountings ticket_articles], [:ticket_time_accountings, :users, column: :created_by_id], [:overviews, :users, column: :created_by_id], [:overviews, :users, column: :updated_by_id], - [:overviews_roles, :overviews], - [:overviews_roles, :roles], + %i[overviews_roles overviews], + %i[overviews_roles roles], - [:overviews_users, :overviews], - [:overviews_users, :users], + %i[overviews_users overviews], + %i[overviews_users users], - [:overviews_groups, :overviews], - [:overviews_groups, :groups], + %i[overviews_groups overviews], + %i[overviews_groups groups], [:triggers, :users, column: :created_by_id], [:triggers, :users, column: :updated_by_id], @@ -163,26 +163,26 @@ class ForeignKeys < ActiveRecord::Migration[4.2] [:jobs, :users, column: :created_by_id], [:jobs, :users, column: :updated_by_id], - [:links, :link_types], + %i[links link_types], [:postmaster_filters, :users, column: :created_by_id], [:postmaster_filters, :users, column: :updated_by_id], - [:text_modules, :users], + %i[text_modules users], [:text_modules, :users, column: :created_by_id], [:text_modules, :users, column: :updated_by_id], - [:text_modules_groups, :text_modules], - [:text_modules_groups, :groups], + %i[text_modules_groups text_modules], + %i[text_modules_groups groups], - [:templates, :users], + %i[templates users], [:templates, :users, column: :created_by_id], [:templates, :users, column: :updated_by_id], - [:templates_groups, :templates], - [:templates_groups, :groups], + %i[templates_groups templates], + %i[templates_groups groups], - [:channels, :groups], + %i[channels groups], [:channels, :users, column: :created_by_id], [:channels, :users, column: :updated_by_id], @@ -198,12 +198,12 @@ class ForeignKeys < ActiveRecord::Migration[4.2] [:chat_topics, :users, column: :created_by_id], [:chat_topics, :users, column: :updated_by_id], - [:chat_sessions, :chats], - [:chat_sessions, :users], + %i[chat_sessions chats], + %i[chat_sessions users], [:chat_sessions, :users, column: :created_by_id], [:chat_sessions, :users, column: :updated_by_id], - [:chat_messages, :chat_sessions], + %i[chat_messages chat_sessions], [:chat_messages, :users, column: :created_by_id], [:chat_agents, :users, column: :created_by_id], @@ -212,9 +212,9 @@ class ForeignKeys < ActiveRecord::Migration[4.2] [:report_profiles, :users, column: :created_by_id], [:report_profiles, :users, column: :updated_by_id], - [:karma_users, :users], + %i[karma_users users], - [:karma_activity_logs, :users], + %i[karma_activity_logs users], [:karma_activity_logs, :karma_activities, column: :activity_id], ] diff --git a/db/migrate/20170905140038_cti_log_preferences_migration.rb b/db/migrate/20170905140038_cti_log_preferences_migration.rb index 16c0c3a67..513473a5f 100644 --- a/db/migrate/20170905140038_cti_log_preferences_migration.rb +++ b/db/migrate/20170905140038_cti_log_preferences_migration.rb @@ -42,7 +42,7 @@ class CtiLogPreferencesMigration < ActiveRecord::Migration[5.0] # check from and to keys which hold the instances preferences = {} - %w(from to).each do |direction| + %w[from to].each do |direction| next if item.preferences[direction].blank? # loop over all instances and covert them @@ -57,7 +57,7 @@ class CtiLogPreferencesMigration < ActiveRecord::Migration[5.0] end # update entry - item.update_column(:preferences, preferences) + item.update_column(:preferences, preferences) # rubocop:disable Rails/SkipsModelValidations end end end diff --git a/db/migrate/20170908000001_fixed_twitter_ticket_article_preferences4.rb b/db/migrate/20170908000001_fixed_twitter_ticket_article_preferences4.rb index 76e07c07d..77979d462 100644 --- a/db/migrate/20170908000001_fixed_twitter_ticket_article_preferences4.rb +++ b/db/migrate/20170908000001_fixed_twitter_ticket_article_preferences4.rb @@ -11,7 +11,7 @@ class FixedTwitterTicketArticlePreferences4 < ActiveRecord::Migration[5.0] article = Ticket::Article.find(article_id) next if !article.preferences changed = false - article.preferences.each do |_key, value| + article.preferences.each_value do |value| next if value.class != ActiveSupport::HashWithIndifferentAccess value.each do |sub_key, sub_level| if sub_level.class == NilClass diff --git a/db/migrate/20170910000002_out_of_office2.rb b/db/migrate/20170910000002_out_of_office2.rb index a3819e741..dae2ce062 100644 --- a/db/migrate/20170910000002_out_of_office2.rb +++ b/db/migrate/20170910000002_out_of_office2.rb @@ -15,7 +15,7 @@ class OutOfOffice2 < ActiveRecord::Migration[4.2] add_column :users, :out_of_office_end_at, :date, null: true add_column :users, :out_of_office_replacement_id, :integer, null: true - add_index :users, [:out_of_office, :out_of_office_start_at, :out_of_office_end_at], name: 'index_out_of_office' + add_index :users, %i[out_of_office out_of_office_start_at out_of_office_end_at], name: 'index_out_of_office' add_index :users, [:out_of_office_replacement_id] add_foreign_key :users, :users, column: :out_of_office_replacement_id User.reset_column_information @@ -44,9 +44,9 @@ class OutOfOffice2 < ActiveRecord::Migration[4.2] direction: 'DESC', }, view: { - d: %w(title customer group owner escalation_at), - s: %w(title customer group owner escalation_at), - m: %w(number title customer group owner escalation_at), + d: %w[title customer group owner escalation_at], + s: %w[title customer group owner escalation_at], + m: %w[number title customer group owner escalation_at], view_mode_default: 's', }, updated_by_id: 1, diff --git a/db/migrate/20170912123300_remove_network.rb b/db/migrate/20170912123300_remove_network.rb index f64f646de..fa8f29434 100644 --- a/db/migrate/20170912123300_remove_network.rb +++ b/db/migrate/20170912123300_remove_network.rb @@ -1,3 +1,4 @@ +# rubocop:disable Rails/ReversibleMigration class RemoveNetwork < ActiveRecord::Migration[5.0] # rewinds db/migrate/20120101000020_create_network.rb diff --git a/db/seeds.rb b/db/seeds.rb index 2623896cc..87dbec1e4 100644 --- a/db/seeds.rb +++ b/db/seeds.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # @@ -13,7 +12,7 @@ Cache.clear # this is the __ordered__ list of seed files # extend only if needed - try to add your changes # to the matching one of the existing files -seeds = %w(settings user_nr_1 signatures roles permissions groups links ticket_state_types ticket_states ticket_priorities ticket_article_types ticket_article_senders macros community_user_resources overviews channels report_profiles chats object_manager_attributes schedulers triggers karma_activities) +seeds = %w[settings user_nr_1 signatures roles permissions groups links ticket_state_types ticket_states ticket_priorities ticket_article_types ticket_article_senders macros community_user_resources overviews channels report_profiles chats object_manager_attributes schedulers triggers karma_activities] # loop and require all seedfiles # files will get executed automatically diff --git a/db/seeds/object_manager_attributes.rb b/db/seeds/object_manager_attributes.rb index 41ab17826..560b3a210 100644 --- a/db/seeds/object_manager_attributes.rb +++ b/db/seeds/object_manager_attributes.rb @@ -1,3 +1,4 @@ +# rubocop:disable Lint/BooleanSymbol ObjectManager::Attribute.add( force: true, object: 'Ticket', @@ -359,7 +360,10 @@ ObjectManager::Attribute.add( display: 'Visibility', data_type: 'select', data_option: { - options: { true: 'internal', false: 'public' }, + options: { + true: 'internal', + false: 'public' + }, nulloption: false, multiple: false, null: true, diff --git a/db/seeds/overviews.rb b/db/seeds/overviews.rb index e274c533b..65db69d50 100644 --- a/db/seeds/overviews.rb +++ b/db/seeds/overviews.rb @@ -19,9 +19,9 @@ Overview.create_if_not_exists( direction: 'ASC', }, view: { - d: %w(title customer group created_at), - s: %w(title customer group created_at), - m: %w(number title customer group created_at), + d: %w[title customer group created_at], + s: %w[title customer group created_at], + m: %w[number title customer group created_at], view_mode_default: 's', }, ) @@ -46,9 +46,9 @@ Overview.create_if_not_exists( direction: 'ASC', }, view: { - d: %w(title customer group created_at), - s: %w(title customer group created_at), - m: %w(number title customer group created_at), + d: %w[title customer group created_at], + s: %w[title customer group created_at], + m: %w[number title customer group created_at], view_mode_default: 's', }, ) @@ -78,9 +78,9 @@ Overview.create_if_not_exists( direction: 'ASC', }, view: { - d: %w(title customer group created_at), - s: %w(title customer group created_at), - m: %w(number title customer group created_at), + d: %w[title customer group created_at], + s: %w[title customer group created_at], + m: %w[number title customer group created_at], view_mode_default: 's', }, ) @@ -101,9 +101,9 @@ Overview.create_if_not_exists( direction: 'ASC', }, view: { - d: %w(title customer group state owner created_at), - s: %w(title customer group state owner created_at), - m: %w(number title customer group state owner created_at), + d: %w[title customer group state owner created_at], + s: %w[title customer group state owner created_at], + m: %w[number title customer group state owner created_at], view_mode_default: 's', }, ) @@ -129,9 +129,9 @@ Overview.create_if_not_exists( direction: 'ASC', }, view: { - d: %w(title customer group owner created_at), - s: %w(title customer group owner created_at), - m: %w(number title customer group owner created_at), + d: %w[title customer group owner created_at], + s: %w[title customer group owner created_at], + m: %w[number title customer group owner created_at], view_mode_default: 's', }, ) @@ -153,9 +153,9 @@ Overview.create_if_not_exists( direction: 'ASC', }, view: { - d: %w(title customer group owner escalation_at), - s: %w(title customer group owner escalation_at), - m: %w(number title customer group owner escalation_at), + d: %w[title customer group owner escalation_at], + s: %w[title customer group owner escalation_at], + m: %w[number title customer group owner escalation_at], view_mode_default: 's', }, ) @@ -181,9 +181,9 @@ Overview.create_if_not_exists( direction: 'DESC', }, view: { - d: %w(title customer group owner escalation_at), - s: %w(title customer group owner escalation_at), - m: %w(number title customer group owner escalation_at), + d: %w[title customer group owner escalation_at], + s: %w[title customer group owner escalation_at], + m: %w[number title customer group owner escalation_at], view_mode_default: 's', }, ) @@ -209,9 +209,9 @@ Overview.create_if_not_exists( direction: 'DESC', }, view: { - d: %w(title customer state created_at), - s: %w(number title state created_at), - m: %w(number title state created_at), + d: %w[title customer state created_at], + s: %w[number title state created_at], + m: %w[number title state created_at], view_mode_default: 's', }, ) @@ -236,9 +236,9 @@ Overview.create_if_not_exists( direction: 'DESC', }, view: { - d: %w(title customer state created_at), - s: %w(number title customer state created_at), - m: %w(number title customer state created_at), + d: %w[title customer state created_at], + s: %w[number title customer state created_at], + m: %w[number title customer state created_at], view_mode_default: 's', }, ) diff --git a/db/seeds/roles.rb b/db/seeds/roles.rb index a1bd66e6f..5f1a643af 100644 --- a/db/seeds/roles.rb +++ b/db/seeds/roles.rb @@ -25,7 +25,7 @@ Role.create_if_not_exists( name: 'Customer', note: 'People who create Tickets ask for help.', preferences: { - not: %w(Agent Admin), + not: %w[Agent Admin], }, default_at_signup: true, updated_by_id: 1, diff --git a/db/seeds/settings.rb b/db/seeds/settings.rb index decad0c72..25155d67a 100644 --- a/db/seeds/settings.rb +++ b/db/seeds/settings.rb @@ -236,7 +236,7 @@ Setting.create_if_not_exists( title: 'Fully Qualified Domain Name', name: 'fqdn', area: 'System::Base', - description: 'Defines the fully qualified domain name of the system. This setting is used as a variable, #{setting.fqdn} which is found in all forms of messaging used by the application, to build links to the tickets within your system.', + description: 'Defines the fully qualified domain name of the system. This setting is used as a variable, #{setting.fqdn} which is found in all forms of messaging used by the application, to build links to the tickets within your system.', # rubocop:disable Lint/InterpolationCheck options: { form: [ { @@ -792,7 +792,7 @@ Setting.create_if_not_exists( uid: 'mail', base: 'dc=example,dc=org', always_filter: '', - always_roles: %w(Admin Agent), + always_roles: %w[Admin Agent], always_groups: ['Users'], sync_params: { firstname: 'sn', @@ -1580,7 +1580,7 @@ Setting.create_if_not_exists( }, state: 'Ticket::Number::Increment', preferences: { - settings_included: %w(ticket_number_increment ticket_number_date), + settings_included: %w[ticket_number_increment ticket_number_date], controller: 'SettingsAreaTicketNumber', permission: ['admin.ticket'], }, @@ -2056,7 +2056,7 @@ Setting.create_if_not_exists( }, ], }, - state: 'Notification Master ', + state: 'Notification Master ', # rubocop:disable Lint/InterpolationCheck preferences: { online_service_disable: true, permission: ['admin.channel_email'], diff --git a/db/seeds/triggers.rb b/db/seeds/triggers.rb index 247d38314..8b07e0c57 100644 --- a/db/seeds/triggers.rb +++ b/db/seeds/triggers.rb @@ -34,7 +34,7 @@ Trigger.create_or_update(
Zammad, your customer support system
', 'recipient' => 'article_last_sender', - 'subject' => 'Thanks for your inquiry (#{ticket.title})', + 'subject' => 'Thanks for your inquiry (#{ticket.title})', # rubocop:disable Lint/InterpolationCheck }, }, active: true, @@ -73,7 +73,7 @@ Trigger.create_or_update(
Zammad, your customer support system
', 'recipient' => 'article_last_sender', - 'subject' => 'Thanks for your follow up (#{ticket.title})', + 'subject' => 'Thanks for your follow up (#{ticket.title})', # rubocop:disable Lint/InterpolationCheck }, }, active: false, @@ -101,7 +101,7 @@ Trigger.create_or_update(

Zammad, your customer support system

', 'recipient' => 'ticket_customer', - 'subject' => 'Owner has changed (#{ticket.title})', + 'subject' => 'Owner has changed (#{ticket.title})', # rubocop:disable Lint/InterpolationCheck }, }, active: false, diff --git a/lib/application_handle_info.rb b/lib/application_handle_info.rb index 854a9d8b4..78d4586c1 100644 --- a/lib/application_handle_info.rb +++ b/lib/application_handle_info.rb @@ -6,4 +6,9 @@ module ApplicationHandleInfo def self.current=(name) Thread.current[:application_handle] = name end + + def self.postmaster? + return false if current.blank? + current.split('.')[1] == 'postmaster' + end end diff --git a/lib/application_lib.rb b/lib/application_lib.rb index 53ab30f2b..7b3ace036 100644 --- a/lib/application_lib.rb +++ b/lib/application_lib.rb @@ -19,8 +19,7 @@ returns def load_adapter_by_setting(setting) adapter = Setting.get(setting) - return if !adapter - return if adapter.empty? + return if adapter.blank? # load backend load_adapter(adapter) diff --git a/lib/auth/ldap.rb b/lib/auth/ldap.rb index 475cf3be4..95fb38d2e 100644 --- a/lib/auth/ldap.rb +++ b/lib/auth/ldap.rb @@ -13,7 +13,7 @@ class Auth # get from config or fallback to login # for a list of user attributes which should # be used for logging in - login_attributes = @config[:login_attributes] || %w(login) + login_attributes = @config[:login_attributes] || %w[login] authed = login_attributes.any? do |attribute| ldap_user.valid?(user[attribute], password) diff --git a/lib/auto_wizard.rb b/lib/auto_wizard.rb index fd1267b0a..362a0819d 100644 --- a/lib/auto_wizard.rb +++ b/lib/auto_wizard.rb @@ -82,10 +82,8 @@ returns end # set Settings - if auto_wizard_hash['Settings'] - auto_wizard_hash['Settings'].each do |setting_data| - Setting.set(setting_data['name'], setting_data['value']) - end + auto_wizard_hash['Settings']&.each do |setting_data| + Setting.set(setting_data['name'], setting_data['value']) end # create Permissions/Organization @@ -103,32 +101,30 @@ returns end # create Users - if auto_wizard_hash['Users'] - auto_wizard_hash['Users'].each do |user_data| - user_data.symbolize_keys! + auto_wizard_hash['Users']&.each do |user_data| + user_data.symbolize_keys! - if admin_user.id == 1 - if !user_data[:roles] && !user_data[:role_ids] - user_data[:roles] = Role.where(name: %w(Agent Admin)) - end - if !user_data[:groups] && !user_data[:group_ids] - user_data[:groups] = Group.all - end + if admin_user.id == 1 + if !user_data[:roles] && !user_data[:role_ids] + user_data[:roles] = Role.where(name: %w[Agent Admin]) end - - created_user = User.create_or_update_with_ref(user_data) - - # use first created user as admin - next if admin_user.id != 1 - - admin_user = created_user - UserInfo.current_user_id = admin_user.id - - # fetch org logo - if admin_user.email.present? - Service::Image.organization_suggest(admin_user.email) + if !user_data[:groups] && !user_data[:group_ids] + user_data[:groups] = Group.all end end + + created_user = User.create_or_update_with_ref(user_data) + + # use first created user as admin + next if admin_user.id != 1 + + admin_user = created_user + UserInfo.current_user_id = admin_user.id + + # fetch org logo + if admin_user.email.present? + Service::Image.organization_suggest(admin_user.email) + end end # create EmailAddresses/Channels/Signatures @@ -158,7 +154,7 @@ returns def self.file_location auto_wizard_file_name = 'auto_wizard.json' - auto_wizard_file_location = "#{Rails.root}/#{auto_wizard_file_name}" + auto_wizard_file_location = Rails.root.join(auto_wizard_file_name) auto_wizard_file_location end private_class_method :file_location diff --git a/lib/calendar_subscriptions.rb b/lib/calendar_subscriptions.rb index fe7686064..1fd8d4ec1 100644 --- a/lib/calendar_subscriptions.rb +++ b/lib/calendar_subscriptions.rb @@ -15,14 +15,13 @@ class CalendarSubscriptions @preferences[ object_name ] = calendar_subscription.state_current[:value] end - return if !@user.preferences[:calendar_subscriptions] - return if @user.preferences[:calendar_subscriptions].empty? + return if @user.preferences[:calendar_subscriptions].blank? @preferences = @preferences.merge(@user.preferences[:calendar_subscriptions]) end def all events_data = [] - @preferences.each do |object_name, _sub_structure| + @preferences.each_key do |object_name| result = generic_call(object_name) events_data = events_data + result end @@ -39,7 +38,7 @@ class CalendarSubscriptions method_name ||= 'all' events_data = [] - if @preferences[ object_name ] && !@preferences[ object_name ].empty? + if @preferences[ object_name ].present? sub_class_name = object_name.to_s.capitalize object = Object.const_get("CalendarSubscriptions::#{sub_class_name}") instance = object.new(@user, @preferences[ object_name ]) diff --git a/lib/calendar_subscriptions/tickets.rb b/lib/calendar_subscriptions/tickets.rb index 571c2c698..10d788591 100644 --- a/lib/calendar_subscriptions/tickets.rb +++ b/lib/calendar_subscriptions/tickets.rb @@ -65,7 +65,7 @@ class CalendarSubscriptions::Tickets operator: 'is', value: Ticket::State.where( state_type_id: Ticket::StateType.where( - name: %w(new open), + name: %w[new open], ), ).map(&:id), }, diff --git a/lib/core_ext/integer.rb b/lib/core_ext/integer.rb deleted file mode 100644 index b3363b5f4..000000000 --- a/lib/core_ext/integer.rb +++ /dev/null @@ -1,17 +0,0 @@ -class Integer - -=begin - - result = 5.empty? - -result - - false - -=end - - def empty? - false - end - -end diff --git a/lib/core_ext/nil_class.rb b/lib/core_ext/nil_class.rb deleted file mode 100644 index 4b4a8878a..000000000 --- a/lib/core_ext/nil_class.rb +++ /dev/null @@ -1,17 +0,0 @@ -class NilClass - -=begin - - result = nil.empty? - -result - - true - -=end - - def empty? - true - end - -end diff --git a/lib/core_ext/open-uri.rb b/lib/core_ext/open-uri.rb index 703b20594..2a262b467 100644 --- a/lib/core_ext/open-uri.rb +++ b/lib/core_ext/open-uri.rb @@ -1,11 +1,12 @@ -# rubocop:disable Style/FileName +# rubocop:disable Naming/FileName +# rubocop:disable Style/CommentedKeyword if Kernel.respond_to?(:open_uri_original_open) module Kernel private # see: https://github.com/ruby/ruby/pull/1675 def open(name, *rest, &block) # :doc: - if name.respond_to?(:open) && !name.method(:open).parameters.empty? + if name.respond_to?(:open) && name.method(:open).parameters.present? name.open(*rest, &block) elsif name.respond_to?(:to_str) && %r{\A[A-Za-z][A-Za-z0-9+\-\.]*://} =~ name && diff --git a/lib/core_ext/string.rb b/lib/core_ext/string.rb index 9fda812e3..89c914bf4 100644 --- a/lib/core_ext/string.rb +++ b/lib/core_ext/string.rb @@ -37,7 +37,7 @@ class String def word_wrap(*args) options = args.extract_options! - unless args.blank? + if args.present? options[:line_width] = args[0] || 82 end options.reverse_merge!(line_width: 82) @@ -135,26 +135,26 @@ class String text.gsub!(/\<.+?\>/, '') link_compare = link.dup - if !link_compare.empty? + if link_compare.present? link.strip! link_compare.strip! link_compare.downcase! link_compare.sub!(%r{/$}, '') end text_compare = text.dup - if !text_compare.empty? + if text_compare.present? text.strip! text_compare.strip! text_compare.downcase! text_compare.sub!(%r{/$}, '') end - placeholder = if !link_compare.empty? && text_compare.empty? + placeholder = if link_compare.present? && text_compare.blank? link - elsif link_compare.empty? && !text_compare.empty? + elsif link_compare.blank? && text_compare.present? text elsif link_compare && link_compare =~ /^mailto/i text - elsif !link_compare.empty? && !text_compare.empty? && (link_compare == text_compare || link_compare == "mailto:#{text}".downcase || link_compare == "http://#{text}".downcase) + elsif link_compare.present? && text_compare.present? && (link_compare == text_compare || link_compare == "mailto:#{text}".downcase || link_compare == "http://#{text}".downcase) "######LINKEXT:#{link}/TEXT:#{text}######" elsif text !~ /^http/ "#{text} (######LINKRAW:#{link}######)" @@ -223,7 +223,7 @@ class String pre = $1 content = $2 post = $5 - if content =~ /^www/i + if content.match?(/^www/i) content = "http://#{content}" end placeholder = if content =~ /^(http|https|ftp|tel)/i @@ -239,7 +239,6 @@ class String coder = HTMLEntities.new string = coder.decode(string) rescue - # strip all & < > " string.gsub!('&', '&') string.gsub!('<', '<') @@ -439,7 +438,7 @@ class String # edv hotline schrieb: #map['word-en-de'] = "[^#{marker}].{1,250}\s(wrote|schrieb):" - map.each do |_key, regexp| + map.each_value do |regexp| begin string.sub!(/#{regexp}/) do |placeholder| placeholder = "#{marker}#{placeholder}" diff --git a/lib/email_helper/probe.rb b/lib/email_helper/probe.rb index a62ca50cb..e34937d9b 100644 --- a/lib/email_helper/probe.rb +++ b/lib/email_helper/probe.rb @@ -68,13 +68,13 @@ 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 do |_provider, settings| + provider_map.each_value do |settings| domains.each do |domain_to_check| next if domain_to_check !~ /#{settings[:domain]}/i # add folder to config if needed - if !params[:folder].empty? && settings[:inbound] && settings[:inbound][:options] + if params[:folder].present? && settings[:inbound] && settings[:inbound][:options] settings[:inbound][:options][:folder] = params[:folder] end @@ -112,7 +112,7 @@ returns on fail inbound_map.each do |config| # add folder to config if needed - if !params[:folder].empty? && config[:options] + if params[:folder].present? && config[:options] config[:options][:folder] = params[:folder] end @@ -221,13 +221,11 @@ returns on fail # connection test result_inbound = {} begin - require "channel/driver/#{adapter.to_filename}" driver_class = Object.const_get("Channel::Driver::#{adapter.to_classname}") driver_instance = driver_class.new result_inbound = driver_instance.fetch(params[:options], nil, 'check') - rescue => e return { result: 'invalid', @@ -321,7 +319,6 @@ returns on fail # test connection begin - require "channel/driver/#{adapter.to_filename}" driver_class = Object.const_get("Channel::Driver::#{adapter.to_classname}") @@ -331,13 +328,12 @@ returns on fail mail, ) rescue => e - # check if sending email was ok, but mailserver rejected if !subject white_map = { 'Recipient address rejected' => true, } - white_map.each do |key, _message| + white_map.each_key do |key| next if e.message !~ /#{Regexp.escape(key)}/i @@ -363,7 +359,7 @@ returns on fail def self.invalid_field(message_backend) invalid_fields.each do |key, fields| - return fields if message_backend =~ /#{Regexp.escape(key)}/i + return fields if message_backend.match?(/#{Regexp.escape(key)}/i) end {} end @@ -388,7 +384,7 @@ returns on fail def self.translation(message_backend) translations.each do |key, message_human| - return message_human if message_backend =~ /#{Regexp.escape(key)}/i + return message_human if message_backend.match?(/#{Regexp.escape(key)}/i) end nil end diff --git a/lib/encode.rb b/lib/encode.rb index 7f7ee3733..c0ccc5ac6 100644 --- a/lib/encode.rb +++ b/lib/encode.rb @@ -13,14 +13,12 @@ module Encode # validate already existing utf8 strings if charset.casecmp('utf8').zero? || charset.casecmp('utf-8').zero? begin - # return if encoding is valid utf8 = string.dup.force_encoding('UTF-8') return utf8 if utf8.valid_encoding? # try to encode from Windows-1252 to utf8 string.encode!('UTF-8', 'Windows-1252') - rescue EncodingError => e Rails.logger.error "Bad encoding: #{string.inspect}" string = string.encode!('UTF-8', invalid: :replace, undef: :replace, replace: '?') diff --git a/lib/enrichment/clearbit/user.rb b/lib/enrichment/clearbit/user.rb index 85f509abe..6dff9d66e 100644 --- a/lib/enrichment/clearbit/user.rb +++ b/lib/enrichment/clearbit/user.rb @@ -119,7 +119,7 @@ module Enrichment def fetch if !Rails.env.production? - filename = "#{Rails.root}/test/fixtures/clearbit/#{@local_user.email}.json" + filename = Rails.root.join('test', 'fixtures', 'clearbit', "#{@local_user.email}.json") if File.exist?(filename) data = IO.binread(filename) return JSON.parse(data) if data diff --git a/lib/facebook.rb b/lib/facebook.rb index d082a3d37..70af4a206 100644 --- a/lib/facebook.rb +++ b/lib/facebook.rb @@ -142,9 +142,9 @@ result # ignore if value is already set map.each do |target, source| - next if user[target] && !user[target].empty? + next if user[target].present? new_value = tweet_user.send(source).to_s - next if !new_value || new_value.empty? + next if new_value.blank? user_data[target] = new_value end user.update!(user_data) @@ -329,12 +329,11 @@ result def from_article(article) post = nil - if article[:type] == 'facebook feed comment' - Rails.logger.debug 'Create feed comment from article...' - post = @client.put_comment(article[:in_reply_to], article[:body]) - else + if article[:type] != 'facebook feed comment' raise "Can't handle unknown facebook article type '#{article[:type]}'." end + Rails.logger.debug 'Create feed comment from article...' + post = @client.put_comment(article[:in_reply_to], article[:body]) Rails.logger.debug post.inspect @client.get_object(post['id']) end @@ -376,7 +375,7 @@ result Rails.logger.debug comments.inspect result = [] - return result if comments.empty? + return result if comments.blank? comments.each do |comment| user = to_user(comment) diff --git a/lib/fill_db.rb b/lib/fill_db.rb index 87a4e62d0..1ceabdd4f 100644 --- a/lib/fill_db.rb +++ b/lib/fill_db.rb @@ -89,7 +89,7 @@ or if you only want to create 100 tickets ActiveRecord::Base.transaction do suffix = rand(99_999).to_s organization = nil - if !organization_pool.empty? && rand(2) == 1 + if organization_pool.present? && rand(2) == 1 organization = organization_pool[ organization_pool.length - 1 ] end user = User.create_or_update( @@ -137,39 +137,38 @@ or if you only want to create 100 tickets priority_pool = Ticket::Priority.all state_pool = Ticket::State.all - if tickets && !tickets.zero? - (1..tickets).each do - ActiveRecord::Base.transaction do - customer = customer_pool[ rand(customer_pool.length - 1) ] - agent = agent_pool[ rand(agent_pool.length - 1) ] - ticket = Ticket.create!( - title: "some title äöüß#{rand(999_999)}", - group: group_pool[ rand(group_pool.length - 1) ], - customer: customer, - owner: agent, - state: state_pool[ rand(state_pool.length - 1) ], - priority: priority_pool[ rand(priority_pool.length - 1) ], - updated_by_id: agent.id, - created_by_id: agent.id, - ) + return if !tickets || tickets.zero? + (1..tickets).each do + ActiveRecord::Base.transaction do + customer = customer_pool[ rand(customer_pool.length - 1) ] + agent = agent_pool[ rand(agent_pool.length - 1) ] + ticket = Ticket.create!( + title: "some title äöüß#{rand(999_999)}", + group: group_pool[ rand(group_pool.length - 1) ], + customer: customer, + owner: agent, + state: state_pool[ rand(state_pool.length - 1) ], + priority: priority_pool[ rand(priority_pool.length - 1) ], + updated_by_id: agent.id, + created_by_id: agent.id, + ) - # create article - article = Ticket::Article.create!( - ticket_id: ticket.id, - from: customer.email, - to: 'some_recipient@example.com', - subject: "some subject#{rand(999_999)}", - message_id: "some@id-#{rand(999_999)}", - body: 'some message ...', - internal: false, - sender: Ticket::Article::Sender.where(name: 'Customer').first, - type: Ticket::Article::Type.where(name: 'phone').first, - updated_by_id: agent.id, - created_by_id: agent.id, - ) - puts " Ticket #{ticket.number} created" - sleep nice - end + # create article + article = Ticket::Article.create!( + ticket_id: ticket.id, + from: customer.email, + to: 'some_recipient@example.com', + subject: "some subject#{rand(999_999)}", + message_id: "some@id-#{rand(999_999)}", + body: 'some message ...', + internal: false, + sender: Ticket::Article::Sender.where(name: 'Customer').first, + type: Ticket::Article::Type.where(name: 'phone').first, + updated_by_id: agent.id, + created_by_id: agent.id, + ) + puts " Ticket #{ticket.number} created" + sleep nice end end end diff --git a/lib/html_sanitizer.rb b/lib/html_sanitizer.rb index 67e0b046b..4d1d73ac8 100644 --- a/lib/html_sanitizer.rb +++ b/lib/html_sanitizer.rb @@ -17,7 +17,7 @@ satinize html string based on whiltelist attributes_whitelist = Rails.configuration.html_sanitizer_attributes_whitelist css_properties_whitelist = Rails.configuration.html_sanitizer_css_properties_whitelist classes_whitelist = ['js-signatureMarker'] - attributes_2_css = %w(width height) + attributes_2_css = %w[width height] # remove html comments string.gsub!(//m, '') @@ -29,7 +29,7 @@ satinize html string based on whiltelist if node['href'].blank? node.replace node.children.to_s Loofah::Scrubber::STOP - elsif ((node.children.empty? || node.children.first.class == Nokogiri::XML::Text) && node.text.present?) || (node.children.size == 1 && node.children.first.content == node.content && node.content.present?) + elsif ((node.children.blank? || node.children.first.class == Nokogiri::XML::Text) && node.text.present?) || (node.children.size == 1 && node.children.first.content == node.content && node.content.present?) if node.text.downcase.start_with?('http', 'ftp', '//') a = Nokogiri::XML::Node.new 'a', node.document a['href'] = node['href'] @@ -54,7 +54,7 @@ satinize html string based on whiltelist end # check if text has urls which need to be clickable - if node && node.name != 'a' && node.parent && node.parent.name != 'a' && (!node.parent.parent || node.parent.parent.name != 'a') + if 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 do |match| @@ -172,7 +172,7 @@ satinize html string based on whiltelist end # scan for invalid link content - %w(href style).each do |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 @@ -180,9 +180,9 @@ satinize html string based on whiltelist end # remove attributes if not whitelisted - node.each do |attribute, _value| + node.each do |attribute, _value| # rubocop:disable Performance/HashEachMethods attribute_name = attribute.downcase - next if attributes_whitelist[:all].include?(attribute_name) || (attributes_whitelist[node.name] && attributes_whitelist[node.name].include?(attribute_name)) + next if attributes_whitelist[:all].include?(attribute_name) || (attributes_whitelist[node.name]&.include?(attribute_name)) node.delete(attribute) end @@ -241,7 +241,7 @@ cleanup html string: def self.cleanup_replace_tags(string) #return string - tags_backlist = %w(span center) + tags_backlist = %w[span center] scrubber = Loofah::Scrubber.new do |node| next if !tags_backlist.include?(node.name) hit = false @@ -265,11 +265,11 @@ cleanup html string: def self.cleanup_structure(string, type = 'all') remove_empty_nodes = if type == 'pre' - %w(span) + %w[span] else - %w(p div span small table) + %w[p div span small table] end - remove_empty_last_nodes = %w(b i u small table) + remove_empty_last_nodes = %w[b i u small table] # remove last empty nodes and empty -not needed- parrent nodes scrubber_structure = Loofah::Scrubber.new do |node| @@ -357,7 +357,7 @@ cleanup html string: pre = $1 post = $2 - if url =~ /^www/i + if url.match?(/^www/i) url = "http://#{url}" end @@ -379,6 +379,8 @@ cleanup html string: return if post.blank? add_link(post, urls, a) end + + true end def self.html_decode(string) @@ -386,20 +388,20 @@ cleanup html string: end def self.cleanup_target(string) - string = URI.unescape(string).encode('utf-8', 'binary', invalid: :replace, undef: :replace, replace: '?') + string = CGI.unescape(string).encode('utf-8', 'binary', invalid: :replace, undef: :replace, replace: '?') string.gsub(/[[:space:]]|\t|\n|\r/, '').gsub(%r{/\*.*?\*/}, '').gsub(//, '').gsub(/\[.+?\]/, '') end def self.url_same?(url_new, url_old) - url_new = URI.unescape(url_new.to_s).encode('utf-8', 'binary', invalid: :replace, undef: :replace, replace: '?').downcase.gsub(%r{/$}, '').gsub(/[[:space:]]|\t|\n|\r/, '').strip - url_old = URI.unescape(url_old.to_s).encode('utf-8', 'binary', invalid: :replace, undef: :replace, replace: '?').downcase.gsub(%r{/$}, '').gsub(/[[:space:]]|\t|\n|\r/, '').strip + url_new = CGI.unescape(url_new.to_s).encode('utf-8', 'binary', invalid: :replace, undef: :replace, replace: '?').downcase.gsub(%r{/$}, '').gsub(/[[:space:]]|\t|\n|\r/, '').strip + url_old = CGI.unescape(url_old.to_s).encode('utf-8', 'binary', invalid: :replace, undef: :replace, replace: '?').downcase.gsub(%r{/$}, '').gsub(/[[:space:]]|\t|\n|\r/, '').strip url_new = html_decode(url_new).sub('/?', '?') url_old = html_decode(url_old).sub('/?', '?') return true if url_new == url_old - return true if "http://#{url_new}" == url_old - return true if "http://#{url_old}" == url_new - return true if "https://#{url_new}" == url_old - return true if "https://#{url_old}" == url_new + return true if url_old == "http://#{url_new}" + return true if url_new == "http://#{url_old}" + return true if url_old == "https://#{url_new}" + return true if url_new == "https://#{url_old}" false end diff --git a/lib/import/base_factory.rb b/lib/import/base_factory.rb index ed8039bd3..26d52ef43 100644 --- a/lib/import/base_factory.rb +++ b/lib/import/base_factory.rb @@ -17,11 +17,9 @@ module Import raise 'Missing import method implementation for this factory' end - def pre_import_hook(_records, *args) - end + def pre_import_hook(_records, *args); end - def post_import_hook(_record, _backend_instance, *args) - end + def post_import_hook(_record, _backend_instance, *args); end def backend_class(_record, *_args) "Import::#{module_name}".constantize diff --git a/lib/import/base_resource.rb b/lib/import/base_resource.rb index 93a57321f..04cb8efad 100644 --- a/lib/import/base_resource.rb +++ b/lib/import/base_resource.rb @@ -2,7 +2,7 @@ module Import class BaseResource include Import::Helper - attr_reader :resource, :remote_id, :errors + attr_reader :resource, :errors def initialize(resource, *args) @action = :unknown @@ -69,7 +69,7 @@ module Import def initialize_associations_states @associations = {} - %i(before after).each do |state| + %i[before after].each do |state| @associations[state] ||= {} end end @@ -236,7 +236,7 @@ module Import def handle_args(_resource, *args) return if !args return if !args.is_a?(Array) - return if args.empty? + return if args.blank? last_arg = args.last return if !last_arg.is_a?(Hash) diff --git a/lib/import/exchange/folder.rb b/lib/import/exchange/folder.rb index 7a4559f0a..3e702bc9c 100644 --- a/lib/import/exchange/folder.rb +++ b/lib/import/exchange/folder.rb @@ -28,7 +28,7 @@ module Import def all # request folders only if neccessary and store the result - @all ||= children(%i(root msgfolderroot publicfoldersroot)) + @all ||= children(%i[root msgfolderroot publicfoldersroot]) end def children(parent_identifiers) diff --git a/lib/import/exchange/item_attributes.rb b/lib/import/exchange/item_attributes.rb index bc0d19ec0..6f414af98 100644 --- a/lib/import/exchange/item_attributes.rb +++ b/lib/import/exchange/item_attributes.rb @@ -24,7 +24,7 @@ module Import def booleanize_values(properties) properties.each do |key, value| if value.is_a?(String) - next if !%w(true false).include?(value) + next if !%w[true false].include?(value) properties[key] = value == 'true' elsif value.is_a?(Hash) properties[key] = booleanize_values(value) @@ -89,7 +89,7 @@ module Import result_key = key if prefix - result_key = if %i(text id).include?(key) && ( !result[result_key] || result[result_key] == value ) + result_key = if %i[text id].include?(key) && ( !result[result_key] || result[result_key] == value ) prefix else "#{prefix}.#{key}".to_sym diff --git a/lib/import/integration_base.rb b/lib/import/integration_base.rb index 45fad7193..40380f5ec 100644 --- a/lib/import/integration_base.rb +++ b/lib/import/integration_base.rb @@ -14,7 +14,7 @@ module Import subclass.extend(Forwardable) # delegate instance methods to the generic class implementations - subclass.delegate [:identifier, :active?, :config, :display_name] => subclass + subclass.delegate %i[identifier active? config display_name] => subclass end # Defines the integration identifier used for diff --git a/lib/import/ldap/user.rb b/lib/import/ldap/user.rb index e5c607a32..aee72561b 100644 --- a/lib/import/ldap/user.rb +++ b/lib/import/ldap/user.rb @@ -86,8 +86,8 @@ module Import return true if resource[:login].blank? # skip resource if only ignored attributes are set - ignored_attributes = %i(login dn created_by_id updated_by_id active) - !resource.except(*ignored_attributes).values.any?(&:present?) + ignored_attributes = %i[login dn created_by_id updated_by_id active] + resource.except(*ignored_attributes).values.none?(&:present?) end def determine_role_ids(resource) @@ -168,7 +168,7 @@ module Import if instance.blank? checked_values = [@remote_id] - %i(login email).each do |attribute| + %i[login email].each do |attribute| check_value = resource[attribute] next if check_value.blank? next if checked_values.include?(check_value) @@ -204,7 +204,7 @@ module Import # we have to manually downcase the login and email # to avoid wrong attribute change detection - %i(login email).each do |attribute| + %i[login email].each do |attribute| next if mapped[attribute].blank? mapped[attribute] = mapped[attribute].downcase end diff --git a/lib/import/ldap/user_factory.rb b/lib/import/ldap/user_factory.rb index 3ed6f40ee..7a9c77e75 100644 --- a/lib/import/ldap/user_factory.rb +++ b/lib/import/ldap/user_factory.rb @@ -124,7 +124,7 @@ module Import def self.track_found_remote_ids(backend_instance) remote_id = backend_instance.remote_id(nil) - @deactivation_actions ||= %i(skipped failed) + @deactivation_actions ||= %i[skipped failed] if @deactivation_actions.include?(backend_instance.action) @found_lost_remote_ids.push(remote_id) else diff --git a/lib/import/otrs.rb b/lib/import/otrs.rb index 3223b7327..55e9489f9 100644 --- a/lib/import/otrs.rb +++ b/lib/import/otrs.rb @@ -140,7 +140,7 @@ module Import def import_action(remote_object, args = {}) records = Import::OTRS::Requester.load(remote_object, limit: args[:limit], offset: args[:offset], diff: args[:diff]) - if !records || records.empty? + if records.blank? log '... no more work.' return false end diff --git a/lib/import/otrs/article/attachment_factory.rb b/lib/import/otrs/article/attachment_factory.rb index c68956b4c..45e987486 100644 --- a/lib/import/otrs/article/attachment_factory.rb +++ b/lib/import/otrs/article/attachment_factory.rb @@ -67,7 +67,7 @@ module Import return true if local_attachments.count == attachments.count # get a common ground local_attachments.each(&:delete) - return true if attachments.empty? + return true if attachments.blank? false end diff --git a/lib/import/otrs/article_customer.rb b/lib/import/otrs/article_customer.rb index 1ee83c56a..d4f478730 100644 --- a/lib/import/otrs/article_customer.rb +++ b/lib/import/otrs/article_customer.rb @@ -84,7 +84,7 @@ module Import def parsed_display_name(from) parsed_address = Mail::Address.new(from) return parsed_address.display_name if parsed_address.display_name - return from if parsed_address.comments.empty? + return from if parsed_address.comments.blank? parsed_address.comments[0] rescue from diff --git a/lib/import/otrs/article_customer_factory.rb b/lib/import/otrs/article_customer_factory.rb index 18c22c931..e2db53431 100644 --- a/lib/import/otrs/article_customer_factory.rb +++ b/lib/import/otrs/article_customer_factory.rb @@ -6,7 +6,7 @@ module Import def skip?(record, *_args) return true if record['SenderType'] != 'customer' return true if record['CreatedBy'].to_i != 1 - return true if record['From'].empty? + return true if record['From'].blank? false end end diff --git a/lib/import/otrs/dynamic_field_factory.rb b/lib/import/otrs/dynamic_field_factory.rb index 4d730ce2a..549853c22 100644 --- a/lib/import/otrs/dynamic_field_factory.rb +++ b/lib/import/otrs/dynamic_field_factory.rb @@ -42,12 +42,12 @@ module Import end def supported_field_types - %w(Text TextArea Checkbox DateTime Date Dropdown Multiselect) + %w[Text TextArea Checkbox DateTime Date Dropdown Multiselect] end def skip_fields return @skip_fields if @skip_fields - @skip_fields = %w(ProcessManagementProcessID ProcessManagementActivityID ZammadMigratorChanged ZammadMigratorChangedOld) + @skip_fields = %w[ProcessManagementProcessID ProcessManagementActivityID ZammadMigratorChanged ZammadMigratorChangedOld] end end end diff --git a/lib/import/otrs/history_factory.rb b/lib/import/otrs/history_factory.rb index f0d99dbb9..03d0604dc 100644 --- a/lib/import/otrs/history_factory.rb +++ b/lib/import/otrs/history_factory.rb @@ -22,7 +22,7 @@ module Import end def supported_types - %w(NewTicket StateUpdate Move PriorityUpdate) + %w[NewTicket StateUpdate Move PriorityUpdate] end def check_supported(history) diff --git a/lib/import/otrs/import_stats.rb b/lib/import/otrs/import_stats.rb index 5929bcbee..5a9f84378 100644 --- a/lib/import/otrs/import_stats.rb +++ b/lib/import/otrs/import_stats.rb @@ -42,7 +42,7 @@ module Import end def base_total - sum_stat(%w(Queue State Priority)) + sum_stat(%w[Queue State Priority]) end def user_done @@ -50,7 +50,7 @@ module Import end def user_total - sum_stat(%w(User CustomerUser)) + sum_stat(%w[User CustomerUser]) end def ticket_done @@ -58,7 +58,7 @@ module Import end def ticket_total - sum_stat(%w(Ticket)) + sum_stat(%w[Ticket]) end def sum_stat(objects) diff --git a/lib/import/otrs/requester.rb b/lib/import/otrs/requester.rb index ef504cf71..adbcc4c27 100644 --- a/lib/import/otrs/requester.rb +++ b/lib/import/otrs/requester.rb @@ -27,7 +27,7 @@ module Import def load(object, opts = {}) @cache ||= {} - if opts.empty? && @cache[object] + if opts.blank? && @cache[object] return @cache[object] end @@ -39,7 +39,7 @@ module Import Diff: opts[:diff] ? 1 : 0 ) - return result if !opts.empty? + return result if opts.present? @cache[object] = result @cache[object] end diff --git a/lib/import/otrs/state_factory.rb b/lib/import/otrs/state_factory.rb index aaf59d66f..f62f9b8ce 100644 --- a/lib/import/otrs/state_factory.rb +++ b/lib/import/otrs/state_factory.rb @@ -65,19 +65,19 @@ module Import def update_ticket_state agent_new = ::Ticket::State.where( - state_type_id: ::Ticket::StateType.where.not(name: %w(merged removed)) + state_type_id: ::Ticket::StateType.where.not(name: %w[merged removed]) ).pluck(:id) agent_edit = ::Ticket::State.where( - state_type_id: ::Ticket::StateType.where.not(name: %w(new merged removed)) + state_type_id: ::Ticket::StateType.where.not(name: %w[new merged removed]) ).pluck(:id) customer_new = ::Ticket::State.where( - state_type_id: ::Ticket::StateType.where.not(name: %w(new closed)) + state_type_id: ::Ticket::StateType.where.not(name: %w[new closed]) ).pluck(:id) customer_edit = ::Ticket::State.where( - state_type_id: ::Ticket::StateType.where.not(name: %w(open closed)) + state_type_id: ::Ticket::StateType.where.not(name: %w[open closed]) ).pluck(:id) ticket_state_id = ::ObjectManager::Attribute.get( diff --git a/lib/import/otrs/sys_config_factory.rb b/lib/import/otrs/sys_config_factory.rb index a17abbe06..43c7ba114 100644 --- a/lib/import/otrs/sys_config_factory.rb +++ b/lib/import/otrs/sys_config_factory.rb @@ -21,7 +21,7 @@ module Import private def direct_settings - %w(HttpType SystemID Organization TicketHook) + %w[HttpType SystemID Organization TicketHook] end def direct_copy?(setting) @@ -55,7 +55,7 @@ module Import def postmaster_default?(setting) - relevant_configs = %w(PostmasterDefaultPriority PostmasterDefaultState PostmasterFollowUpState) + relevant_configs = %w[PostmasterDefaultPriority PostmasterDefaultState PostmasterFollowUpState] return false if !relevant_configs.include?(setting['Key']) map = { diff --git a/lib/import/otrs/ticket.rb b/lib/import/otrs/ticket.rb index 45fdd35c0..8af2ef7d8 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 do |key| + ticket.each_key do |key| key_string = key.to_s @@ -144,7 +144,7 @@ module Import user_id = nil articles.each do |article| next if article['SenderType'] != 'customer' - next if article['From'].empty? + next if article['From'].blank? user = Import::OTRS::ArticleCustomer.find(article) break if !user user_id = user.id @@ -171,7 +171,7 @@ module Import def fix_close_time(ticket) return if ticket['StateType'] != 'closed' return if ticket['Closed'] - return if !ticket['Closed'].empty? + return if ticket['Closed'].present? ticket['Closed'] = ticket['Created'] end end diff --git a/lib/import/otrs/user.rb b/lib/import/otrs/user.rb index f52acdf53..a9392c890 100644 --- a/lib/import/otrs/user.rb +++ b/lib/import/otrs/user.rb @@ -38,7 +38,7 @@ module Import return false if !@local_user # only update roles if different (reduce sql statements) - if user[:role_ids] && user[:role_ids].sort == @local_user.role_ids.sort + if user[:role_ids]&.sort == @local_user.role_ids.sort user.delete(:role_ids) end @@ -143,7 +143,7 @@ module Import def groups_from_otrs_group(role_object, group) result = [] - return result if role_object['GroupIDs'].empty? + return result if role_object['GroupIDs'].blank? permissions = role_object['GroupIDs'][ group['ID'] ] return result if !permissions diff --git a/lib/import/zendesk/import_stats.rb b/lib/import/zendesk/import_stats.rb index d32b084e0..28773ba5c 100644 --- a/lib/import/zendesk/import_stats.rb +++ b/lib/import/zendesk/import_stats.rb @@ -49,7 +49,7 @@ module Import 'Automations' => 0, } - result.each do |object, _score| + result.each_key do |object| result[ object ] = statistic_count(object) end diff --git a/lib/import/zendesk/object_attribute.rb b/lib/import/zendesk/object_attribute.rb index ae8a7fd01..440f2b220 100644 --- a/lib/import/zendesk/object_attribute.rb +++ b/lib/import/zendesk/object_attribute.rb @@ -12,8 +12,7 @@ module Import private - def init_callback(_attribute) - end + def init_callback(_attribute); end def add(object, name, attribute) ObjectManager::Attribute.add( attribute_config(object, name, attribute) ) diff --git a/lib/import/zendesk/ticket/comment.rb b/lib/import/zendesk/ticket/comment.rb index 996920d56..d03f3b657 100644 --- a/lib/import/zendesk/ticket/comment.rb +++ b/lib/import/zendesk/ticket/comment.rb @@ -62,7 +62,7 @@ module Import def import_attachments(comment) attachments = comment.attachments - return if attachments.empty? + return if attachments.blank? Import::Zendesk::Ticket::Comment::AttachmentFactory.import(attachments, @local_article) end end diff --git a/lib/import/zendesk/ticket/comment/attachment_factory.rb b/lib/import/zendesk/ticket/comment/attachment_factory.rb index 4ccc1da85..167ff8192 100644 --- a/lib/import/zendesk/ticket/comment/attachment_factory.rb +++ b/lib/import/zendesk/ticket/comment/attachment_factory.rb @@ -22,7 +22,7 @@ module Import return if local_attachments.count == records.count # get a common ground local_attachments.each(&:delete) - return if records.empty? + return if records.blank? records.each(&import_block) end diff --git a/lib/import/zendesk/user/group.rb b/lib/import/zendesk/user/group.rb index afeb8fe7a..9fe4782a8 100644 --- a/lib/import/zendesk/user/group.rb +++ b/lib/import/zendesk/user/group.rb @@ -14,7 +14,7 @@ module Import def for(user) groups = [] - return groups if mapping[user.id].empty? + return groups if mapping[user.id].blank? mapping[user.id].each do |zendesk_group_id| diff --git a/lib/ldap.rb b/lib/ldap.rb index ae2d50beb..7c0623a9e 100644 --- a/lib/ldap.rb +++ b/lib/ldap.rb @@ -200,11 +200,10 @@ class Ldap method: :simple_tls, } - if !@config[:ssl_verify] - @encryption[:tls_options] = { - verify_mode: OpenSSL::SSL::VERIFY_NONE - } - end + return if @config[:ssl_verify] + @encryption[:tls_options] = { + verify_mode: OpenSSL::SSL::VERIFY_NONE + } end def handle_bind_crendentials diff --git a/lib/ldap/group.rb b/lib/ldap/group.rb index 39bfef153..a1c5419f4 100644 --- a/lib/ldap/group.rb +++ b/lib/ldap/group.rb @@ -58,7 +58,7 @@ class Ldap return {} if filter.blank? groups = {} - @ldap.search(filter, base: base_dn, attributes: %w(dn)) do |entry| + @ldap.search(filter, base: base_dn, attributes: %w[dn]) do |entry| groups[entry.dn.downcase] = entry.dn.downcase end groups @@ -80,7 +80,7 @@ class Ldap filter ||= filter() result = {} - @ldap.search(filter, attributes: %w(dn member memberuid)) do |entry| + @ldap.search(filter, attributes: %w[dn member memberuid]) do |entry| roles = mapping[entry.dn.downcase] next if roles.blank? @@ -140,7 +140,7 @@ class Ldap entry[:memberuid].collect do |uid| dn = nil - @ldap.search("(uid=#{uid})", attributes: %w(dn)) do |user| + @ldap.search("(uid=#{uid})", attributes: %w[dn]) do |user| dn = user.dn end dn diff --git a/lib/ldap/user.rb b/lib/ldap/user.rb index c10cae694..3a7b99a1d 100644 --- a/lib/ldap/user.rb +++ b/lib/ldap/user.rb @@ -11,44 +11,44 @@ class Ldap class User include Ldap::FilterLookup - BLACKLISTED = [ - :admincount, - :accountexpires, - :badpasswordtime, - :badpwdcount, - :countrycode, - :distinguishedname, - :dnshostname, - :dscorepropagationdata, - :instancetype, - :iscriticalsystemobject, - :useraccountcontrol, - :usercertificate, - :objectclass, - :objectcategory, - :objectguid, - :objectsid, - :primarygroupid, - :pwdlastset, - :lastlogoff, - :lastlogon, - :lastlogontimestamp, - :localpolicyflags, - :lockouttime, - :logoncount, - :logonhours, - :'msdfsr-computerreferencebl', - :'msds-supportedencryptiontypes', - :ridsetreferences, - :samaccounttype, - :memberof, - :serverreferencebl, - :serviceprincipalname, - :showinadvancedviewonly, - :usnchanged, - :usncreated, - :whenchanged, - :whencreated, + BLACKLISTED = %i[ + admincount + accountexpires + badpasswordtime + badpwdcount + countrycode + distinguishedname + dnshostname + dscorepropagationdata + instancetype + iscriticalsystemobject + useraccountcontrol + usercertificate + objectclass + objectcategory + objectguid + objectsid + primarygroupid + pwdlastset + lastlogoff + lastlogon + lastlogontimestamp + localpolicyflags + lockouttime + logoncount + logonhours + msdfsr-computerreferencebl + msds-supportedencryptiontypes + ridsetreferences + samaccounttype + memberof + serverreferencebl + serviceprincipalname + showinadvancedviewonly + usnchanged + usncreated + whenchanged + whencreated ].freeze # Returns the uid attribute. @@ -61,7 +61,7 @@ class Ldap # @return [String] The uid attribute. def self.uid_attribute(attributes) result = nil - %i(samaccountname userprincipalname uid dn).each do |attribute| + %i[samaccountname userprincipalname uid dn].each do |attribute| next if attributes[attribute].blank? result = attribute.to_s break diff --git a/lib/mixin/required_sub_paths.rb b/lib/mixin/required_sub_paths.rb index fa436749e..38eb22b13 100644 --- a/lib/mixin/required_sub_paths.rb +++ b/lib/mixin/required_sub_paths.rb @@ -2,7 +2,7 @@ module Mixin module RequiredSubPaths def self.included(_base) - path = caller_locations.first.path + path = caller_locations(1..1).first.path sub_path = File.join(File.dirname(path), File.basename(path, '.rb')) eager_load_recursive(sub_path) end diff --git a/lib/models.rb b/lib/models.rb index f51965948..c9b1c3a99 100644 --- a/lib/models.rb +++ b/lib/models.rb @@ -26,13 +26,13 @@ returns def self.all all = {} - dir = "#{Rails.root}/app/models/" - Dir.glob( "#{dir}**/*.rb" ) do |entry| - next if entry =~ /application_model/i - next if entry =~ %r{channel/}i - next if entry =~ %r{observer/}i - next if entry =~ %r{store/provider/}i - next if entry =~ %r{models/concerns/}i + dir = Rails.root.join('app', 'models').to_s + Dir.glob("#{dir}/**/*.rb" ) do |entry| + next if entry.match?(/application_model/i) + next if entry.match?(%r{channel/}i) + next if entry.match?(%r{observer/}i) + next if entry.match?(%r{store/provider/}i) + next if entry.match?(%r{models/concerns/}i) entry.gsub!(dir, '') entry = entry.to_classname @@ -69,7 +69,7 @@ returns def self.searchable models = [] - all.each do |model_class, _options| + all.each_key do |model_class| next if !model_class next if !model_class.respond_to? :search_preferences models.push model_class @@ -139,7 +139,7 @@ returns # find relations via reflections list.each do |model_class, model_attributes| next if !model_attributes[:reflections] - model_attributes[:reflections].each do |_reflection_key, reflection_value| + model_attributes[:reflections].each_value do |reflection_value| next if reflection_value.macro != :belongs_to col_name = "#{reflection_value.name}_id" @@ -170,7 +170,7 @@ returns # cleanup, remove models with empty references references.each do |k, v| - next if !v.empty? + next if v.present? references.delete(k) end @@ -192,8 +192,8 @@ returns def self.references_total(object_name, object_id) references = references(object_name, object_id) total = 0 - references.each do |_model, model_references| - model_references.each do |_col, count| + references.each_value do |model_references| + model_references.each_value do |count| total += count end end @@ -229,7 +229,7 @@ returns # collect items and attributes to update items_to_update = {} - attributes.each do |attribute, _count| + attributes.each_key do |attribute| Rails.logger.debug "#{object_name}: #{model}.#{attribute}->#{object_id_to_merge}->#{object_id_primary}" model_object.where("#{attribute} = ?", object_id_to_merge).each do |item| if !items_to_update[item.id] @@ -241,9 +241,7 @@ returns # update items ActiveRecord::Base.transaction do - items_to_update.each do |_id, item| - item.save! - end + items_to_update.each_value(&:save!) end end true diff --git a/lib/notification_factory/mailer.rb b/lib/notification_factory/mailer.rb index b949f044e..6472543f8 100644 --- a/lib/notification_factory/mailer.rb +++ b/lib/notification_factory/mailer.rb @@ -62,7 +62,7 @@ returns selected_group_ids = user.preferences['notification_config']['group_ids'] if selected_group_ids.is_a?(Array) hit = nil - if selected_group_ids.empty? + if selected_group_ids.blank? hit = true elsif selected_group_ids[0] == '-' && selected_group_ids.count == 1 hit = true diff --git a/lib/notification_factory/renderer.rb b/lib/notification_factory/renderer.rb index 5e700c876..0a55064cf 100644 --- a/lib/notification_factory/renderer.rb +++ b/lib/notification_factory/renderer.rb @@ -65,14 +65,14 @@ examples how to use object_name = object_methods.shift # if no object is given, just return - return "\#{no such object}" if object_name.empty? + return '#{no such object}' if object_name.blank? # rubocop:disable Lint/InterpolationCheck object_refs = @objects[object_name] || @objects[object_name.to_sym] # if object is not in avalable objects, just return return "\#{#{object_name} / no such object}" if !object_refs # if content of method is a complex datatype, just return - if object_methods.empty? && object_refs.class != String && object_refs.class != Float && object_refs.class != Integer + if object_methods.blank? && object_refs.class != String && object_refs.class != Float && object_refs.class != Integer return "\#{#{key} / no such method}" end object_methods_s = '' diff --git a/lib/report/ticket_moved.rb b/lib/report/ticket_moved.rb index 83df739d4..03f75b546 100644 --- a/lib/report/ticket_moved.rb +++ b/lib/report/ticket_moved.rb @@ -133,8 +133,8 @@ returns end def self.group_attributes(selector, params) + group_id = selector['value'] if selector['operator'] == 'is' - group_id = selector['value'] if params[:params][:type] == 'in' return { id_not_from: group_id, @@ -146,8 +146,7 @@ returns id_not_to: group_id, } end - else - group_id = selector['value'] + elsif selector['operator'] == 'is not' if params[:params][:type] == 'in' return { id_from: group_id, diff --git a/lib/report/ticket_reopened.rb b/lib/report/ticket_reopened.rb index 9046e82d9..ef4affd37 100644 --- a/lib/report/ticket_reopened.rb +++ b/lib/report/ticket_reopened.rb @@ -111,7 +111,7 @@ returns key = 'Report::TicketReopened::StateList' ticket_state_ids = Cache.get( key ) return ticket_state_ids if ticket_state_ids - ticket_state_types = Ticket::StateType.where( name: %w(closed merged removed) ) + ticket_state_types = Ticket::StateType.where( name: %w[closed merged removed] ) ticket_state_ids = [] ticket_state_types.each do |ticket_state_type| ticket_state_type.states.each do |ticket_state| diff --git a/lib/search_index_backend.rb b/lib/search_index_backend.rb index 893a5e920..3d244b16b 100644 --- a/lib/search_index_backend.rb +++ b/lib/search_index_backend.rb @@ -201,7 +201,7 @@ return search result # add * on simple query like "somephrase23" or "attribute: somephrase23" if query.present? query.strip! - if query =~ /^([[:alpha:],0-9]+|[[:alpha:],0-9]+\:\s+[[:alpha:],0-9]+)$/ + if query.match?(/^([[:alpha:],0-9]+|[[:alpha:],0-9]+\:\s+[[:alpha:],0-9]+)$/) query += '*' end end @@ -345,7 +345,7 @@ get count of tickets and tickets which match on selector def self.selector2query(selector, _current_user, aggs_interval, limit) query_must = [] query_must_not = [] - if selector && !selector.empty? + if selector.present? selector.each do |key, data| key_tmp = key.sub(/^.+?\./, '') t = {} @@ -400,10 +400,10 @@ get count of tickets and tickets which match on selector data[:query][:bool] = {} end - if !query_must.empty? + if query_must.present? data[:query][:bool][:must] = query_must end - if !query_must_not.empty? + if query_must_not.present? data[:query][:bool][:must_not] = query_must_not end diff --git a/lib/sequencer/unit/import/common/import_job/sub_sequence/general.rb b/lib/sequencer/unit/import/common/import_job/sub_sequence/general.rb index e581e1782..b0ffeafa1 100644 --- a/lib/sequencer/unit/import/common/import_job/sub_sequence/general.rb +++ b/lib/sequencer/unit/import/common/import_job/sub_sequence/general.rb @@ -55,8 +55,7 @@ class Sequencer end end - def processed(_result) - end + def processed(_result); end end end end diff --git a/lib/sequencer/unit/import/common/model/skip/blank/base.rb b/lib/sequencer/unit/import/common/model/skip/blank/base.rb index d57a10126..70a78da2b 100644 --- a/lib/sequencer/unit/import/common/model/skip/blank/base.rb +++ b/lib/sequencer/unit/import/common/model/skip/blank/base.rb @@ -31,7 +31,7 @@ class Sequencer end def relevant_blank? - !attribute_value.except(*ignore).values.any?(&:present?) + attribute_value.except(*ignore).values.none?(&:present?) end end end diff --git a/lib/sequencer/unit/import/common/model/skip/missing_mandatory/base.rb b/lib/sequencer/unit/import/common/model/skip/missing_mandatory/base.rb index cb327161e..14cf05759 100644 --- a/lib/sequencer/unit/import/common/model/skip/missing_mandatory/base.rb +++ b/lib/sequencer/unit/import/common/model/skip/missing_mandatory/base.rb @@ -32,7 +32,7 @@ class Sequencer def mandatory_missing? values = attribute_value.fetch_values(*mandatory) - !values.any?(&:present?) + values.none?(&:present?) rescue KeyError => e false end diff --git a/lib/sequencer/unit/import/common/model/statistics/mixin/diff.rb b/lib/sequencer/unit/import/common/model/statistics/mixin/diff.rb index 1dd1194c7..7411709bc 100644 --- a/lib/sequencer/unit/import/common/model/statistics/mixin/diff.rb +++ b/lib/sequencer/unit/import/common/model/statistics/mixin/diff.rb @@ -15,7 +15,7 @@ class Sequencer private def actions - %i(skipped created updated unchanged failed deactivated) + %i[skipped created updated unchanged failed deactivated] end def diff diff --git a/lib/sequencer/unit/import/common/user/attributes/downcase.rb b/lib/sequencer/unit/import/common/user/attributes/downcase.rb index c5791e062..eb0a6499c 100644 --- a/lib/sequencer/unit/import/common/user/attributes/downcase.rb +++ b/lib/sequencer/unit/import/common/user/attributes/downcase.rb @@ -10,7 +10,7 @@ class Sequencer uses :mapped def process - %i(login email).each do |attribute| + %i[login email].each do |attribute| next if mapped[attribute].blank? mapped[attribute].downcase! end diff --git a/lib/sequencer/unit/import/exchange/folder_contact/statistics/diff.rb b/lib/sequencer/unit/import/exchange/folder_contact/statistics/diff.rb index 9ed81f27f..55c127d2c 100644 --- a/lib/sequencer/unit/import/exchange/folder_contact/statistics/diff.rb +++ b/lib/sequencer/unit/import/exchange/folder_contact/statistics/diff.rb @@ -28,7 +28,7 @@ class Sequencer private def actions - %i(created updated unchanged skipped failed) + %i[created updated unchanged skipped failed] end end end diff --git a/lib/sequencer/unit/mixin/dynamic_attribute.rb b/lib/sequencer/unit/mixin/dynamic_attribute.rb index e37012d90..df7e1b707 100644 --- a/lib/sequencer/unit/mixin/dynamic_attribute.rb +++ b/lib/sequencer/unit/mixin/dynamic_attribute.rb @@ -1,4 +1,3 @@ -# rubocop:disable Lint/NestedMethodDefinition class Sequencer class Unit module Mixin diff --git a/lib/service/image/zammad.rb b/lib/service/image/zammad.rb index 22c93bcd5..dcae93943 100644 --- a/lib/service/image/zammad.rb +++ b/lib/service/image/zammad.rb @@ -13,7 +13,7 @@ class Service::Image::Zammad email.downcase! - return if email =~ /@example.com$/ + return if email.match?(/@example.com$/) # fetch image response = UserAgent.post( diff --git a/lib/sessions.rb b/lib/sessions.rb index b191013a7..95149cd26 100644 --- a/lib/sessions.rb +++ b/lib/sessions.rb @@ -55,15 +55,14 @@ returns FileUtils.mv(path_tmp, path) # send update to browser - if session && session['id'] - send( - client_id, - { - event: 'ws:login', - data: { success: true }, - } - ) - end + return if !session || session['id'].blank? + send( + client_id, + { + event: 'ws:login', + data: { success: true }, + } + ) end =begin @@ -656,9 +655,10 @@ returns # restart job again if try_run_max > try_count thread_client(client_id, try_count, try_run_time) - else - raise "STOP thread_client for client #{client_id} after #{try_run_max} tries" + return end + + raise "STOP thread_client for client #{client_id} after #{try_run_max} tries" end log('debug', "/LOOP #{client_id} - #{try_count}") end diff --git a/lib/sessions/backend/activity_stream.rb b/lib/sessions/backend/activity_stream.rb index acc463dd0..9a024c502 100644 --- a/lib/sessions/backend/activity_stream.rb +++ b/lib/sessions/backend/activity_stream.rb @@ -17,12 +17,12 @@ class Sessions::Backend::ActivityStream return end - if activity_stream && activity_stream.first && activity_stream.first['created_at'] == @last_change + if activity_stream&.first && activity_stream.first['created_at'] == @last_change return end # update last changed - if activity_stream && activity_stream.first + if activity_stream&.first @last_change = activity_stream.first['created_at'] end diff --git a/lib/sessions/event/base.rb b/lib/sessions/event/base.rb index 936b8e7a9..5c1b659f2 100644 --- a/lib/sessions/event/base.rb +++ b/lib/sessions/event/base.rb @@ -107,7 +107,6 @@ class Sessions::Event::Base # rubocop:enable Rails/Output end - def destroy - end + def destroy; end end diff --git a/lib/sessions/event/login.rb b/lib/sessions/event/login.rb index a4b42c156..2533d08b8 100644 --- a/lib/sessions/event/login.rb +++ b/lib/sessions/event/login.rb @@ -20,7 +20,7 @@ class Sessions::Event::Login < Sessions::Event::Base new_session_data = {} - if session && session.data && session.data['user_id'] + if session&.data && session.data['user_id'] new_session_data = { 'id' => session.data['user_id'], } diff --git a/lib/signature_detection.rb b/lib/signature_detection.rb index 03ed608b1..8361a62ae 100644 --- a/lib/signature_detection.rb +++ b/lib/signature_detection.rb @@ -23,7 +23,7 @@ returns string_list = [] messages.each do |message| - if message[:content_type] =~ %r{text/html}i + if message[:content_type].match?(%r{text/html}i) string_list.push message[:content].html2text(true) next end @@ -78,7 +78,7 @@ returns # define the block size without any difference # except "-" because in this case 1 line is removed to much - match_block_total = diff_string_index + (line =~ /^(\\|\+)/i ? -1 : 0) + match_block_total = diff_string_index + (line.match?(/^(\\|\+)/i) ? -1 : 0) # get string of possible signature, use only the first 10 lines match_max_content = 0 @@ -128,7 +128,7 @@ returns def self.find_signature_line(signature, string, content_type) - if content_type =~ %r{text/html}i + if content_type.match?(%r{text/html}i) string = string.html2text(true) end diff --git a/lib/static_assets.rb b/lib/static_assets.rb index aadb8342d..b9a17e133 100644 --- a/lib/static_assets.rb +++ b/lib/static_assets.rb @@ -121,12 +121,12 @@ returns end # store hash in config - if list && list[0] - file = Store.find(list[0].id) - filelocation = filename(file) - Setting.set('product_logo', filelocation) - return file - end + return if !list || !list[0] + + file = Store.find(list[0].id) + filelocation = filename(file) + Setting.set('product_logo', filelocation) + file end =begin @@ -140,13 +140,13 @@ generate filename based on Store model def self.filename(file) hash = Digest::MD5.hexdigest(file.content) extention = '' - if file.preferences['Content-Type'] =~ /jpg|jpeg/i + if file.preferences['Content-Type'].match?(/jpg|jpeg/i) extention = '.jpg' - elsif file.preferences['Content-Type'] =~ /png/i + elsif file.preferences['Content-Type'].match?(/png/i) extention = '.png' - elsif file.preferences['Content-Type'] =~ /gif/i + elsif file.preferences['Content-Type'].match?(/gif/i) extention = '.gif' - elsif file.preferences['Content-Type'] =~ /svg/i + elsif file.preferences['Content-Type'].match?(/svg/i) extention = '.svg' end "#{hash}#{extention}" @@ -163,8 +163,8 @@ sync image to fs (public/assets/images/hash.png) def self.sync file = read return if !file - path = "#{Rails.root}/public/assets/images/#{filename(file)}" - File.open( path, 'wb' ) do |f| + path = Rails.root.join('public', 'assets', 'images', filename(file)) + File.open(path, 'wb') do |f| f.puts file.content end end diff --git a/lib/stats.rb b/lib/stats.rb index ef0e9cd74..615d49720 100644 --- a/lib/stats.rb +++ b/lib/stats.rb @@ -44,7 +44,7 @@ returns # calculate average backend_average_sum = {} - user_result.each do |_user_id, data| + user_result.each_value do |data| data.each do |backend_model, backend_result| next if !backend_result.key?(:used_for_average) if !backend_average_sum[backend_model] diff --git a/lib/telegram.rb b/lib/telegram.rb index 729dee516..159e5a66e 100644 --- a/lib/telegram.rb +++ b/lib/telegram.rb @@ -35,7 +35,7 @@ returns =end def self.set_webhook(token, callback_url) - if callback_url =~ %r{^http://}i + if callback_url.match?(%r{^http://}i) raise 'webhook url need to start with https://, you use http://' end api = TelegramAPI.new(token) @@ -174,14 +174,14 @@ returns def self.message_id(params) message_id = nil - [:message, :edited_message].each do |key| + %i[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 do |key| + %i[message edited_message].each do |key| next if !params[key] next if !params[key][:chat] next if !params[key][:chat][:id] @@ -279,14 +279,14 @@ returns # prepare title title = '-' - [:text, :caption].each do |area| + %i[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 do |area| + %i[sticker photo document voice].each do |area| begin next if !params[:message] next if !params[:message][area] @@ -304,7 +304,7 @@ returns end # find ticket or create one - state_ids = Ticket::State.where(name: %w(closed merged removed)).pluck(:id) + state_ids = Ticket::State.where(name: %w[closed merged removed]).pluck(:id) ticket = Ticket.where(customer_id: user.id).where.not(state_id: state_ids).order(:updated_at).first if ticket diff --git a/lib/tweet_base.rb b/lib/tweet_base.rb index cc492641a..bf95d3ce4 100644 --- a/lib/tweet_base.rb +++ b/lib/tweet_base.rb @@ -12,11 +12,11 @@ class TweetBase if tweet.class == Twitter::DirectMessage Rails.logger.debug "Twitter sender for dm (#{tweet.id}): found" Rails.logger.debug tweet.sender.inspect - return tweet.sender + tweet.sender elsif tweet.class == Twitter::Tweet Rails.logger.debug "Twitter sender for tweet (#{tweet.id}): found" Rails.logger.debug tweet.user.inspect - return tweet.user + tweet.user else raise "Unknown tweet type '#{tweet.class}'" end @@ -47,9 +47,9 @@ class TweetBase # ignore if value is already set map.each do |target, source| - next if user[target] && !user[target].empty? + next if user[target].present? new_value = tweet_user.send(source).to_s - next if !new_value || new_value.empty? + next if new_value.blank? user_data[target] = new_value end user.update!(user_data) @@ -113,7 +113,7 @@ class TweetBase customer_id: user.id, state: Ticket::State.where.not( state_type_id: Ticket::StateType.where( - name: %w(closed merged removed), + name: %w[closed merged removed], ) ) ) @@ -169,16 +169,14 @@ class TweetBase article_type = 'twitter status' from = "@#{tweet.user.screen_name}" mention_ids = [] - if tweet.user_mentions - tweet.user_mentions.each do |local_user| - if !to - to = '' - else - to += ', ' - end - to += "@#{local_user.screen_name}" - mention_ids.push local_user.id + tweet.user_mentions&.each do |local_user| + if !to + to = '' + else + to += ', ' end + to += "@#{local_user.screen_name}" + mention_ids.push local_user.id end in_reply_to = tweet.in_reply_to_status_id @@ -257,7 +255,6 @@ class TweetBase ticket = existing_article.ticket else begin - # in case of streaming mode, get parent tweet via REST client if @connection_type == 'stream' client = TweetRest.new(@auth) @@ -370,7 +367,7 @@ class TweetBase def preferences_cleanup(preferences) # replace Twitter::NullObject with nill to prevent elasticsearch index issue - preferences.each do |_key, value| + preferences.each_value do |value| next if !value.is_a?(Hash) value.each do |sub_key, sub_level| if sub_level.class == NilClass diff --git a/lib/tweet_stream.rb b/lib/tweet_stream.rb index dc270932c..925d1cfa7 100644 --- a/lib/tweet_stream.rb +++ b/lib/tweet_stream.rb @@ -17,7 +17,7 @@ class TweetStream < TweetBase end def disconnect - if @client && @client.custom_connection_handle + if @client&.custom_connection_handle @client.custom_connection_handle.close end diff --git a/lib/user_agent.rb b/lib/user_agent.rb index 5f8eb98c5..1cc4bc155 100644 --- a/lib/user_agent.rb +++ b/lib/user_agent.rb @@ -271,7 +271,9 @@ returns if proxy =~ /^(.+?):(.+?)$/ proxy_host = $1 proxy_port = $2 - else + end + + if proxy_host.blank? || proxy_port.blank? raise "Invalid proxy address: #{proxy} - expect e.g. proxy.example.com:3128" end @@ -292,7 +294,7 @@ returns http.open_timeout = options[:open_timeout] || 4 http.read_timeout = options[:read_timeout] || 10 - if uri.scheme =~ /https/i + if uri.scheme.match?(/https/i) http.use_ssl = true # @TODO verify_mode should be configurable http.verify_mode = OpenSSL::SSL::VERIFY_NONE @@ -313,10 +315,10 @@ returns def self.set_params(request, params, options) if options[:json] request.add_field('Content-Type', 'application/json') - if !params.empty? + if params.present? request.body = params.to_json end - elsif !params.empty? + elsif params.present? request.set_form_data(params) end request diff --git a/lib/version.rb b/lib/version.rb index 011ba1a3d..847079ca1 100644 --- a/lib/version.rb +++ b/lib/version.rb @@ -17,7 +17,7 @@ returns def self.get begin - version = File.read("#{Rails.root}/VERSION") + version = File.read(Rails.root.join('VERSION')) version.strip! rescue => e message = e.to_s diff --git a/script/websocket-server.rb b/script/websocket-server.rb index 8882aacac..6199a089b 100755 --- a/script/websocket-server.rb +++ b/script/websocket-server.rb @@ -169,7 +169,7 @@ EventMachine.run do # check if connection not already exists next if !@clients[client_id] - Sessions.touch(client_id) + Sessions.touch(client_id) # rubocop:disable Rails/SkipsModelValidations @clients[client_id][:last_ping] = Time.now.utc.to_i # spool messages for new connects @@ -211,14 +211,14 @@ EventMachine.run do # websocket log 'notice', "Status: websocket clients: #{@clients.size}" - @clients.each do |client_id, _client| + @clients.each_key do |client_id| log 'notice', 'working...', client_id end # ajax client_list = Sessions.list clients = 0 - client_list.each do |_client_id, client| + client_list.each_value do |client| next if client[:meta][:type] == 'websocket' clients = clients + 1 end @@ -242,7 +242,6 @@ EventMachine.run do log 'notice', 'send data to client', client_id websocket_send(client_id, queue) rescue => e - log 'error', 'problem:' + e.inspect, client_id # disconnect client diff --git a/spec/factories/signature.rb b/spec/factories/signature.rb index 15bc21f3e..296992c1c 100644 --- a/spec/factories/signature.rb +++ b/spec/factories/signature.rb @@ -7,7 +7,7 @@ end FactoryBot.define do factory :signature do name { generate(:test_signature_name) } - body '#{user.firstname} #{user.lastname}'.text2html + body '#{user.firstname} #{user.lastname}'.text2html # rubocop:disable Lint/InterpolationCheck created_by_id 1 updated_by_id 1 end diff --git a/spec/lib/auth/ldap_spec.rb b/spec/lib/auth/ldap_spec.rb index d14294fe5..c3dfdc22f 100644 --- a/spec/lib/auth/ldap_spec.rb +++ b/spec/lib/auth/ldap_spec.rb @@ -30,7 +30,7 @@ RSpec.describe ::Auth::Ldap do instance = described_class.new( adapter: described_class.name, - login_attributes: %w(firstname), + login_attributes: %w[firstname], ) ldap_user = double diff --git a/spec/lib/import/ldap/user_factory_spec.rb b/spec/lib/import/ldap/user_factory_spec.rb index d0ea4b2f3..df091375b 100644 --- a/spec/lib/import/ldap/user_factory_spec.rb +++ b/spec/lib/import/ldap/user_factory_spec.rb @@ -211,7 +211,7 @@ RSpec.describe Import::Ldap::UserFactory do # activate skipping config[:unassigned_users] = 'skip_sync' config[:group_role_map] = { - 'dummy' => %w(1 2), + 'dummy' => %w[1 2], } # group user role mapping @@ -518,7 +518,7 @@ RSpec.describe Import::Ldap::UserFactory do config = { group_filter: '(objectClass=group)', group_role_map: { - group_dn => %w(1 2), + group_dn => %w[1 2], } } diff --git a/spec/lib/import/otrs/state_factory_spec.rb b/spec/lib/import/otrs/state_factory_spec.rb index 1b50b8181..2bf2806a4 100644 --- a/spec/lib/import/otrs/state_factory_spec.rb +++ b/spec/lib/import/otrs/state_factory_spec.rb @@ -15,7 +15,7 @@ RSpec.describe Import::OTRS::StateFactory do it 'updates ObjectManager Ticket state_id and pending_time filter' 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) + 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 = [] states.each do |state| @@ -110,7 +110,7 @@ RSpec.describe Import::OTRS::StateFactory do context 'changing Ticket::State IDs' do 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) + 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 = [] states.each do |state| diff --git a/spec/lib/import/otrs/user_spec.rb b/spec/lib/import/otrs/user_spec.rb index 92423aef6..11f08d9bc 100644 --- a/spec/lib/import/otrs/user_spec.rb +++ b/spec/lib/import/otrs/user_spec.rb @@ -21,8 +21,7 @@ RSpec.describe Import::OTRS::User do start_import_test end - def role_delete_expecations(role_ids) - end + def role_delete_expecations(role_ids); end def load_user_json(file) json_fixture("import/otrs/user/#{file}") diff --git a/spec/models/concerns/has_groups_examples.rb b/spec/models/concerns/has_groups_examples.rb index 331bca593..07ed6dc0c 100644 --- a/spec/models/concerns/has_groups_examples.rb +++ b/spec/models/concerns/has_groups_examples.rb @@ -169,12 +169,12 @@ RSpec.shared_examples 'HasGroups' do context 'access list' do it 'lists access Group IDs' do - result = group_access_instance.group_ids_access(%w(read write)) + result = group_access_instance.group_ids_access(%w[read write]) expect(result).to include(group_read.id) end it "doesn't list for no access" do - result = group_access_instance.group_ids_access(%w(write create)) + result = group_access_instance.group_ids_access(%w[write create]) expect(result).not_to include(group_read.id) end end @@ -223,7 +223,7 @@ RSpec.shared_examples 'HasGroups' do expect do group_access_instance.group_names_access_map = { group_full.name => 'full', - group_read.name => %w(read write), + group_read.name => %w[read write], } end.to change { described_class.group_through.klass.count @@ -309,7 +309,7 @@ RSpec.shared_examples 'HasGroups' do expect do group_access_instance.group_ids_access_map = { group_full.id => 'full', - group_read.id => %w(read write), + group_read.id => %w[read write], } end.to change { described_class.group_through.klass.count @@ -523,11 +523,11 @@ RSpec.shared_examples '#group_access? call' do context 'access list' do it 'checks positive' do - expect(group_access_instance.group_access?(group_parameter, %w(read write))).to be true + expect(group_access_instance.group_access?(group_parameter, %w[read write])).to be true end it 'checks negative' do - expect(group_access_instance.group_access?(group_parameter, %w(write create))).to be false + expect(group_access_instance.group_access?(group_parameter, %w[write create])).to be false end end end @@ -547,11 +547,11 @@ RSpec.shared_examples '.group_access call' do context 'access list' do it 'lists access IDs' do - expect(described_class.group_access(group_parameter, %w(read write))).to include(group_access_instance) + expect(described_class.group_access(group_parameter, %w[read write])).to include(group_access_instance) end it 'excludes non access IDs' do - expect(described_class.group_access(group_parameter, %w(write create))).not_to include(group_access_instance) + expect(described_class.group_access(group_parameter, %w[write create])).not_to include(group_access_instance) end end end diff --git a/spec/models/concerns/has_roles_examples.rb b/spec/models/concerns/has_roles_examples.rb index cc86565e4..1d55d2412 100644 --- a/spec/models/concerns/has_roles_examples.rb +++ b/spec/models/concerns/has_roles_examples.rb @@ -182,12 +182,12 @@ RSpec.shared_examples 'HasRoles' do context 'access list' do it 'lists access Group IDs' do - result = group_access_instance.group_ids_access(%w(read write)) + result = group_access_instance.group_ids_access(%w[read write]) expect(result).to include(group_role.id) end it "doesn't list for no access" do - result = group_access_instance.group_ids_access(%w(write create)) + result = group_access_instance.group_ids_access(%w[write create]) expect(result).not_to include(group_role.id) end @@ -196,7 +196,7 @@ RSpec.shared_examples 'HasRoles' do group_role.name => 'read', } - result = group_access_instance.group_ids_access(%w(read create)) + result = group_access_instance.group_ids_access(%w[read create]) expect(result.uniq).to eq(result) end end @@ -237,11 +237,11 @@ RSpec.shared_examples '#role_access? call' do context 'access list' do it 'checks positive' do - expect(group_access_instance.role_access?(group_parameter, %w(read write))).to be true + expect(group_access_instance.role_access?(group_parameter, %w[read write])).to be true end it 'checks negative' do - expect(group_access_instance.role_access?(group_parameter, %w(write create))).to be false + expect(group_access_instance.role_access?(group_parameter, %w[write create])).to be false end end end @@ -261,11 +261,11 @@ RSpec.shared_examples '.role_access_ids call' do context 'access list' do it 'lists access IDs' do - expect(described_class.role_access_ids(group_parameter, %w(read write))).to include(group_access_instance.id) + expect(described_class.role_access_ids(group_parameter, %w[read write])).to include(group_access_instance.id) end it 'excludes non access IDs' do - expect(described_class.role_access_ids(group_parameter, %w(write create))).not_to include(group_access_instance.id) + expect(described_class.role_access_ids(group_parameter, %w[write create])).not_to include(group_access_instance.id) end end end diff --git a/spec/models/cti/caller_id_spec.rb b/spec/models/cti/caller_id_spec.rb index f7c7a5bd1..8d450ba1f 100644 --- a/spec/models/cti/caller_id_spec.rb +++ b/spec/models/cti/caller_id_spec.rb @@ -5,9 +5,9 @@ RSpec.describe Cti::CallerId do describe 'extract_numbers' do it { expect(described_class.extract_numbers("some text\ntest 123")).to eq [] } it { expect(described_class.extract_numbers('Lorem ipsum dolor sit amet, consectetuer +49 (0) 30 60 00 00 00-0 adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel.')).to eq ['4930600000000'] } - it { expect(described_class.extract_numbers("GS Oberalteich\nTelefon 09422 1000 Telefax 09422 805000\nE-Mail: ")).to eq %w(4994221000 499422805000) } - it { expect(described_class.extract_numbers('Tel +41 81 288 63 93 / +41 76 346 72 14 ...')).to eq %w(41812886393 41763467214) } - it { expect(described_class.extract_numbers("P: +1 (949) 431 0000\nF: +1 (949) 431 0001\nW: http://znuny")).to eq %w(19494310000 19494310001) } + it { expect(described_class.extract_numbers("GS Oberalteich\nTelefon 09422 1000 Telefax 09422 805000\nE-Mail: ")).to eq %w[4994221000 499422805000] } + it { expect(described_class.extract_numbers('Tel +41 81 288 63 93 / +41 76 346 72 14 ...')).to eq %w[41812886393 41763467214] } + it { expect(described_class.extract_numbers("P: +1 (949) 431 0000\nF: +1 (949) 431 0001\nW: http://znuny")).to eq %w[19494310000 19494310001] } end describe 'normalize_number' do diff --git a/spec/models/taskbar_spec.rb b/spec/models/taskbar_spec.rb index 83d5e3e58..346e246d5 100644 --- a/spec/models/taskbar_spec.rb +++ b/spec/models/taskbar_spec.rb @@ -27,7 +27,7 @@ RSpec.describe Taskbar do end it 'state' do - expect(taskbar.state.empty?).to eq(true) + expect(taskbar.state.blank?).to eq(true) end it 'check last_contact' do diff --git a/spec/models/translation_spec.rb b/spec/models/translation_spec.rb index 1c78441eb..642207422 100644 --- a/spec/models/translation_spec.rb +++ b/spec/models/translation_spec.rb @@ -99,7 +99,7 @@ RSpec.describe Translation do it 'check download of locales' do version = Version.get directory = Rails.root.join('config') - file = Rails.root.join("#{directory}/locales-#{version}.yml") + file = Rails.root.join(directory, "locales-#{version}.yml") if File.exist?(file) File.delete(file) end @@ -111,11 +111,11 @@ RSpec.describe Translation do it 'check download of translations' do version = Version.get locale = 'de-de' - directory = Rails.root.join('config/translations') + directory = Rails.root.join('config', 'translations') if File.directory?(directory) FileUtils.rm_rf(directory) end - file = Rails.root.join("#{directory}/#{locale}-#{version}.yml") + file = Rails.root.join(directory, "#{locale}-#{version}.yml") expect(File.exist?(file)).to be false Translation.fetch(locale) expect(File.exist?(file)).to be true diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb index 2fb7affaa..0e350a2ec 100644 --- a/spec/rails_helper.rb +++ b/spec/rails_helper.rb @@ -21,7 +21,7 @@ require 'rspec/rails' # directory. Alternatively, in the individual `*_spec.rb` files, manually # require only the support files necessary. # -Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } +Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f } # Checks for pending migration and applies them before tests are run. # If you are not using ActiveRecord, you can remove this line. diff --git a/spec/support/system_init.rb b/spec/support/system_init.rb index ac0c986b7..a7d554f83 100644 --- a/spec/support/system_init.rb +++ b/spec/support/system_init.rb @@ -4,12 +4,12 @@ RSpec.configure do |config| email = 'admin@example.com' if !::User.exists?(email: email) FactoryBot.create(:user, - login: 'admin', - firstname: 'Admin', - lastname: 'Admin', - email: email, - password: 'admin', - roles: [Role.lookup(name: 'Admin')],) + login: 'admin', + firstname: 'Admin', + lastname: 'Admin', + email: email, + password: 'admin', + roles: [Role.lookup(name: 'Admin')],) end end end diff --git a/test/browser/aaa_getting_started_test.rb b/test/browser/aaa_getting_started_test.rb index ebe5588bc..6a6857dbe 100644 --- a/test/browser/aaa_getting_started_test.rb +++ b/test/browser/aaa_getting_started_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AaaGettingStartedTest < TestCase @@ -211,7 +211,7 @@ class AaaGettingStartedTest < TestCase } accounts.push account end - if accounts.empty? + if accounts.blank? #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'" return @@ -282,7 +282,7 @@ class AaaGettingStartedTest < TestCase } accounts.push account end - if accounts.empty? + if accounts.blank? #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'" return diff --git a/test/browser/aab_basic_urls_test.rb b/test/browser/aab_basic_urls_test.rb index 83b106611..5bd5838cf 100644 --- a/test/browser/aab_basic_urls_test.rb +++ b/test/browser/aab_basic_urls_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AABBasicUrlsTest < TestCase diff --git a/test/browser/aab_unit_test.rb b/test/browser/aab_unit_test.rb index 94a960793..fab47d2de 100644 --- a/test/browser/aab_unit_test.rb +++ b/test/browser/aab_unit_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AAbUnitTest < TestCase diff --git a/test/browser/aac_basic_richtext_test.rb b/test/browser/aac_basic_richtext_test.rb index 46d276e18..c3e026954 100644 --- a/test/browser/aac_basic_richtext_test.rb +++ b/test/browser/aac_basic_richtext_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AACBasicRichtextTest < TestCase diff --git a/test/browser/abb_one_group_test.rb b/test/browser/abb_one_group_test.rb index 13de33b8a..a24cac5fb 100644 --- a/test/browser/abb_one_group_test.rb +++ b/test/browser/abb_one_group_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentTicketActionLevel0Test < TestCase diff --git a/test/browser/admin_channel_email_test.rb b/test/browser/admin_channel_email_test.rb index 78acf93d2..3ff92b526 100644 --- a/test/browser/admin_channel_email_test.rb +++ b/test/browser/admin_channel_email_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AdminChannelEmailTest < TestCase diff --git a/test/browser/admin_object_manager_test.rb b/test/browser/admin_object_manager_test.rb index 0e93c0cd3..691cb5a55 100644 --- a/test/browser/admin_object_manager_test.rb +++ b/test/browser/admin_object_manager_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 +# rubocop:disable Lint/BooleanSymbol require 'browser_test_helper' class AdminObjectManagerTest < TestCase diff --git a/test/browser/admin_overview_test.rb b/test/browser/admin_overview_test.rb index 94a577ea7..87b6791f5 100644 --- a/test/browser/admin_overview_test.rb +++ b/test/browser/admin_overview_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AdminOverviewTest < TestCase diff --git a/test/browser/admin_role_test.rb b/test/browser/admin_role_test.rb index 5c34baffa..da4e862b0 100644 --- a/test/browser/admin_role_test.rb +++ b/test/browser/admin_role_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AdminRoleTest < TestCase diff --git a/test/browser/agent_navigation_and_title_test.rb b/test/browser/agent_navigation_and_title_test.rb index d2b141d8c..499ca87b0 100644 --- a/test/browser/agent_navigation_and_title_test.rb +++ b/test/browser/agent_navigation_and_title_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentNavigationAndTitleTest < TestCase diff --git a/test/browser/agent_organization_profile_test.rb b/test/browser/agent_organization_profile_test.rb index 6c8051509..89826290d 100644 --- a/test/browser/agent_organization_profile_test.rb +++ b/test/browser/agent_organization_profile_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentOrganizationProfileTest < TestCase diff --git a/test/browser/agent_ticket_attachment_test.rb b/test/browser/agent_ticket_attachment_test.rb index 2e35f5f56..e309ca91c 100644 --- a/test/browser/agent_ticket_attachment_test.rb +++ b/test/browser/agent_ticket_attachment_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentTicketAttachmentTest < TestCase diff --git a/test/browser/agent_ticket_email_reply_keep_body_test.rb b/test/browser/agent_ticket_email_reply_keep_body_test.rb index 20f793241..3878d2e85 100644 --- a/test/browser/agent_ticket_email_reply_keep_body_test.rb +++ b/test/browser/agent_ticket_email_reply_keep_body_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentTicketEmailReplyKeepBodyTest < TestCase diff --git a/test/browser/agent_ticket_email_signature_test.rb b/test/browser/agent_ticket_email_signature_test.rb index 3e8ad43cb..e5cd13b5f 100644 --- a/test/browser/agent_ticket_email_signature_test.rb +++ b/test/browser/agent_ticket_email_signature_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentTicketEmailSignatureTest < TestCase diff --git a/test/browser/agent_ticket_link_test.rb b/test/browser/agent_ticket_link_test.rb index 60769d51d..5eb964a11 100644 --- a/test/browser/agent_ticket_link_test.rb +++ b/test/browser/agent_ticket_link_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentTicketLinkTest < TestCase diff --git a/test/browser/agent_ticket_macro_test.rb b/test/browser/agent_ticket_macro_test.rb index aeff466a0..94a5730d8 100644 --- a/test/browser/agent_ticket_macro_test.rb +++ b/test/browser/agent_ticket_macro_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentTicketMacroTest < TestCase diff --git a/test/browser/agent_ticket_merge_test.rb b/test/browser/agent_ticket_merge_test.rb index 4582aa2f0..27ed3b6eb 100644 --- a/test/browser/agent_ticket_merge_test.rb +++ b/test/browser/agent_ticket_merge_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentTicketMergeTest < TestCase diff --git a/test/browser/agent_ticket_online_notification_test.rb b/test/browser/agent_ticket_online_notification_test.rb index 7300e6560..db0bd9e0e 100644 --- a/test/browser/agent_ticket_online_notification_test.rb +++ b/test/browser/agent_ticket_online_notification_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentTicketOnlineNotificationTest < TestCase diff --git a/test/browser/agent_ticket_overview_level0_test.rb b/test/browser/agent_ticket_overview_level0_test.rb index 3385b6dca..8c1fc1e72 100644 --- a/test/browser/agent_ticket_overview_level0_test.rb +++ b/test/browser/agent_ticket_overview_level0_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentTicketOverviewLevel0Test < TestCase diff --git a/test/browser/agent_ticket_overview_level1_test.rb b/test/browser/agent_ticket_overview_level1_test.rb index 4200c37a3..2f6ebdc7c 100644 --- a/test/browser/agent_ticket_overview_level1_test.rb +++ b/test/browser/agent_ticket_overview_level1_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentTicketOverviewLevel1Test < TestCase diff --git a/test/browser/agent_ticket_overview_tab_test.rb b/test/browser/agent_ticket_overview_tab_test.rb index 80d495d26..b38a524f5 100644 --- a/test/browser/agent_ticket_overview_tab_test.rb +++ b/test/browser/agent_ticket_overview_tab_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentTicketOverviewTabTest < TestCase diff --git a/test/browser/agent_ticket_tag_test.rb b/test/browser/agent_ticket_tag_test.rb index 337d2ab13..1d881b5e7 100644 --- a/test/browser/agent_ticket_tag_test.rb +++ b/test/browser/agent_ticket_tag_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentTicketTagTest < TestCase diff --git a/test/browser/agent_ticket_text_module_test.rb b/test/browser/agent_ticket_text_module_test.rb index 4a32f5c8b..47324b771 100644 --- a/test/browser/agent_ticket_text_module_test.rb +++ b/test/browser/agent_ticket_text_module_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentTicketTextModuleTest < TestCase @@ -101,7 +101,7 @@ class AgentTicketTextModuleTest < TestCase data: { name: 'some name' + random, keywords: random, - content: 'some content #{ticket.customer.lastname}' + random, + content: "some content \#{ticket.customer.lastname}#{random}", }, ) diff --git a/test/browser/agent_ticket_time_accounting_test.rb b/test/browser/agent_ticket_time_accounting_test.rb index 983355938..fcfc2ef84 100644 --- a/test/browser/agent_ticket_time_accounting_test.rb +++ b/test/browser/agent_ticket_time_accounting_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentTicketTimeAccountingTest < TestCase diff --git a/test/browser/agent_ticket_update1_test.rb b/test/browser/agent_ticket_update1_test.rb index c758ee841..5f9be5085 100644 --- a/test/browser/agent_ticket_update1_test.rb +++ b/test/browser/agent_ticket_update1_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentTicketUpdate1Test < TestCase diff --git a/test/browser/agent_ticket_update2_test.rb b/test/browser/agent_ticket_update2_test.rb index 6b70eac23..6a1c0ace1 100644 --- a/test/browser/agent_ticket_update2_test.rb +++ b/test/browser/agent_ticket_update2_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentTicketUpdate2Test < TestCase diff --git a/test/browser/agent_ticket_update3_test.rb b/test/browser/agent_ticket_update3_test.rb index ddf3b9dd7..9dc52755b 100644 --- a/test/browser/agent_ticket_update3_test.rb +++ b/test/browser/agent_ticket_update3_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentTicketUpdate3Test < TestCase diff --git a/test/browser/agent_ticket_update_and_reload_test.rb b/test/browser/agent_ticket_update_and_reload_test.rb index 27a5583d1..9f8d3083d 100644 --- a/test/browser/agent_ticket_update_and_reload_test.rb +++ b/test/browser/agent_ticket_update_and_reload_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentTicketUpdateAndReloadTest < TestCase diff --git a/test/browser/agent_user_manage_test.rb b/test/browser/agent_user_manage_test.rb index 282dcbd38..4d2160f29 100644 --- a/test/browser/agent_user_manage_test.rb +++ b/test/browser/agent_user_manage_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentUserManageTest < TestCase diff --git a/test/browser/agent_user_profile_test.rb b/test/browser/agent_user_profile_test.rb index a53a28566..664a03d0f 100644 --- a/test/browser/agent_user_profile_test.rb +++ b/test/browser/agent_user_profile_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AgentUserProfileTest < TestCase diff --git a/test/browser/auth_test.rb b/test/browser/auth_test.rb index ee09c79cf..2ea4238c5 100644 --- a/test/browser/auth_test.rb +++ b/test/browser/auth_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AuthTest < TestCase diff --git a/test/browser/chat_test.rb b/test/browser/chat_test.rb index 5fa781d37..cd273d4d0 100644 --- a/test/browser/chat_test.rb +++ b/test/browser/chat_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class ChatTest < TestCase diff --git a/test/browser/customer_ticket_create_test.rb b/test/browser/customer_ticket_create_test.rb index c538d420a..e7f15f162 100644 --- a/test/browser/customer_ticket_create_test.rb +++ b/test/browser/customer_ticket_create_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class CustomerTicketCreateTest < TestCase diff --git a/test/browser/first_steps_test.rb b/test/browser/first_steps_test.rb index 2ed6827c2..2506abbda 100644 --- a/test/browser/first_steps_test.rb +++ b/test/browser/first_steps_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class FirstStepsTest < TestCase diff --git a/test/browser/form_test.rb b/test/browser/form_test.rb index 8b6f35a91..140abdb5c 100644 --- a/test/browser/form_test.rb +++ b/test/browser/form_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class FormTest < TestCase diff --git a/test/browser/integration_test.rb b/test/browser/integration_test.rb index d6bb6beb7..3154d012d 100644 --- a/test/browser/integration_test.rb +++ b/test/browser/integration_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class IntegrationTest < TestCase diff --git a/test/browser/keyboard_shortcuts_test.rb b/test/browser/keyboard_shortcuts_test.rb index 6a394e060..c266cb85d 100644 --- a/test/browser/keyboard_shortcuts_test.rb +++ b/test/browser/keyboard_shortcuts_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class KeyboardShortcutsTest < TestCase diff --git a/test/browser/maintenance_app_version_test.rb b/test/browser/maintenance_app_version_test.rb index e8d322cc8..2370bd88c 100644 --- a/test/browser/maintenance_app_version_test.rb +++ b/test/browser/maintenance_app_version_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class MaintenanceAppVersionTest < TestCase diff --git a/test/browser/maintenance_login_message_test.rb b/test/browser/maintenance_login_message_test.rb index d08077dc0..90423b034 100644 --- a/test/browser/maintenance_login_message_test.rb +++ b/test/browser/maintenance_login_message_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class MaintenanceLoginMessageTest < TestCase diff --git a/test/browser/maintenance_mode_test.rb b/test/browser/maintenance_mode_test.rb index a214a5409..f00952423 100644 --- a/test/browser/maintenance_mode_test.rb +++ b/test/browser/maintenance_mode_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class MaintenanceModeTest < TestCase diff --git a/test/browser/maintenance_session_message_test.rb b/test/browser/maintenance_session_message_test.rb index 3df03ae8f..5ea58c808 100644 --- a/test/browser/maintenance_session_message_test.rb +++ b/test/browser/maintenance_session_message_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class MaintenanceSessionMessageTest < TestCase diff --git a/test/browser/manage_test.rb b/test/browser/manage_test.rb index 631114ee4..0ecc13415 100644 --- a/test/browser/manage_test.rb +++ b/test/browser/manage_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class ManageTest < TestCase diff --git a/test/browser/monitoring_test.rb b/test/browser/monitoring_test.rb index d4e79b4db..695c4a87e 100644 --- a/test/browser/monitoring_test.rb +++ b/test/browser/monitoring_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class MonitoringTest < TestCase diff --git a/test/browser/preferences_language_test.rb b/test/browser/preferences_language_test.rb index 2dfa5ef87..59903391a 100644 --- a/test/browser/preferences_language_test.rb +++ b/test/browser/preferences_language_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class PreferencesLanguageTest < TestCase diff --git a/test/browser/preferences_permission_check_test.rb b/test/browser/preferences_permission_check_test.rb index 3723708a3..a08e69af1 100644 --- a/test/browser/preferences_permission_check_test.rb +++ b/test/browser/preferences_permission_check_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class PreferencesPermissionCheckTest < TestCase diff --git a/test/browser/preferences_token_access_test.rb b/test/browser/preferences_token_access_test.rb index 11f153440..d6d97cfee 100644 --- a/test/browser/preferences_token_access_test.rb +++ b/test/browser/preferences_token_access_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class PreferencesTokenAccessTest < TestCase diff --git a/test/browser/setting_test.rb b/test/browser/setting_test.rb index 2cbd02b40..5783bd097 100644 --- a/test/browser/setting_test.rb +++ b/test/browser/setting_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class SettingTest < TestCase diff --git a/test/browser/signup_password_change_and_reset_test.rb b/test/browser/signup_password_change_and_reset_test.rb index c72f1d598..b174f2cb7 100644 --- a/test/browser/signup_password_change_and_reset_test.rb +++ b/test/browser/signup_password_change_and_reset_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class SignupPasswordChangeAndResetTest < TestCase diff --git a/test/browser/switch_to_user_test.rb b/test/browser/switch_to_user_test.rb index 6148dcb05..6c953d111 100644 --- a/test/browser/switch_to_user_test.rb +++ b/test/browser/switch_to_user_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class SwitchToUserTest < TestCase diff --git a/test/browser/taskbar_session_test.rb b/test/browser/taskbar_session_test.rb index 7ef161e0b..f289d0d37 100644 --- a/test/browser/taskbar_session_test.rb +++ b/test/browser/taskbar_session_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class TaskbarSessionTest < TestCase diff --git a/test/browser/taskbar_task_test.rb b/test/browser/taskbar_task_test.rb index 5702f4f4b..959008134 100644 --- a/test/browser/taskbar_task_test.rb +++ b/test/browser/taskbar_task_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class TaskbarTaskTest < TestCase diff --git a/test/browser/translation_test.rb b/test/browser/translation_test.rb index c05041895..be17b75b5 100644 --- a/test/browser/translation_test.rb +++ b/test/browser/translation_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class TranslationTest < TestCase diff --git a/test/browser/user_switch_cache_test.rb b/test/browser/user_switch_cache_test.rb index 7b700c7ab..576fdbb4d 100644 --- a/test/browser/user_switch_cache_test.rb +++ b/test/browser/user_switch_cache_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class UserSwitchCache < TestCase diff --git a/test/browser_test_helper.rb b/test/browser_test_helper.rb index f8f12fb19..909503218 100644 --- a/test/browser_test_helper.rb +++ b/test/browser_test_helper.rb @@ -1,5 +1,5 @@ ENV['RAILS_ENV'] = 'test' -# rubocop:disable HandleExceptions, ClassVars, NonLocalExitFromIterator +# rubocop:disable HandleExceptions, ClassVars, NonLocalExitFromIterator, Style/GuardClause require File.expand_path('../../config/environment', __FILE__) require 'selenium-webdriver' @@ -33,7 +33,7 @@ class TestCase < Test::Unit::TestCase end def browser_support_cookies - if browser =~ /(internet_explorer|ie)/i + if browser.match?(/(internet_explorer|ie)/i) return false end true @@ -47,7 +47,7 @@ class TestCase < Test::Unit::TestCase if !@browsers @browsers = {} end - if !ENV['REMOTE_URL'] || ENV['REMOTE_URL'].empty? + if ENV['REMOTE_URL'].blank? local_browser = Selenium::WebDriver.for(browser.to_sym, profile: profile) @browsers[local_browser.hash] = local_browser browser_instance_preferences(local_browser) @@ -116,7 +116,7 @@ class TestCase < Test::Unit::TestCase def teardown return if !@browsers - @browsers.each do |_hash, local_browser| + @browsers.each_value do |local_browser| screenshot(browser: local_browser, comment: 'teardown') browser_instance_close(local_browser) end @@ -874,14 +874,12 @@ class TestCase < Test::Unit::TestCase instance = params[:browser] || @browser element = instance.find_elements(css: params[:css])[0] - if params[:css] =~ /select/ + if params[:css].match?(/select/) dropdown = Selenium::WebDriver::Support::Select.new(element) success = false - if dropdown.selected_options - dropdown.selected_options.each do |option| - if option.text == params[:value] - success = true - end + dropdown.selected_options&.each do |option| + if option.text == params[:value] + success = true end end if params[:should_not_match] @@ -901,13 +899,12 @@ class TestCase < Test::Unit::TestCase begin text = if params[:attribute] element.attribute(params[:attribute]) - elsif params[:css] =~ /(input|textarea)/i + elsif params[:css].match?(/(input|textarea)/i) element.attribute('value') else element.text end rescue => e - # just try again if !fallback return match(params, true) @@ -928,7 +925,7 @@ class TestCase < Test::Unit::TestCase if text =~ /#{params[:value]}/i match = $1 || true end - elsif text =~ /#{Regexp.quote(params[:value])}/i + elsif text.match?(/#{Regexp.quote(params[:value])}/i) match = true end @@ -1020,7 +1017,6 @@ set type of task (closeTab, closeNextInOverview, stayOnTab) cookies = instance.manage.all_cookies 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 @@ -1062,7 +1058,7 @@ set type of task (closeTab, closeNextInOverview, stayOnTab) instance = params[:browser] || @browser title = instance.title - if title =~ /#{params[:value]}/i + if title.match?(/#{params[:value]}/i) assert(true, "matching '#{params[:value]}' in title '#{title}'") else raise "not matching '#{params[:value]}' in title '#{title}'" @@ -1091,11 +1087,10 @@ set type of task (closeTab, closeNextInOverview, stayOnTab) sleep 1 begin - # verify title if data[:title] title = instance.find_elements(css: '.tasks .is-active')[0].text.strip - if title =~ /#{data[:title]}/i + if title.match?(/#{data[:title]}/i) assert(true, "matching '#{data[:title]}' in title '#{title}'") else screenshot(browser: instance, comment: 'verify_task_failed') @@ -1135,7 +1130,6 @@ set type of task (closeTab, closeNextInOverview, stayOnTab) end end rescue => e - # just try again if !fallback verify_task(params, true) @@ -1228,7 +1222,7 @@ set type of task (closeTab, closeNextInOverview, stayOnTab) instance = params[:browser] || @browser params[:files].each do |file| - instance.find_elements(css: params[:css])[0].send_keys "#{Rails.root}/#{file}" + instance.find_elements(css: params[:css])[0].send_keys(Rails.root.join(file)) end sleep 2 * params[:files].count end @@ -1261,7 +1255,6 @@ set type of task (closeTab, closeNextInOverview, stayOnTab) element = instance.find_elements(css: params[:css])[0] if element #&& element.displayed? begin - # watch for selector if !params[:attribute] && !params[:value] assert(true, "'#{params[:css]}' found") @@ -1272,12 +1265,12 @@ set type of task (closeTab, closeNextInOverview, stayOnTab) else text = if params[:attribute] element.attribute(params[:attribute]) - elsif params[:css] =~ /(input|textarea)/i + elsif params[:css].match?(/(input|textarea)/i) element.attribute('value') else element.text end - if text =~ /#{params[:value]}/i + if text.match?(/#{params[:value]}/i) assert(true, "'#{params[:value]}' found in '#{text}'") sleep 0.5 return true @@ -1499,9 +1492,7 @@ wait untill text in selector disabppears instance.mouse.move_to(instance.find_elements(css: '.js-notificationsContainer .js-item:first-child')[0]) sleep 0.1 click_element = instance.find_elements(css: '.js-notificationsContainer .js-item:first-child .js-remove')[0] - if click_element - click_element.click - end + click_element&.click else break end @@ -1530,7 +1521,6 @@ wait untill text in selector disabppears begin instance.find_elements(css: '.search .js-emptySearch')[0].click rescue - # in issues with ff & selenium, sometimes exeption appears # "Element is not currently visible and so may not be interacted with" log('empty_search via js') @@ -1636,23 +1626,21 @@ wait untill text in selector disabppears end end - if data[:selector] - data[:selector].each do |key, value| - select( - browser: instance, - css: '.modal .ticket_selector .js-attributeSelector select', - value: key, - mute_log: true, - ) - sleep 0.5 - select( - browser: instance, - css: '.modal .ticket_selector .js-value select', - value: value, - deselect_all: true, - mute_log: true, - ) - end + data[:selector]&.each do |key, value| + select( + browser: instance, + css: '.modal .ticket_selector .js-attributeSelector select', + value: key, + mute_log: true, + ) + sleep 0.5 + select( + browser: instance, + css: '.modal .ticket_selector .js-value select', + value: value, + deselect_all: true, + mute_log: true, + ) end if data['order::direction'] @@ -1669,7 +1657,7 @@ wait untill text in selector disabppears 11.times do element = instance.find_elements(css: 'body')[0] text = element.text - if text =~ /#{Regexp.quote(data[:name])}/ + if text.match?(/#{Regexp.quote(data[:name])}/) assert(true, 'overview created') overview = { name: name, @@ -1742,23 +1730,21 @@ wait untill text in selector disabppears end end - if data[:selector] - data[:selector].each do |key, value| - select( - browser: instance, - css: '.modal .ticket_selector .js-attributeSelector select', - value: key, - mute_log: true, - ) - sleep 0.5 - select( - browser: instance, - css: '.modal .ticket_selector .js-value select', - value: value, - deselect_all: true, - mute_log: true, - ) - end + data[:selector]&.each do |key, value| + select( + browser: instance, + css: '.modal .ticket_selector .js-attributeSelector select', + value: key, + mute_log: true, + ) + sleep 0.5 + select( + browser: instance, + css: '.modal .ticket_selector .js-value select', + value: value, + deselect_all: true, + mute_log: true, + ) end if data['order::direction'] @@ -1775,7 +1761,7 @@ wait untill text in selector disabppears 11.times do element = instance.find_elements(css: 'body')[0] text = element.text - if text =~ /#{Regexp.quote(data[:name])}/ + if text.match?(/#{Regexp.quote(data[:name])}/) assert(true, 'overview updated') overview = { name: name, @@ -1963,24 +1949,20 @@ wait untill text in selector disabppears end end - if params[:custom_data_select] - 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 + 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 - if params[:custom_data_input] - 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 + 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 if data[:attachment] @@ -2005,7 +1987,7 @@ wait untill text in selector disabppears sleep 1 9.times do - if instance.current_url =~ /#{Regexp.quote('#ticket/zoom/')}/ + if instance.current_url.match?(/#{Regexp.quote('#ticket/zoom/')}/) assert(true, 'ticket created') sleep 2.5 id = instance.current_url @@ -2197,27 +2179,23 @@ wait untill text in selector disabppears ) end - if params[:custom_data_select] - params[:custom_data_select].each do |local_key, local_value| - select( - browser: instance, - css: ".active .sidebar select[name=\"#{local_key}\"]", - value: local_value, - ) - end + params[:custom_data_select]&.each do |local_key, local_value| + select( + browser: instance, + css: ".active .sidebar select[name=\"#{local_key}\"]", + value: local_value, + ) end - if params[:custom_data_input] - 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 + 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 - if data[:state] || data[:group] || data[:body] || !params[:custom_data_select].empty? || !params[:custom_data_input].empty? + if data[:state] || data[:group] || data[:body] || params[:custom_data_select].present? || params[:custom_data_input].present? found = nil 9.times do @@ -2225,7 +2203,7 @@ wait untill text in selector disabppears begin text = instance.find_elements(css: '.content.active .js-reset')[0].text - if text =~ /(Discard your unsaved changes.|Verwerfen der)/ + if text.match?(/(Discard your unsaved changes.|Verwerfen der)/) found = true end rescue @@ -2304,7 +2282,7 @@ wait untill text in selector disabppears if data[:title] title = instance.find_elements(css: '.content.active .ticketZoom-header .js-objectTitle').first.text.strip - if title =~ /#{data[:title]}/i + if title.match?(/#{data[:title]}/i) assert(true, "matching '#{data[:title]}' in title '#{title}'") else raise "not matching '#{data[:title]}' in title '#{title}'" @@ -2313,33 +2291,29 @@ wait untill text in selector disabppears if data[:body] body = instance.find_elements(css: '.content.active [data-name="body"]').first.text.strip - if body =~ /#{data[:body]}/i + if body.match?(/#{data[:body]}/i) assert(true, "matching '#{data[:body]}' in body '#{body}'") else raise "not matching '#{data[:body]}' in body '#{body}'" end end - if params[:custom_data_select] - 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 - assert(true, "matching '#{value}' in #{local_key} '#{local_value}'") - else - raise "not matching '#{value}' in #{local_key} '#{local_value}'" - end + 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.match?(/#{local_value}/i) + assert(true, "matching '#{value}' in #{local_key} '#{local_value}'") + else + raise "not matching '#{value}' in #{local_key} '#{local_value}'" end end - if params[:custom_data_input] - 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 - assert(true, "matching '#{value}' in #{local_key} '#{local_value}'") - else - raise "not matching '#{value}' in #{local_key} '#{local_value}'" - end + 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.match?(/#{local_value}/i) + assert(true, "matching '#{value}' in #{local_key} '#{local_value}'") + else + raise "not matching '#{value}' in #{local_key} '#{local_value}'" end end @@ -2528,7 +2502,7 @@ wait untill text in selector disabppears #puts url.inspect #puts element.inspect end - overviews.each do |url, _value| + overviews.each_key do |url| count = instance.find_elements(css: ".content.active .sidebar a[href=\"#{url}\"] .badge")[0].text overviews[url] = count.to_i end @@ -2735,7 +2709,7 @@ wait untill text in selector disabppears 7.times do element = instance.find_elements(css: 'body')[0] text = element.text - if text =~ /#{Regexp.quote(data[:name])}/ + if text.match?(/#{Regexp.quote(data[:name])}/) assert(true, 'sla created') sleep 1 return true @@ -2802,7 +2776,7 @@ wait untill text in selector disabppears 7.times do element = instance.find_elements(css: 'body')[0] text = element.text - if text =~ /#{Regexp.quote(data[:name])}/ + if text.match?(/#{Regexp.quote(data[:name])}/) assert(true, 'text module created') sleep 1 return true @@ -2869,7 +2843,7 @@ wait untill text in selector disabppears 11.times do element = instance.find_elements(css: 'body')[0] text = element.text - if text =~ /#{Regexp.quote(data[:name])}/ + if text.match?(/#{Regexp.quote(data[:name])}/) assert(true, 'signature created') sleep 1 return true @@ -2938,30 +2912,28 @@ wait untill text in selector disabppears 11.times do element = instance.find_elements(css: 'body')[0] text = element.text - if text =~ /#{Regexp.quote(data[:name])}/ + if text.match?(/#{Regexp.quote(data[:name])}/) assert(true, 'group created') modal_disappear(browser: instance) # wait until modal has gone # add member - if data[: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 - sleep 3 - element = instance.find_elements(css: '.content.active [name="search"]')[0] - element.clear - element.send_keys(member[:login]) - sleep 3 - #instance.find_elements(:css => '.content.active table [data-id]')[0].click - instance.execute_script('$(".content.active table [data-id] td").first().click()') - modal_ready(browser: instance) - #instance.find_elements(:css => 'label:contains(" ' + action[:name] + '")')[0].click - instance.execute_script('$(".js-groupList tr:contains(\"' + data[:name] + '\") .js-groupListItem[value=' + member[:access] + ']").prop("checked", true)') - screenshot(browser: instance, comment: 'group_create_member') - instance.find_elements(css: '.modal button.js-submit')[0].click - modal_disappear(browser: instance) - end + 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 + sleep 3 + element = instance.find_elements(css: '.content.active [name="search"]')[0] + element.clear + element.send_keys(member[:login]) + sleep 3 + #instance.find_elements(:css => '.content.active table [data-id]')[0].click + instance.execute_script('$(".content.active table [data-id] td").first().click()') + modal_ready(browser: instance) + #instance.find_elements(:css => 'label:contains(" ' + action[:name] + '")')[0].click + instance.execute_script('$(".js-groupList tr:contains(\"' + data[:name] + '\") .js-groupListItem[value=' + member[:access] + ']").prop("checked", true)') + screenshot(browser: instance, comment: 'group_create_member') + instance.find_elements(css: '.modal button.js-submit')[0].click + modal_disappear(browser: instance) end end sleep 1 @@ -3048,29 +3020,27 @@ wait untill text in selector disabppears 11.times do element = instance.find_elements(css: 'body')[0] text = element.text - if text =~ /#{Regexp.quote(data[:name])}/ + if text.match?(/#{Regexp.quote(data[:name])}/) assert(true, 'role created') modal_disappear(browser: instance) # wait until modal has gone # add member - if data[:member] - 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 - sleep 3 - element = instance.find_elements(css: '.content.active [name="search"]')[0] - element.clear - element.send_keys(login) - sleep 3 - #instance.find_elements(:css => '.content.active table [data-id]')[0].click - instance.execute_script('$(".content.active table [data-id] td").first().click()') - sleep 3 - #instance.find_elements(:css => 'label:contains(" ' + action[:name] + '")')[0].click - instance.execute_script('$(\'label:contains(" ' + data[:name] + '")\').first().click()') - instance.find_elements(css: '.modal button.js-submit')[0].click - modal_disappear(browser: instance) - end + 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 + sleep 3 + element = instance.find_elements(css: '.content.active [name="search"]')[0] + element.clear + element.send_keys(login) + sleep 3 + #instance.find_elements(:css => '.content.active table [data-id]')[0].click + instance.execute_script('$(".content.active table [data-id] td").first().click()') + sleep 3 + #instance.find_elements(:css => 'label:contains(" ' + action[:name] + '")')[0].click + 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 sleep 1 @@ -3164,29 +3134,27 @@ wait untill text in selector disabppears 11.times do element = instance.find_elements(css: 'body')[0] text = element.text - if text =~ /#{Regexp.quote(data[:name])}/ + if text.match?(/#{Regexp.quote(data[:name])}/) assert(true, 'role created') modal_disappear(browser: instance) # wait until modal has gone # add member - if data[:member] - 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 - sleep 3 - element = instance.find_elements(css: '.content.active [name="search"]')[0] - element.clear - element.send_keys(login) - sleep 3 - #instance.find_elements(:css => '.content.active table [data-id]')[0].click - instance.execute_script('$(".content.active table [data-id] td").first().click()') - sleep 3 - #instance.find_elements(:css => 'label:contains(" ' + action[:name] + '")')[0].click - instance.execute_script('$(\'label:contains(" ' + data[:name] + '")\').first().click()') - instance.find_elements(css: '.modal button.js-submit')[0].click - modal_disappear(browser: instance) - end + 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 + sleep 3 + element = instance.find_elements(css: '.content.active [name="search"]')[0] + element.clear + element.send_keys(login) + sleep 3 + #instance.find_elements(:css => '.content.active table [data-id]')[0].click + instance.execute_script('$(".content.active table [data-id] td").first().click()') + sleep 3 + #instance.find_elements(:css => 'label:contains(" ' + action[:name] + '")')[0].click + 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 sleep 1 @@ -3332,12 +3300,14 @@ wait untill text in selector disabppears if data[:data_option] if data[:data_option][:options] if data[:data_type] == 'Boolean' + # rubocop:disable Lint/BooleanSymbol element = instance.find_elements(css: '.modal .js-valueTrue').first element.clear element.send_keys(data[:data_option][:options][:true]) element = instance.find_elements(css: '.modal .js-valueFalse').first element.clear element.send_keys(data[:data_option][:options][:false]) + # rubocop:enable Lint/BooleanSymbol else data[:data_option][:options].each do |key, value| element = instance.find_elements(css: '.modal .js-Table .js-key').last @@ -3352,14 +3322,14 @@ wait untill text in selector disabppears end end - [:default, :min, :max, :diff].each do |key| + %i[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 do |key| + %i[future past].each do |key| next if !data[:data_option].key?(key) select( browser: instance, @@ -3388,7 +3358,7 @@ wait untill text in selector disabppears 11.times do element = instance.find_elements(css: 'body')[0] text = element.text - if text =~ /#{Regexp.quote(data[:name])}/ + if text.match?(/#{Regexp.quote(data[:name])}/) assert(true, 'object manager attribute created') sleep 1 return true @@ -3454,12 +3424,14 @@ wait untill text in selector disabppears if data[:data_option] if data[:data_option][:options] if data[:data_type] == 'Boolean' + # rubocop:disable Lint/BooleanSymbol element = instance.find_elements(css: '.modal .js-valueTrue').first element.clear element.send_keys(data[:data_option][:options][:true]) element = instance.find_elements(css: '.modal .js-valueFalse').first element.clear element.send_keys(data[:data_option][:options][:false]) + # rubocop:enable Lint/BooleanSymbol else data[:data_option][:options].each do |key, value| element = instance.find_elements(css: '.modal .js-Table .js-key').last @@ -3474,14 +3446,14 @@ wait untill text in selector disabppears end end - [:default, :min, :max, :diff].each do |key| + %i[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 do |key| + %i[future past].each do |key| next if !data[:data_option].key?(key) select( browser: instance, @@ -3510,7 +3482,7 @@ wait untill text in selector disabppears 11.times do element = instance.find_elements(css: 'body')[0] text = element.text - if text =~ /#{Regexp.quote(data[:name])}/ + if text.match?(/#{Regexp.quote(data[:name])}/) assert(true, 'object manager attribute updated') sleep 1 return true @@ -3617,7 +3589,7 @@ wait untill text in selector disabppears assert(tags[0]) tags_found = {} - params[:tags].each do |key, _value| + params[:tags].each_key do |key| tags_found[key] = false end diff --git a/test/controllers/api_auth_controller_test.rb b/test/controllers/api_auth_controller_test.rb index 019ffd696..3bd3f35aa 100644 --- a/test/controllers/api_auth_controller_test.rb +++ b/test/controllers/api_auth_controller_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class ApiAuthControllerTest < ActionDispatch::IntegrationTest @@ -8,7 +8,7 @@ class ApiAuthControllerTest < ActionDispatch::IntegrationTest @headers = { 'ACCEPT' => 'application/json', 'CONTENT_TYPE' => 'application/json' } # create agent - roles = Role.where(name: %w(Admin Agent)) + roles = Role.where(name: %w[Admin Agent]) groups = Group.all UserInfo.current_user_id = 1 diff --git a/test/controllers/basic_controller_test.rb b/test/controllers/basic_controller_test.rb index 7c7c1bf5b..da6306be3 100644 --- a/test/controllers/basic_controller_test.rb +++ b/test/controllers/basic_controller_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class BasicControllerTest < ActionDispatch::IntegrationTest diff --git a/test/controllers/form_controller_test.rb b/test/controllers/form_controller_test.rb index a90844a70..7c14edbd8 100644 --- a/test/controllers/form_controller_test.rb +++ b/test/controllers/form_controller_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' require 'rake' diff --git a/test/controllers/integration_check_mk_controller_test.rb b/test/controllers/integration_check_mk_controller_test.rb index ae0465fe2..d14a7534a 100644 --- a/test/controllers/integration_check_mk_controller_test.rb +++ b/test/controllers/integration_check_mk_controller_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class IntegationCheckMkControllerTest < ActionDispatch::IntegrationTest diff --git a/test/controllers/monitoring_controller_test.rb b/test/controllers/monitoring_controller_test.rb index 26bfe7389..b9c6d7bdc 100644 --- a/test/controllers/monitoring_controller_test.rb +++ b/test/controllers/monitoring_controller_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class MonitoringControllerTest < ActionDispatch::IntegrationTest @@ -12,7 +12,7 @@ class MonitoringControllerTest < ActionDispatch::IntegrationTest Setting.set('monitoring_token', @token) # create agent - roles = Role.where(name: %w(Admin Agent)) + roles = Role.where(name: %w[Admin Agent]) groups = Group.all # channel cleanup @@ -24,7 +24,7 @@ class MonitoringControllerTest < ActionDispatch::IntegrationTest channel.last_log_out = nil channel.save! end - dir = "#{Rails.root}/tmp/unprocessable_mail" + dir = Rails.root.join('tmp', 'unprocessable_mail') Dir.glob("#{dir}/*.eml") do |entry| File.delete(entry) end @@ -374,7 +374,7 @@ class MonitoringControllerTest < ActionDispatch::IntegrationTest assert_equal(false, result['healthy']) assert_equal('Channel: Email::Notification out ;scheduler not running', result['message']) - dir = "#{Rails.root}/tmp/unprocessable_mail" + dir = Rails.root.join('tmp', 'unprocessable_mail') FileUtils.mkdir_p(dir) FileUtils.touch("#{dir}/test.eml") diff --git a/test/controllers/packages_controller_test.rb b/test/controllers/packages_controller_test.rb index 36d79343e..1eac66ca5 100644 --- a/test/controllers/packages_controller_test.rb +++ b/test/controllers/packages_controller_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class PackagesControllerTest < ActionDispatch::IntegrationTest @@ -8,7 +8,7 @@ class PackagesControllerTest < ActionDispatch::IntegrationTest @headers = { 'ACCEPT' => 'application/json', 'CONTENT_TYPE' => 'application/json' } # create agent - roles = Role.where(name: %w(Admin Agent)) + roles = Role.where(name: %w[Admin Agent]) groups = Group.all UserInfo.current_user_id = 1 diff --git a/test/controllers/search_controller_test.rb b/test/controllers/search_controller_test.rb index c483dab67..e444485e9 100644 --- a/test/controllers/search_controller_test.rb +++ b/test/controllers/search_controller_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' require 'rake' @@ -12,7 +12,7 @@ class SearchControllerTest < ActionDispatch::IntegrationTest @headers = { 'ACCEPT' => 'application/json', 'CONTENT_TYPE' => 'application/json' } # create agent - roles = Role.where(name: %w(Admin Agent)) + roles = Role.where(name: %w[Admin Agent]) groups = Group.all @admin = User.create_or_update( @@ -195,21 +195,21 @@ class SearchControllerTest < ActionDispatch::IntegrationTest assert_response(401) result = JSON.parse(@response.body) assert_equal(Hash, result.class) - assert_not(result.empty?) + assert_not(result.blank?) assert_equal('authentication failed', result['error']) post '/api/v1/search/user', params: params.to_json, headers: @headers assert_response(401) result = JSON.parse(@response.body) assert_equal(Hash, result.class) - assert_not(result.empty?) + assert_not(result.blank?) assert_equal('authentication failed', result['error']) post '/api/v1/search', params: params.to_json, headers: @headers assert_response(401) result = JSON.parse(@response.body) assert_equal(Hash, result.class) - assert_not(result.empty?) + assert_not(result.blank?) assert_equal('authentication failed', result['error']) end diff --git a/test/controllers/settings_controller_test.rb b/test/controllers/settings_controller_test.rb index 93249425b..5930ba0f5 100644 --- a/test/controllers/settings_controller_test.rb +++ b/test/controllers/settings_controller_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class SettingsControllerTest < ActionDispatch::IntegrationTest @@ -8,7 +8,7 @@ class SettingsControllerTest < ActionDispatch::IntegrationTest @headers = { 'ACCEPT' => 'application/json', 'CONTENT_TYPE' => 'application/json' } # create agent - roles = Role.where(name: %w(Admin Agent)) + roles = Role.where(name: %w[Admin Agent]) groups = Group.all UserInfo.current_user_id = 1 diff --git a/test/controllers/taskbars_controller_test.rb b/test/controllers/taskbars_controller_test.rb index 9c3697669..e8a8bf48b 100644 --- a/test/controllers/taskbars_controller_test.rb +++ b/test/controllers/taskbars_controller_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TaskbarsControllerTest < ActionDispatch::IntegrationTest diff --git a/test/controllers/ticket_article_attachments_controller_test.rb b/test/controllers/ticket_article_attachments_controller_test.rb index 35bbc74eb..2e4286332 100644 --- a/test/controllers/ticket_article_attachments_controller_test.rb +++ b/test/controllers/ticket_article_attachments_controller_test.rb @@ -1,11 +1,11 @@ -# encoding: utf-8 + require 'test_helper' class TicketArticleAttachmentsControllerTest < ActionDispatch::IntegrationTest setup do # create agent - roles = Role.where(name: %w(Admin Agent)) + roles = Role.where(name: %w[Admin Agent]) groups = Group.all UserInfo.current_user_id = 1 diff --git a/test/controllers/ticket_articles_controller_test.rb b/test/controllers/ticket_articles_controller_test.rb index 9119426bf..0fb8be1d0 100644 --- a/test/controllers/ticket_articles_controller_test.rb +++ b/test/controllers/ticket_articles_controller_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketArticlesControllerTest < ActionDispatch::IntegrationTest @@ -8,7 +8,7 @@ class TicketArticlesControllerTest < ActionDispatch::IntegrationTest @headers = { 'ACCEPT' => 'application/json', 'CONTENT_TYPE' => 'application/json' } # create agent - roles = Role.where(name: %w(Admin Agent)) + roles = Role.where(name: %w[Admin Agent]) groups = Group.all UserInfo.current_user_id = 1 diff --git a/test/controllers/tickets_controller_test.rb b/test/controllers/tickets_controller_test.rb index d63bac89e..aaf571fab 100644 --- a/test/controllers/tickets_controller_test.rb +++ b/test/controllers/tickets_controller_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketsControllerTest < ActionDispatch::IntegrationTest @@ -8,7 +8,7 @@ class TicketsControllerTest < ActionDispatch::IntegrationTest @headers = { 'ACCEPT' => 'application/json', 'CONTENT_TYPE' => 'application/json' } # create agent - roles = Role.where(name: %w(Admin Agent)) + roles = Role.where(name: %w[Admin Agent]) groups = Group.all UserInfo.current_user_id = 1 diff --git a/test/controllers/user_organization_controller_test.rb b/test/controllers/user_organization_controller_test.rb index 4079eba1f..b484d4faf 100644 --- a/test/controllers/user_organization_controller_test.rb +++ b/test/controllers/user_organization_controller_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' require 'rake' @@ -9,7 +9,7 @@ class UserOrganizationControllerTest < ActionDispatch::IntegrationTest @headers = { 'ACCEPT' => 'application/json', 'CONTENT_TYPE' => 'application/json' } # create agent - roles = Role.where(name: %w(Admin Agent)) + roles = Role.where(name: %w[Admin Agent]) groups = Group.all UserInfo.current_user_id = 1 diff --git a/test/fixtures/seeds.rb b/test/fixtures/seeds.rb index 8ed902c03..8f21fdf54 100644 --- a/test/fixtures/seeds.rb +++ b/test/fixtures/seeds.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + # inital data set as extention to db/seeds.rb Trigger.destroy_all @@ -30,7 +30,7 @@ User.create_or_update( email: 'admin@example.com', password: 'adminpw', active: true, - roles: Role.where(name: %w(Admin)), + roles: Role.where(name: %w[Admin]), updated_by_id: 1, created_by_id: 1, ) diff --git a/test/integration/aaa_auto_wizard_base_setup_test.rb b/test/integration/aaa_auto_wizard_base_setup_test.rb index 913583238..8f26b5169 100644 --- a/test/integration/aaa_auto_wizard_base_setup_test.rb +++ b/test/integration/aaa_auto_wizard_base_setup_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AaaAutoWizardBaseSetupTest < TestCase diff --git a/test/integration/auto_wizard_browser_test.rb b/test/integration/auto_wizard_browser_test.rb index b07485433..2a71f78a9 100644 --- a/test/integration/auto_wizard_browser_test.rb +++ b/test/integration/auto_wizard_browser_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class AutoWizardBrowserTest < TestCase diff --git a/test/integration/auto_wizard_test.rb b/test/integration/auto_wizard_test.rb index 17ef729b2..026466bc6 100644 --- a/test/integration/auto_wizard_test.rb +++ b/test/integration/auto_wizard_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class AutoWizardTest < ActiveSupport::TestCase @@ -46,7 +46,7 @@ class AutoWizardTest < ActiveSupport::TestCase assert_equal(false, AutoWizard.enabled?) # check first user roles - auto_wizard_data[:Users][0][:roles] = %w(Agent Admin) + auto_wizard_data[:Users][0][:roles] = %w[Agent Admin] auto_wizard_data[:Users].each do |local_user| user = User.find_by(login: local_user[:login]) @@ -203,11 +203,9 @@ class AutoWizardTest < ActiveSupport::TestCase 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 do |local_user_login| - local_user = User.find_by(login: local_user_login) - assert(group.user_ids.include?(local_user.id)) - end + 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 if local_group[:signature] signature = group.signature @@ -239,14 +237,14 @@ class AutoWizardTest < ActiveSupport::TestCase end def auto_wizard_file_write(data) - location = "#{Rails.root}/auto_wizard.json" + location = Rails.root.join('auto_wizard.json') file = File.new(location, 'wb') file.write(data.to_json) file.close end def auto_wizard_file_exists? - location = "#{Rails.root}/auto_wizard.json" + location = Rails.root.join('auto_wizard.json') return false if File.exist?(location) true end diff --git a/test/integration/calendar_subscriptions_tickets_test.rb b/test/integration/calendar_subscriptions_tickets_test.rb index 0816aacb8..25a9246c8 100644 --- a/test/integration/calendar_subscriptions_tickets_test.rb +++ b/test/integration/calendar_subscriptions_tickets_test.rb @@ -1,4 +1,4 @@ -## encoding: utf-8 + require 'integration_test_helper' class CalendarSubscriptionsTicketsTest < ActiveSupport::TestCase @@ -272,7 +272,7 @@ class CalendarSubscriptionsTicketsTest < ActiveSupport::TestCase event_data.each do |event| contained = false - if ical =~ /#{event[:summary]}/ + if ical.match?(/#{event[:summary]}/) contained = true end @@ -348,7 +348,7 @@ class CalendarSubscriptionsTicketsTest < ActiveSupport::TestCase event_data.each do |event| contained = false - if ical =~ /#{event[:summary]}/ + if ical.match?(/#{event[:summary]}/) contained = true end @@ -424,7 +424,7 @@ class CalendarSubscriptionsTicketsTest < ActiveSupport::TestCase event_data.each do |event| contained = false - if ical =~ /#{event[:summary]}/ + if ical.match?(/#{event[:summary]}/) contained = true end diff --git a/test/integration/clearbit_test.rb b/test/integration/clearbit_test.rb index 6e01e9ca0..1b4f42c2e 100644 --- a/test/integration/clearbit_test.rb +++ b/test/integration/clearbit_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'integration_test_helper' class ClearbitTest < ActiveSupport::TestCase diff --git a/test/integration/elasticsearch_test.rb b/test/integration/elasticsearch_test.rb index 778c4100d..961a3ff30 100644 --- a/test/integration/elasticsearch_test.rb +++ b/test/integration/elasticsearch_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'integration_test_helper' require 'rake' @@ -168,7 +168,7 @@ class ElasticsearchTest < ActiveSupport::TestCase Store.add( object: 'Ticket::Article', o_id: article1.id, - data: IO.binread("#{Rails.root}/test/fixtures/es-normal.txt"), + data: IO.binread(Rails.root.join('test', 'fixtures', 'es-normal.txt')), filename: 'es-normal.txt', preferences: {}, created_by_id: 1, @@ -229,7 +229,7 @@ class ElasticsearchTest < ActiveSupport::TestCase Store.add( object: 'Ticket::Article', o_id: article1.id, - data: IO.binread("#{Rails.root}/test/fixtures/es-normal.txt"), + data: IO.binread(Rails.root.join('test', 'fixtures', 'es-normal.txt')), filename: 'es-normal.txt', preferences: {}, created_by_id: 1, @@ -240,7 +240,7 @@ class ElasticsearchTest < ActiveSupport::TestCase Store.add( object: 'Ticket::Article', o_id: article1.id, - data: IO.binread("#{Rails.root}/test/fixtures/es-pdf1.pdf"), + data: IO.binread(Rails.root.join('test', 'fixtures', 'es-pdf1.pdf')), filename: 'es-pdf1.pdf', preferences: {}, created_by_id: 1, @@ -251,7 +251,7 @@ class ElasticsearchTest < ActiveSupport::TestCase Store.add( object: 'Ticket::Article', o_id: article1.id, - data: IO.binread("#{Rails.root}/test/fixtures/es-box1.box"), + data: IO.binread(Rails.root.join('test', 'fixtures', 'es-box1.box')), filename: 'mail1.box', preferences: {}, created_by_id: 1, @@ -262,7 +262,7 @@ class ElasticsearchTest < ActiveSupport::TestCase Store.add( object: 'Ticket::Article', o_id: article1.id, - data: IO.binread("#{Rails.root}/test/fixtures/es-too-big.txt"), + data: IO.binread(Rails.root.join('test', 'fixtures', 'es-too-big.txt')), filename: 'es-too-big.txt', preferences: {}, created_by_id: 1, @@ -332,7 +332,7 @@ class ElasticsearchTest < ActiveSupport::TestCase limit: 15, ) - assert(!result.empty?, 'result exists not') + assert(result.present?, 'result exists not') assert(result[0], 'record 1') assert(!result[1], 'record 2') assert_equal(result[0].id, ticket2.id) @@ -344,7 +344,7 @@ class ElasticsearchTest < ActiveSupport::TestCase limit: 15, ) - assert(!result.empty?, 'result exists not') + assert(result.present?, 'result exists not') assert(result[0], 'record 1') assert(!result[1], 'record 2') assert_equal(result[0].id, ticket2.id) @@ -387,7 +387,7 @@ class ElasticsearchTest < ActiveSupport::TestCase query: 'kindergarden', limit: 15, ) - assert(result.empty?, 'result should be empty') + assert(result.blank?, 'result should be empty') assert(!result[0], 'record 1') # search as @customer1 @@ -397,7 +397,7 @@ class ElasticsearchTest < ActiveSupport::TestCase limit: 15, ) - assert(!result.empty?, 'result exists not') + assert(result.present?, 'result exists not') assert(result[0], 'record 1') assert(result[1], 'record 2') assert(!result[2], 'record 3') @@ -411,7 +411,7 @@ class ElasticsearchTest < ActiveSupport::TestCase limit: 15, ) - assert(!result.empty?, 'result exists not') + assert(result.present?, 'result exists not') assert(result[0], 'record 1') assert(result[1], 'record 2') assert(!result[2], 'record 3') @@ -425,7 +425,7 @@ class ElasticsearchTest < ActiveSupport::TestCase limit: 15, ) - assert(!result.empty?, 'result exists not') + assert(result.present?, 'result exists not') assert(result[0], 'record 1') assert(!result[1], 'record 2') assert_equal(result[0].id, ticket3.id) @@ -523,7 +523,7 @@ class ElasticsearchTest < ActiveSupport::TestCase query: 'customer1', limit: 15, ) - assert(!result.empty?, 'result should not be empty') + assert(result.present?, 'result should not be empty') assert(result[0], 'record 1') assert(!result[1], 'record 2') assert_equal(result[0].id, @customer1.id) @@ -534,7 +534,7 @@ class ElasticsearchTest < ActiveSupport::TestCase query: 'customer1', limit: 15, ) - assert(result.empty?, 'result should be empty') + assert(result.blank?, 'result should be empty') assert(!result[0], 'record 1') # cleanup diff --git a/test/integration/email_deliver_test.rb b/test/integration/email_deliver_test.rb index 5b069068d..b7dff2901 100644 --- a/test/integration/email_deliver_test.rb +++ b/test/integration/email_deliver_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class EmailDeliverTest < ActiveSupport::TestCase diff --git a/test/integration/email_helper_test.rb b/test/integration/email_helper_test.rb index 745e6c130..f13802872 100644 --- a/test/integration/email_helper_test.rb +++ b/test/integration/email_helper_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class EmailHelperTest < ActiveSupport::TestCase @@ -374,7 +374,7 @@ class EmailHelperTest < ActiveSupport::TestCase assert_equal('invalid', result[:result]) # if we have to many failed logins, we need to handle another error message - if result[:message_human] && !result[:message_human].empty? + if result[:message_human].present? assert_equal('Authentication failed!', result[:message_human]) else assert_match(/Please log in with your web browser and then try again/, result[:message]) diff --git a/test/integration/email_keep_on_server_test.rb b/test/integration/email_keep_on_server_test.rb index 99d8069b9..e3003aad0 100644 --- a/test/integration/email_keep_on_server_test.rb +++ b/test/integration/email_keep_on_server_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' require 'net/imap' diff --git a/test/integration/facebook_browser_test.rb b/test/integration/facebook_browser_test.rb index c42135d5b..d2e371e6f 100644 --- a/test/integration/facebook_browser_test.rb +++ b/test/integration/facebook_browser_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class FacebookBrowserTest < TestCase diff --git a/test/integration/facebook_test.rb b/test/integration/facebook_test.rb index 769b9a523..a9cdc7808 100644 --- a/test/integration/facebook_test.rb +++ b/test/integration/facebook_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'integration_test_helper' class FacebookTest < ActiveSupport::TestCase diff --git a/test/integration/geo_calendar_test.rb b/test/integration/geo_calendar_test.rb index 9cbbe836e..8ecd6bcaa 100644 --- a/test/integration/geo_calendar_test.rb +++ b/test/integration/geo_calendar_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'integration_test_helper' class GeoIpCalendar < ActiveSupport::TestCase diff --git a/test/integration/geo_ip_test.rb b/test/integration/geo_ip_test.rb index b1eaba5e8..a2537343a 100644 --- a/test/integration/geo_ip_test.rb +++ b/test/integration/geo_ip_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'integration_test_helper' class GeoIpTest < ActiveSupport::TestCase diff --git a/test/integration/geo_location_test.rb b/test/integration/geo_location_test.rb index 88e6d1152..7fb38f17c 100644 --- a/test/integration/geo_location_test.rb +++ b/test/integration/geo_location_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'integration_test_helper' require 'webmock/minitest' diff --git a/test/integration/idoit_controller_test.rb b/test/integration/idoit_controller_test.rb index f7d376066..a970abf31 100644 --- a/test/integration/idoit_controller_test.rb +++ b/test/integration/idoit_controller_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' require 'webmock/minitest' @@ -20,7 +20,7 @@ class IdoitControllerTest < ActionDispatch::IntegrationTest client_id: '', }) groups = Group.where(name: 'Users') - roles = Role.where(name: %w(Agent)) + roles = Role.where(name: %w[Agent]) agent = User.create_or_update( login: 'idoit-agent@example.com', firstname: 'E', @@ -33,7 +33,7 @@ class IdoitControllerTest < ActionDispatch::IntegrationTest updated_by_id: 1, created_by_id: 1, ) - roles = Role.where(name: %w(Agent Admin)) + roles = Role.where(name: %w[Agent Admin]) admin = User.create_or_update( login: 'idoit-admin@example.com', firstname: 'E', diff --git a/test/integration/object_manager_test.rb b/test/integration/object_manager_test.rb index c6125a69f..47d9db91a 100644 --- a/test/integration/object_manager_test.rb +++ b/test/integration/object_manager_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 +# rubocop:disable Lint/BooleanSymbol require 'test_helper' class ObjectManagerTest < ActiveSupport::TestCase @@ -7,10 +7,10 @@ class ObjectManagerTest < ActiveSupport::TestCase test 'a object manager' do list_objects = ObjectManager.list_objects - assert_equal(%w(Ticket TicketArticle User Organization Group), list_objects) + assert_equal(%w[Ticket TicketArticle User Organization Group], list_objects) list_objects = ObjectManager.list_frontend_objects - assert_equal(%w(Ticket User Organization Group), list_objects) + assert_equal(%w[Ticket User Organization Group], list_objects) assert_equal(false, ObjectManager::Attribute.pending_migration?) diff --git a/test/integration/otrs_import_browser_test.rb b/test/integration/otrs_import_browser_test.rb index 505bea0fd..9329089e3 100644 --- a/test/integration/otrs_import_browser_test.rb +++ b/test/integration/otrs_import_browser_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class OtrsImportBrowserTest < TestCase diff --git a/test/integration/otrs_import_test.rb b/test/integration/otrs_import_test.rb index c3a839d5a..87010e203 100644 --- a/test/integration/otrs_import_test.rb +++ b/test/integration/otrs_import_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'integration_test_helper' class OtrsImportTest < ActiveSupport::TestCase @@ -33,12 +33,12 @@ class OtrsImportTest < ActiveSupport::TestCase test 'check dynamic fields' do local_objects = ObjectManager::Attribute.list_full - object_attribute_names = local_objects.reject do |local_object| - local_object[:object] != 'Ticket' + object_attribute_names = local_objects.select do |local_object| + local_object[:object] == 'Ticket' 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) + 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') end diff --git a/test/integration/package_test.rb b/test/integration/package_test.rb index 1799e97cc..26bf7f7f2 100644 --- a/test/integration/package_test.rb +++ b/test/integration/package_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class PackageTest < ActiveSupport::TestCase diff --git a/test/integration/report_test.rb b/test/integration/report_test.rb index af1164ae8..b4f300459 100644 --- a/test/integration/report_test.rb +++ b/test/integration/report_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'integration_test_helper' require 'rake' diff --git a/test/integration/sipgate_controller_test.rb b/test/integration/sipgate_controller_test.rb index 26eecf6e6..5d252f130 100644 --- a/test/integration/sipgate_controller_test.rb +++ b/test/integration/sipgate_controller_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' require 'rexml/document' @@ -37,7 +37,7 @@ class SipgateControllerTest < ActionDispatch::IntegrationTest },) groups = Group.where(name: 'Users') - roles = Role.where(name: %w(Agent)) + roles = Role.where(name: %w[Agent]) agent = User.create_or_update( login: 'cti-agent@example.com', firstname: 'E', diff --git a/test/integration/slack_test.rb b/test/integration/slack_test.rb index 52847def9..b57d77367 100644 --- a/test/integration/slack_test.rb +++ b/test/integration/slack_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'integration_test_helper' require 'slack' @@ -34,7 +34,7 @@ class SlackTest < ActiveSupport::TestCase items = [ { group_ids: [slack_group.id], - types: %w(create update reminder_reached), + types: %w[create update reminder_reached], webhook: webhook, channel: channel, username: 'zammad bot', @@ -300,7 +300,7 @@ class SlackTest < ActiveSupport::TestCase message_count = 0 channel_history['messages'].each do |message| next if !message['text'] - if message['text'] =~ /#{search_for}/i + if message['text'].match?(/#{search_for}/i) message_count += 1 p "SUCCESS: message with #{search_for} found #{message_count} time(s)!" end diff --git a/test/integration/telegram_controller_test.rb b/test/integration/telegram_controller_test.rb index c31465ca1..b9adae6b7 100644 --- a/test/integration/telegram_controller_test.rb +++ b/test/integration/telegram_controller_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' require 'rexml/document' require 'webmock/minitest' diff --git a/test/integration/twitter_browser_test.rb b/test/integration/twitter_browser_test.rb index dab4ae94e..c0ea4d20b 100644 --- a/test/integration/twitter_browser_test.rb +++ b/test/integration/twitter_browser_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class TwitterBrowserTest < TestCase diff --git a/test/integration/twitter_test.rb b/test/integration/twitter_test.rb index c1d984f16..25c9f0d7f 100644 --- a/test/integration/twitter_test.rb +++ b/test/integration/twitter_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'integration_test_helper' class TwitterTest < ActiveSupport::TestCase diff --git a/test/integration/user_agent_test.rb b/test/integration/user_agent_test.rb index 57923906c..d3f7b19a6 100644 --- a/test/integration/user_agent_test.rb +++ b/test/integration/user_agent_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'integration_test_helper' class UserAgentTest < ActiveSupport::TestCase diff --git a/test/integration/user_device_controller_test.rb b/test/integration/user_device_controller_test.rb index a5788f44d..d3697b407 100644 --- a/test/integration/user_device_controller_test.rb +++ b/test/integration/user_device_controller_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class UserDeviceControllerTest < ActionDispatch::IntegrationTest @@ -11,7 +11,7 @@ class UserDeviceControllerTest < ActionDispatch::IntegrationTest @headers = { 'ACCEPT' => 'application/json', 'CONTENT_TYPE' => 'application/json' } # create agent - roles = Role.where(name: %w(Admin Agent)) + roles = Role.where(name: %w[Admin Agent]) groups = Group.all UserInfo.current_user_id = 1 diff --git a/test/integration/zendesk_import_browser_test.rb b/test/integration/zendesk_import_browser_test.rb index 60876e0bf..1963ac81d 100644 --- a/test/integration/zendesk_import_browser_test.rb +++ b/test/integration/zendesk_import_browser_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'browser_test_helper' class ZendeskImportBrowserTest < TestCase diff --git a/test/integration/zendesk_import_test.rb b/test/integration/zendesk_import_test.rb index 8d125fa7a..fe598f861 100644 --- a/test/integration/zendesk_import_test.rb +++ b/test/integration/zendesk_import_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'integration_test_helper' class ZendeskImportTest < ActiveSupport::TestCase @@ -155,7 +155,7 @@ class ZendeskImportTest < ActiveSupport::TestCase # check user fields test 'check user fields' do local_fields = User.column_names - copmare_fields = %w( + copmare_fields = %w[ id organization_id login @@ -193,7 +193,7 @@ class ZendeskImportTest < ActiveSupport::TestCase updated_at lieblingstier custom_dropdown - ) + ] assert_equal(copmare_fields, local_fields, 'user fields') end @@ -275,7 +275,7 @@ class ZendeskImportTest < ActiveSupport::TestCase # check organization fields test 'check organization fields' do local_fields = Organization.column_names - copmare_fields = %w( + copmare_fields = %w[ id name shared @@ -289,7 +289,7 @@ class ZendeskImportTest < ActiveSupport::TestCase updated_at api_key custom_dropdown - ) + ] assert_equal(copmare_fields, local_fields, 'organization fields') end @@ -456,7 +456,7 @@ If you\'re reading this message in your email, click the ticket number link that # check ticket fields test 'check ticket fields' do local_fields = Ticket.column_names - copmare_fields = %w( + copmare_fields = %w[ id group_id priority_id @@ -500,7 +500,7 @@ If you\'re reading this message in your email, click the ticket number link that custom_integer custom_regex custom_drop_down - ) + ] assert_equal(copmare_fields, local_fields, 'ticket fields') end diff --git a/test/integration_test_helper.rb b/test/integration_test_helper.rb index 841df1ccc..ca23a6622 100644 --- a/test/integration_test_helper.rb +++ b/test/integration_test_helper.rb @@ -15,8 +15,8 @@ class ActiveSupport::TestCase Cache.clear # load seeds - load "#{Rails.root}/db/seeds.rb" - load "#{Rails.root}/test/fixtures/seeds.rb" + load Rails.root.join('db', 'seeds.rb') + load Rails.root.join('test', 'fixtures', 'seeds.rb') setup do diff --git a/test/test_helper.rb b/test/test_helper.rb index d1064274c..51bb095e5 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -28,8 +28,8 @@ class ActiveSupport::TestCase Cache.clear # load seeds - load "#{Rails.root}/db/seeds.rb" - load "#{Rails.root}/test/fixtures/seeds.rb" + load Rails.root.join('db', 'seeds.rb') + load Rails.root.join('test', 'fixtures', 'seeds.rb') # set system mode to done / to activate Setting.set('system_init_done', true) @@ -67,14 +67,14 @@ class ActiveSupport::TestCase def email_notification_count(type, recipient) # read config file and count type & recipients - file = "#{Rails.root}/log/#{Rails.env}.log" + file = Rails.root.join('log', "#{Rails.env}.log") lines = [] IO.foreach(file) do |line| lines.push line end count = 0 lines.reverse.each do |line| - break if line =~ /\+\+\+\+NEW\+\+\+\+TEST\+\+\+\+/ + break if line.match?(/\+\+\+\+NEW\+\+\+\+TEST\+\+\+\+/) next if line !~ /Send notification \(#{type}\)/ next if line !~ /to:\s#{recipient}/ count += 1 @@ -85,14 +85,14 @@ class ActiveSupport::TestCase def email_count(recipient) # read config file and count & recipients - file = "#{Rails.root}/log/#{Rails.env}.log" + file = Rails.root.join('log', "#{Rails.env}.log") lines = [] IO.foreach(file) do |line| lines.push line end count = 0 lines.reverse.each do |line| - break if line =~ /\+\+\+\+NEW\+\+\+\+TEST\+\+\+\+/ + break if line.match?(/\+\+\+\+NEW\+\+\+\+TEST\+\+\+\+/) next if line !~ /Send email to:/ next if line !~ /to:\s'#{recipient}'/ count += 1 diff --git a/test/unit/aaa_string_test.rb b/test/unit/aaa_string_test.rb index e1c0458f1..70f2da1be 100644 --- a/test/unit/aaa_string_test.rb +++ b/test/unit/aaa_string_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 # rubocop:disable all require 'test_helper' diff --git a/test/unit/activity_stream_test.rb b/test/unit/activity_stream_test.rb index 01110299e..3b2f8cda4 100644 --- a/test/unit/activity_stream_test.rb +++ b/test/unit/activity_stream_test.rb @@ -1,10 +1,10 @@ -# encoding: utf-8 + require 'test_helper' class ActivityStreamTest < ActiveSupport::TestCase setup do - roles = Role.where(name: %w(Admin Agent)) + roles = Role.where(name: %w[Admin Agent]) groups = Group.where(name: 'Users') @admin_user = User.create_or_update( login: 'admin', @@ -83,7 +83,7 @@ class ActivityStreamTest < ActiveSupport::TestCase assert_not(stream[3]) stream = @current_user.activity_stream(4) - assert(stream.empty?) + assert(stream.blank?) # cleanup ticket.destroy! @@ -122,7 +122,7 @@ class ActivityStreamTest < ActiveSupport::TestCase assert_not(stream[2]) stream = @current_user.activity_stream(4) - assert(stream.empty?) + assert(stream.blank?) # cleanup organization.destroy! @@ -154,7 +154,7 @@ class ActivityStreamTest < ActiveSupport::TestCase assert_not(stream[1]) stream = @current_user.activity_stream(4) - assert(stream.empty?) + assert(stream.blank?) # cleanup user.destroy! @@ -201,7 +201,7 @@ class ActivityStreamTest < ActiveSupport::TestCase assert_not(stream[2]) stream = @current_user.activity_stream(4) - assert(stream.empty?) + assert(stream.blank?) # cleanup user.destroy! diff --git a/test/unit/assets_test.rb b/test/unit/assets_test.rb index 9e7914d7b..538f1c492 100644 --- a/test/unit/assets_test.rb +++ b/test/unit/assets_test.rb @@ -1,10 +1,10 @@ -# encoding: utf-8 + require 'test_helper' class AssetsTest < ActiveSupport::TestCase test 'user' do - roles = Role.where(name: %w(Agent Admin)) + roles = Role.where(name: %w[Agent Admin]) groups = Group.all org1 = Organization.create_or_update( name: 'some user org', @@ -141,7 +141,7 @@ class AssetsTest < ActiveSupport::TestCase test 'organization' do - roles = Role.where( name: %w(Agent Admin) ) + roles = Role.where( name: %w[Agent Admin] ) admin1 = User.create_or_update( login: 'admin1@example.org', firstname: 'admin1', @@ -154,7 +154,7 @@ class AssetsTest < ActiveSupport::TestCase roles: roles, ) - roles = Role.where( name: %w(Customer) ) + roles = Role.where( name: %w[Customer] ) org = Organization.create_or_update( name: 'some customer org', updated_by_id: admin1.id, @@ -278,7 +278,7 @@ class AssetsTest < ActiveSupport::TestCase def diff(o1, o2) return true if o1 == o2 - %w(updated_at created_at).each do |item| + %w[updated_at created_at].each do |item| if o1[item] o1[item] = o1[item].to_s end @@ -286,7 +286,7 @@ class AssetsTest < ActiveSupport::TestCase o2[item] = o2[item].to_s end end - return true if (o1.to_a - o2.to_a).empty? + return true if (o1.to_a - o2.to_a).blank? #puts "ERROR: difference \n1: #{o1.inspect}\n2: #{o2.inspect}\ndiff: #{(o1.to_a - o2.to_a).inspect}" false end @@ -294,7 +294,7 @@ class AssetsTest < ActiveSupport::TestCase test 'overview' do UserInfo.current_user_id = 1 - roles = Role.where(name: %w(Customer)) + roles = Role.where(name: %w[Customer]) user1 = User.create_or_update( login: 'assets_overview1@example.org', @@ -368,9 +368,9 @@ class AssetsTest < ActiveSupport::TestCase direction: 'ASC', }, view: { - d: %w(title customer group created_at), - s: %w(title customer group created_at), - m: %w(number title customer group created_at), + d: %w[title customer group created_at], + s: %w[title customer group created_at], + m: %w[number title customer group created_at], view_mode_default: 's', }, ) @@ -405,9 +405,9 @@ class AssetsTest < ActiveSupport::TestCase direction: 'ASC', }, view: { - d: %w(title customer group created_at), - s: %w(title customer group created_at), - m: %w(number title customer group created_at), + d: %w[title customer group created_at], + s: %w[title customer group created_at], + m: %w[number title customer group created_at], view_mode_default: 's', }, ) @@ -425,7 +425,7 @@ class AssetsTest < ActiveSupport::TestCase test 'sla' do UserInfo.current_user_id = 1 - roles = Role.where(name: %w(Customer)) + roles = Role.where(name: %w[Customer]) user1 = User.create_or_update( login: 'assets_sla1@example.org', @@ -491,7 +491,7 @@ class AssetsTest < ActiveSupport::TestCase test 'job' do UserInfo.current_user_id = 1 - roles = Role.where(name: %w(Customer)) + roles = Role.where(name: %w[Customer]) user1 = User.create_or_update( login: 'assets_job1@example.org', diff --git a/test/unit/auth_test.rb b/test/unit/auth_test.rb index f982e4e6e..151782666 100644 --- a/test/unit/auth_test.rb +++ b/test/unit/auth_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class AuthTest < ActiveSupport::TestCase diff --git a/test/unit/cache_test.rb b/test/unit/cache_test.rb index 37992bdaf..76b8bdc27 100644 --- a/test/unit/cache_test.rb +++ b/test/unit/cache_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class CacheTest < ActiveSupport::TestCase diff --git a/test/unit/calendar_subscription_test.rb b/test/unit/calendar_subscription_test.rb index 3e31dbab1..36292b148 100644 --- a/test/unit/calendar_subscription_test.rb +++ b/test/unit/calendar_subscription_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class CalendarSubscriptionTest < ActiveSupport::TestCase diff --git a/test/unit/calendar_test.rb b/test/unit/calendar_test.rb index 0b33fa1b2..ac57ce9cf 100644 --- a/test/unit/calendar_test.rb +++ b/test/unit/calendar_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class CalendarTest < ActiveSupport::TestCase diff --git a/test/unit/chat_test.rb b/test/unit/chat_test.rb index fe406d23b..27b428d38 100644 --- a/test/unit/chat_test.rb +++ b/test/unit/chat_test.rb @@ -1,11 +1,11 @@ -# encoding: utf-8 + require 'test_helper' class ChatTest < ActiveSupport::TestCase setup do groups = Group.all - roles = Role.where( name: %w(Agent) ) + roles = Role.where( name: %w[Agent] ) @agent1 = User.create_or_update( login: 'ticket-chat-agent1@example.com', firstname: 'Notification', diff --git a/test/unit/cti_caller_id_test.rb b/test/unit/cti_caller_id_test.rb index 94c08c078..7a899f9e7 100644 --- a/test/unit/cti_caller_id_test.rb +++ b/test/unit/cti_caller_id_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class CtiCallerIdTest < ActiveSupport::TestCase diff --git a/test/unit/db_auto_increment_test.rb b/test/unit/db_auto_increment_test.rb index 4872b33ae..0f5edcc39 100644 --- a/test/unit/db_auto_increment_test.rb +++ b/test/unit/db_auto_increment_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class DbAutoIncrementTest < ActiveSupport::TestCase diff --git a/test/unit/email_address_test.rb b/test/unit/email_address_test.rb index 261cd033e..4a6ccf588 100644 --- a/test/unit/email_address_test.rb +++ b/test/unit/email_address_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class EmailAddressTest < ActiveSupport::TestCase diff --git a/test/unit/email_build_test.rb b/test/unit/email_build_test.rb index c293bcd98..cf6585e4d 100644 --- a/test/unit/email_build_test.rb +++ b/test/unit/email_build_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class EmailBuildTest < ActiveSupport::TestCase @@ -73,21 +73,19 @@ class EmailBuildTest < ActiveSupport::TestCase assert_equal(2, data[:attachments].length) # check attachments - if data[:attachments] - data[:attachments].each do |attachment| - if attachment[:filename] == 'message.html' - assert_nil(attachment[:preferences]['Content-ID']) - assert_equal(true, attachment[:preferences]['content-alternative']) - assert_equal('text/html', attachment[:preferences]['Mime-Type']) - assert_equal('UTF-8', attachment[:preferences]['Charset']) - elsif attachment[:filename] == 'somename.png' - assert_nil(attachment[:preferences]['Content-ID']) - assert_nil(attachment[:preferences]['content-alternative']) - assert_equal('image/png', attachment[:preferences]['Mime-Type']) - assert_equal('UTF-8', attachment[:preferences]['Charset']) - else - assert(false, "invalid attachment, should not be there, #{attachment.inspect}") - end + data[:attachments]&.each do |attachment| + if attachment[:filename] == 'message.html' + assert_nil(attachment[:preferences]['Content-ID']) + assert_equal(true, attachment[:preferences]['content-alternative']) + assert_equal('text/html', attachment[:preferences]['Mime-Type']) + assert_equal('UTF-8', attachment[:preferences]['Charset']) + elsif attachment[:filename] == 'somename.png' + assert_nil(attachment[:preferences]['Content-ID']) + assert_nil(attachment[:preferences]['content-alternative']) + assert_equal('image/png', attachment[:preferences]['Mime-Type']) + assert_equal('UTF-8', attachment[:preferences]['Charset']) + else + assert(false, "invalid attachment, should not be there, #{attachment.inspect}") end end end @@ -127,16 +125,14 @@ class EmailBuildTest < ActiveSupport::TestCase assert_equal(1, data[:attachments].length) # check attachments - if data[:attachments] - data[:attachments].each do |attachment| - if attachment[:filename] == 'somename.png' - assert_nil(attachment[:preferences]['Content-ID']) - assert_nil(attachment[:preferences]['content-alternative']) - assert_equal('image/png', attachment[:preferences]['Mime-Type']) - assert_equal('UTF-8', attachment[:preferences]['Charset']) - else - assert(false, "invalid attachment, should not be there, #{attachment.inspect}") - end + data[:attachments]&.each do |attachment| + if attachment[:filename] == 'somename.png' + assert_nil(attachment[:preferences]['Content-ID']) + assert_nil(attachment[:preferences]['content-alternative']) + assert_equal('image/png', attachment[:preferences]['Mime-Type']) + assert_equal('UTF-8', attachment[:preferences]['Charset']) + else + assert(false, "invalid attachment, should not be there, #{attachment.inspect}") end end end diff --git a/test/unit/email_parser_test.rb b/test/unit/email_parser_test.rb index 1bfa8f3f6..e0bd4808e 100644 --- a/test/unit/email_parser_test.rb +++ b/test/unit/email_parser_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 # rubocop:disable all require 'test_helper' diff --git a/test/unit/email_postmaster_test.rb b/test/unit/email_postmaster_test.rb index 3893ddab3..877c8b0b3 100644 --- a/test/unit/email_postmaster_test.rb +++ b/test/unit/email_postmaster_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 # rubocop:disable all require 'test_helper' diff --git a/test/unit/email_process_auto_response_test.rb b/test/unit/email_process_auto_response_test.rb index 1d81118f6..d37c1f1d7 100644 --- a/test/unit/email_process_auto_response_test.rb +++ b/test/unit/email_process_auto_response_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 +# rubocop:disable Lint/InterpolationCheck require 'test_helper' class EmailProcessAutoResponseTest < ActiveSupport::TestCase diff --git a/test/unit/email_process_bounce_delivery_permanent_failed_test.rb b/test/unit/email_process_bounce_delivery_permanent_failed_test.rb index f62210e55..75d5b62ce 100644 --- a/test/unit/email_process_bounce_delivery_permanent_failed_test.rb +++ b/test/unit/email_process_bounce_delivery_permanent_failed_test.rb @@ -1,10 +1,10 @@ -# encoding: utf-8 +# rubocop:disable Lint/InterpolationCheck require 'test_helper' class EmailProcessBounceDeliveryPermanentFailedTest < ActiveSupport::TestCase test 'process with bounce trigger email loop check - article based blocker' do - roles = Role.where(name: %w(Customer)) + roles = Role.where(name: %w[Customer]) customer1 = User.create_or_update( login: 'ticket-bounce-trigger1@example.com', firstname: 'Notification', @@ -111,7 +111,7 @@ class EmailProcessBounceDeliveryPermanentFailedTest < ActiveSupport::TestCase end test 'process with bounce trigger email loop check - bounce based blocker' do - roles = Role.where(name: %w(Customer)) + roles = Role.where(name: %w[Customer]) customer2 = User.create_or_update( login: 'ticket-bounce-trigger2@example.com', firstname: 'Notification', diff --git a/test/unit/email_process_bounce_follow_test.rb b/test/unit/email_process_bounce_follow_test.rb index 242c95845..0deed2d91 100644 --- a/test/unit/email_process_bounce_follow_test.rb +++ b/test/unit/email_process_bounce_follow_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 +# rubocop:disable Lint/InterpolationCheck require 'test_helper' class EmailProcessBounceFollowUpTest < ActiveSupport::TestCase @@ -38,7 +38,7 @@ class EmailProcessBounceFollowUpTest < ActiveSupport::TestCase end test 'process with bounce trigger email loop check - article based blocker' do - roles = Role.where(name: %w(Customer)) + roles = Role.where(name: %w[Customer]) customer1 = User.create_or_update( login: 'ticket-bounce-trigger1@example.com', firstname: 'Notification', @@ -145,7 +145,7 @@ class EmailProcessBounceFollowUpTest < ActiveSupport::TestCase end test 'process with bounce trigger email loop check - bounce based blocker' do - roles = Role.where(name: %w(Customer)) + roles = Role.where(name: %w[Customer]) customer2 = User.create_or_update( login: 'ticket-bounce-trigger2@example.com', firstname: 'Notification', diff --git a/test/unit/email_process_follow_up_possible_test.rb b/test/unit/email_process_follow_up_possible_test.rb index 32529ceaf..46a81cf8f 100644 --- a/test/unit/email_process_follow_up_possible_test.rb +++ b/test/unit/email_process_follow_up_possible_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class EmailProcessFollowUpPossibleTest < ActiveSupport::TestCase diff --git a/test/unit/email_process_follow_up_test.rb b/test/unit/email_process_follow_up_test.rb index ccbc5c291..59c1d0e08 100644 --- a/test/unit/email_process_follow_up_test.rb +++ b/test/unit/email_process_follow_up_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class EmailProcessFollowUpTest < ActiveSupport::TestCase @@ -88,7 +88,7 @@ References: <20150830145601.30. no reference " setting_orig = Setting.get('postmaster_follow_up_search_in') - Setting.set('postmaster_follow_up_search_in', %w(body attachment references)) + Setting.set('postmaster_follow_up_search_in', %w[body attachment references]) travel 1.second ticket_p, article_p, user_p = Channel::EmailParser.new.process({}, email_raw_string_subject) @@ -251,7 +251,7 @@ Some Text" test 'process with follow up check with two external reference headers' do setting_orig = Setting.get('postmaster_follow_up_search_in') - Setting.set('postmaster_follow_up_search_in', %w(body attachment references)) + Setting.set('postmaster_follow_up_search_in', %w[body attachment references]) data1 = "From: me@example.com To: z@example.com diff --git a/test/unit/email_process_identify_sender_max_test.rb b/test/unit/email_process_identify_sender_max_test.rb index 81d0d316b..0a0efecc3 100644 --- a/test/unit/email_process_identify_sender_max_test.rb +++ b/test/unit/email_process_identify_sender_max_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class EmailProcessIdentifySenderMax < ActiveSupport::TestCase diff --git a/test/unit/email_process_out_of_office_test.rb b/test/unit/email_process_out_of_office_test.rb index 10f529e0c..2025a12c1 100644 --- a/test/unit/email_process_out_of_office_test.rb +++ b/test/unit/email_process_out_of_office_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class EmailProcessOutOfOfficeTest < ActiveSupport::TestCase diff --git a/test/unit/email_process_reply_to_test.rb b/test/unit/email_process_reply_to_test.rb index dbef68207..d0db22d1a 100644 --- a/test/unit/email_process_reply_to_test.rb +++ b/test/unit/email_process_reply_to_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class EmailProcessReplyToTest < ActiveSupport::TestCase diff --git a/test/unit/email_process_sender_is_system_address_or_agent_test.rb b/test/unit/email_process_sender_is_system_address_or_agent_test.rb index bd0b7093b..d1e7265c8 100644 --- a/test/unit/email_process_sender_is_system_address_or_agent_test.rb +++ b/test/unit/email_process_sender_is_system_address_or_agent_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class EmailProcessSenderIsSystemAddressOrAgent < ActiveSupport::TestCase diff --git a/test/unit/email_process_sender_name_update_if_needed.rb b/test/unit/email_process_sender_name_update_if_needed.rb index 553adf421..6c979f315 100644 --- a/test/unit/email_process_sender_name_update_if_needed.rb +++ b/test/unit/email_process_sender_name_update_if_needed.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class EmailProcessSenderNameUpdateIfNeeded < ActiveSupport::TestCase diff --git a/test/unit/email_process_state_open_set.rb b/test/unit/email_process_state_open_set.rb index 6ae4bf578..0347e14ca 100644 --- a/test/unit/email_process_state_open_set.rb +++ b/test/unit/email_process_state_open_set.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class EmailProcessStateOpenSet < ActiveSupport::TestCase diff --git a/test/unit/email_process_test.rb b/test/unit/email_process_test.rb index 3df6d1844..b945e0737 100644 --- a/test/unit/email_process_test.rb +++ b/test/unit/email_process_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 # rubocop:disable all require 'test_helper' diff --git a/test/unit/email_regex_test.rb b/test/unit/email_regex_test.rb index 0052fa06f..88832ef76 100644 --- a/test/unit/email_regex_test.rb +++ b/test/unit/email_regex_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class EmailRegexTest < ActiveSupport::TestCase diff --git a/test/unit/email_signatur_detection_test.rb b/test/unit/email_signatur_detection_test.rb index 8ad183d1d..37510921a 100644 --- a/test/unit/email_signatur_detection_test.rb +++ b/test/unit/email_signatur_detection_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class EmailSignaturDetectionTest < ActiveSupport::TestCase @@ -14,7 +14,7 @@ class EmailSignaturDetectionTest < ActiveSupport::TestCase fixture_messages = [] fixture_files.each do |filepath, value| - value[:content] = File.new("#{Rails.root}/test/fixtures/#{filepath}", 'r').read + value[:content] = File.new( Rails.root.join('test', 'fixtures', filepath), 'r').read fixture_messages.push value end @@ -22,7 +22,7 @@ class EmailSignaturDetectionTest < ActiveSupport::TestCase expected_signature = "\nMit freundlichen Grüßen\n\nBob Smith\nBerechtigungen und dez. Department\n________________________________\n\nMusik AG\nBerechtigungen und dez. Department (ITPBM)\nKastanien 2" assert_equal(expected_signature, signature) - fixture_files.each do |_filepath, value| + fixture_files.each_value do |value| assert_equal(value[:line], SignatureDetection.find_signature_line(signature, value[:content], value[:content_type])) end end @@ -37,7 +37,7 @@ class EmailSignaturDetectionTest < ActiveSupport::TestCase fixture_messages = [] fixture_files.each do |filepath, value| - value[:content] = File.new("#{Rails.root}/test/fixtures/#{filepath}", 'r').read + value[:content] = File.new( Rails.root.join('test', 'fixtures', filepath), 'r').read fixture_messages.push value end @@ -45,14 +45,14 @@ class EmailSignaturDetectionTest < ActiveSupport::TestCase expected_signature = "\nFreundliche Grüße\n\nGünter Lässig\nLokale Daten\n\nMusic GmbH\nBaustraße 123, 12345 Max City\nTelefon 0123 5432114\nTelefax 0123 5432139" assert_equal(expected_signature, signature) - fixture_files.each do |_filepath, value| + fixture_files.each_value do |value| assert_equal(value[:line], SignatureDetection.find_signature_line(signature, value[:content], value[:content_type])) end end test 'test case 3 - just tests' do signature = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nBob Smith\nABC Organisation\n\nEXAMPLE IT-Service GmbH\nDorten 5 F&E\n12345 Da / Germany\nPhone: +49 (0) 1234 567 890 / +49 (0) 1234 567 891\nFax:     +49 (0) 1234 567 892" - message = File.new("#{Rails.root}/test/fixtures/email_signature_detection/example1.html", 'r').read + message = File.new(Rails.root.join('test', 'fixtures', 'email_signature_detection', 'example1.html'), 'r').read signature_line = SignatureDetection.find_signature_line(signature, message, 'text/html') assert_equal(11, signature_line) end @@ -67,7 +67,7 @@ class EmailSignaturDetectionTest < ActiveSupport::TestCase fixture_messages = [] fixture_files.each do |filepath, value| - value[:content] = File.new("#{Rails.root}/test/fixtures/#{filepath}", 'r').read + value[:content] = File.new( Rails.root.join('test', 'fixtures', filepath), 'r').read fixture_messages.push value end @@ -84,7 +84,7 @@ class EmailSignaturDetectionTest < ActiveSupport::TestCase raw_email_header = "From: Bob.Smith@music.com\nTo: test@zammad.org\nSubject: test\n\n" # process email I - file = File.open("#{Rails.root}/test/fixtures/email_signature_detection/client_a_1.txt", 'rb') + file = File.open(Rails.root.join('test', 'fixtures', 'email_signature_detection', 'client_a_1.txt'), 'rb') raw_email = raw_email_header + file.read ticket1, article1, user1, mail = Channel::EmailParser.new.process({}, raw_email) assert(ticket1) @@ -92,7 +92,7 @@ class EmailSignaturDetectionTest < ActiveSupport::TestCase Scheduler.worker(true) # process email II - file = File.open("#{Rails.root}/test/fixtures/email_signature_detection/client_a_2.txt", 'rb') + file = File.open(Rails.root.join('test', 'fixtures', 'email_signature_detection', 'client_a_2.txt'), 'rb') raw_email = raw_email_header + file.read ticket2, article2, user2, mail = Channel::EmailParser.new.process({}, raw_email) assert(ticket2) @@ -104,7 +104,7 @@ class EmailSignaturDetectionTest < ActiveSupport::TestCase assert(user2.preferences[:signature_detection]) # process email III - file = File.open("#{Rails.root}/test/fixtures/email_signature_detection/client_a_3.txt", 'rb') + file = File.open(Rails.root.join('test', 'fixtures', 'email_signature_detection', 'client_a_3.txt'), 'rb') raw_email = raw_email_header + file.read ticket3, article3, user3, mail = Channel::EmailParser.new.process({}, raw_email) assert(ticket3) diff --git a/test/unit/history_test.rb b/test/unit/history_test.rb index afb276786..51c06e078 100644 --- a/test/unit/history_test.rb +++ b/test/unit/history_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class HistoryTest < ActiveSupport::TestCase diff --git a/test/unit/html_sanitizer_test.rb b/test/unit/html_sanitizer_test.rb index 77d03f4c3..56d81360a 100644 --- a/test/unit/html_sanitizer_test.rb +++ b/test/unit/html_sanitizer_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class HtmlSanitizerTest < ActiveSupport::TestCase diff --git a/test/unit/integration_icinga_test.rb b/test/unit/integration_icinga_test.rb index 2106bd6c4..4bf1ce357 100644 --- a/test/unit/integration_icinga_test.rb +++ b/test/unit/integration_icinga_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class IntegrationIcingaTest < ActiveSupport::TestCase diff --git a/test/unit/integration_monit_test.rb b/test/unit/integration_monit_test.rb index fafe72109..a481cc77d 100644 --- a/test/unit/integration_monit_test.rb +++ b/test/unit/integration_monit_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class IntegrationMonitTest < ActiveSupport::TestCase diff --git a/test/unit/integration_nagios_test.rb b/test/unit/integration_nagios_test.rb index 4e33aa405..9248be00e 100644 --- a/test/unit/integration_nagios_test.rb +++ b/test/unit/integration_nagios_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class IntegrationNagiosTest < ActiveSupport::TestCase diff --git a/test/unit/job_test.rb b/test/unit/job_test.rb index d92edfe59..9000e312e 100644 --- a/test/unit/job_test.rb +++ b/test/unit/job_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class JobTest < ActiveSupport::TestCase diff --git a/test/unit/karma_test.rb b/test/unit/karma_test.rb index c53bd09ed..b2659a206 100644 --- a/test/unit/karma_test.rb +++ b/test/unit/karma_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class KarmaTest < ActiveSupport::TestCase diff --git a/test/unit/migration_ror_42_to50_store_test.rb b/test/unit/migration_ror_42_to50_store_test.rb index 56778693b..09e1c273b 100644 --- a/test/unit/migration_ror_42_to50_store_test.rb +++ b/test/unit/migration_ror_42_to50_store_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + # Rails 5.0 has changed to only store and read ActiveSupport::HashWithIndifferentAccess from stores # we extended lib/core_ext/active_record/store/indifferent_coder.rb to read also ActionController::Parameters # and convert them to ActiveSupport::HashWithIndifferentAccess for migration in db/migrate/20170910000001_fixed_store_upgrade_45.rb. diff --git a/test/unit/model_test.rb b/test/unit/model_test.rb index b7c0d7777..9c5431539 100644 --- a/test/unit/model_test.rb +++ b/test/unit/model_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class ModelTest < ActiveSupport::TestCase @@ -65,7 +65,7 @@ class ModelTest < ActiveSupport::TestCase # create base groups = Group.where(name: 'Users') - roles = Role.where(name: %w(Agent Admin)) + roles = Role.where(name: %w[Agent Admin]) agent1 = User.create_or_update( login: 'model-agent1@example.com', firstname: 'Model', @@ -179,7 +179,7 @@ class ModelTest < ActiveSupport::TestCase assert(!references1['Organization']) assert(!references1['Group']) assert(!references1['UserGroup']) - assert(references1.empty?) + assert(references1.blank?) references_total1 = Models.references_total('User', agent1.id) assert_equal(references_total1, 0) @@ -211,7 +211,7 @@ class ModelTest < ActiveSupport::TestCase # verify agent2 references2 = Models.references('Organization', organization2.id) - assert(references2.empty?) + assert(references2.blank?) references_total2 = Models.references_total('Organization', organization2.id) assert_equal(references_total2, 0) @@ -221,7 +221,7 @@ class ModelTest < ActiveSupport::TestCase # verify agent1 references1 = Models.references('Organization', organization1.id) - assert(references1.empty?) + assert(references1.blank?) references_total1 = Models.references_total('Organization', organization1.id) assert_equal(references_total1, 0) diff --git a/test/unit/notification_factory_mailer_template_test.rb b/test/unit/notification_factory_mailer_template_test.rb index 2dc38a9e8..2a3e4b36b 100644 --- a/test/unit/notification_factory_mailer_template_test.rb +++ b/test/unit/notification_factory_mailer_template_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class NotificationFactoryMailerTemplateTest < ActiveSupport::TestCase @@ -158,8 +158,8 @@ class NotificationFactoryMailerTemplateTest < ActiveSupport::TestCase created_by_id: 1, ) changes = { - state: %w(aaa bbb), - group: %w(xxx yyy), + state: %w[aaa bbb], + group: %w[xxx yyy], } result = NotificationFactory::Mailer.template( template: 'ticket_update', diff --git a/test/unit/notification_factory_mailer_test.rb b/test/unit/notification_factory_mailer_test.rb index 22a0d3e7c..770911693 100644 --- a/test/unit/notification_factory_mailer_test.rb +++ b/test/unit/notification_factory_mailer_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class NotificationFactoryMailerTest < ActiveSupport::TestCase diff --git a/test/unit/notification_factory_renderer_test.rb b/test/unit/notification_factory_renderer_test.rb index d3bcffed1..74e33362c 100644 --- a/test/unit/notification_factory_renderer_test.rb +++ b/test/unit/notification_factory_renderer_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 +# rubocop:disable Lint/InterpolationCheck require 'test_helper' class NotificationFactoryRendererTest < ActiveSupport::TestCase diff --git a/test/unit/notification_factory_slack_template_test.rb b/test/unit/notification_factory_slack_template_test.rb index cb3b349f0..319198492 100644 --- a/test/unit/notification_factory_slack_template_test.rb +++ b/test/unit/notification_factory_slack_template_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class NotificationFactorySlackTemplateTest < ActiveSupport::TestCase @@ -98,8 +98,8 @@ class NotificationFactorySlackTemplateTest < ActiveSupport::TestCase created_by_id: 1, ) changes = { - state: %w(aaa bbb), - group: %w(xxx yyy), + state: %w[aaa bbb], + group: %w[xxx yyy], } result = NotificationFactory::Slack.template( template: 'ticket_update', diff --git a/test/unit/notification_factory_template_test.rb b/test/unit/notification_factory_template_test.rb index baee7c7ea..604ed0e62 100644 --- a/test/unit/notification_factory_template_test.rb +++ b/test/unit/notification_factory_template_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 +# rubocop:disable Lint/InterpolationCheck require 'test_helper' class NotificationFactoryTemplateTest < ActiveSupport::TestCase diff --git a/test/unit/object_cache_test.rb b/test/unit/object_cache_test.rb index 4ab4ee840..086210c9a 100644 --- a/test/unit/object_cache_test.rb +++ b/test/unit/object_cache_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class ObjectCacheTest < ActiveSupport::TestCase @@ -9,7 +9,7 @@ class ObjectCacheTest < ActiveSupport::TestCase created_by_id: 1, ) - roles = Role.where( name: %w(Agent Admin) ) + roles = Role.where( name: %w[Agent Admin] ) groups = Group.all user1 = User.create_or_update( login: 'object_cache1@example.org', @@ -36,7 +36,7 @@ class ObjectCacheTest < ActiveSupport::TestCase end test 'user cache' do - roles = Role.where(name: %w(Agent Admin)) + roles = Role.where(name: %w[Agent Admin]) groups = Group.all.order(:id) # be sure that minimum one admin is available 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 f79557371..db2b02d04 100644 --- a/test/unit/object_create_update_with_ref_name_test.rb +++ b/test/unit/object_create_update_with_ref_name_test.rb @@ -1,9 +1,9 @@ -# encoding: utf-8 + require 'test_helper' class ObjectCreateUpdateWithRefNameTest < ActiveSupport::TestCase test 'organization' do - roles = Role.where(name: %w(Agent Admin)) + roles = Role.where(name: %w[Agent Admin]) groups = Group.all user1 = User.create_or_update( login: 'object_ref_name1@example.org', @@ -90,7 +90,7 @@ class ObjectCreateUpdateWithRefNameTest < ActiveSupport::TestCase organization: 'some org update_with_ref user', updated_by_id: 1, created_by_id: 1, - roles: %w(Agent Admin), + roles: %w[Agent Admin], groups: ['Users'], ) user2 = User.create_or_update_with_ref( @@ -137,7 +137,7 @@ class ObjectCreateUpdateWithRefNameTest < ActiveSupport::TestCase organization_id: nil, updated_by_id: 1, created_by_id: 1, - roles: %w(Agent Admin), + roles: %w[Agent Admin], groups: [], ) user2 = User.create_or_update_with_ref( diff --git a/test/unit/object_type_lookup_test.rb b/test/unit/object_type_lookup_test.rb index d4643d471..f37a9c24a 100644 --- a/test/unit/object_type_lookup_test.rb +++ b/test/unit/object_type_lookup_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class ObjectTypeLookupTest < ActiveSupport::TestCase diff --git a/test/unit/online_notifiaction_test.rb b/test/unit/online_notifiaction_test.rb index a50354f11..07e669f9d 100644 --- a/test/unit/online_notifiaction_test.rb +++ b/test/unit/online_notifiaction_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class OnlineNotificationTest < ActiveSupport::TestCase @@ -347,11 +347,11 @@ class OnlineNotificationTest < ActiveSupport::TestCase Scheduler.worker(true) notifications = OnlineNotification.list_by_object('Ticket', tickets[0].id) - assert(!notifications.empty?, 'should have notifications') + assert(notifications.present?, 'should have notifications') assert(OnlineNotification.all_seen?('Ticket', tickets[0].id), 'still not seen notifications for merged ticket available') notifications = OnlineNotification.list_by_object('Ticket', tickets[1].id) - assert(!notifications.empty?, 'should have notifications') + assert(notifications.present?, 'should have notifications') assert(!OnlineNotification.all_seen?('Ticket', tickets[1].id), 'no notifications for master ticket available') # delete tickets @@ -364,7 +364,7 @@ class OnlineNotificationTest < ActiveSupport::TestCase # check if notifications for ticket still exist Scheduler.worker(true) notifications = OnlineNotification.list_by_object('Ticket', ticket_id) - assert(notifications.empty?, 'still notifications for destroyed ticket available') + assert(notifications.blank?, 'still notifications for destroyed ticket available') end end diff --git a/test/unit/organization_domain_based_assignment_test.rb b/test/unit/organization_domain_based_assignment_test.rb index bfc2cff9a..4b2e04523 100644 --- a/test/unit/organization_domain_based_assignment_test.rb +++ b/test/unit/organization_domain_based_assignment_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class OrganizationDomainBasedAssignmentTest < ActiveSupport::TestCase diff --git a/test/unit/organization_ref_object_touch_test.rb b/test/unit/organization_ref_object_touch_test.rb index f6095fd98..f327bee06 100644 --- a/test/unit/organization_ref_object_touch_test.rb +++ b/test/unit/organization_ref_object_touch_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class OrganizationRefObjectTouchTest < ActiveSupport::TestCase diff --git a/test/unit/overview_test.rb b/test/unit/overview_test.rb index 145b64951..a70b2d381 100644 --- a/test/unit/overview_test.rb +++ b/test/unit/overview_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class OverviewTest < ActiveSupport::TestCase @@ -18,9 +18,9 @@ class OverviewTest < ActiveSupport::TestCase direction: 'DESC', }, view: { - d: %w(title customer state created_at), - s: %w(number title customer state created_at), - m: %w(number title customer state created_at), + d: %w[title customer state created_at], + s: %w[number title customer state created_at], + m: %w[number title customer state created_at], view_mode_default: 's', }, ) @@ -40,9 +40,9 @@ class OverviewTest < ActiveSupport::TestCase direction: 'DESC', }, view: { - d: %w(title customer state created_at), - s: %w(number title customer state created_at), - m: %w(number title customer state created_at), + d: %w[title customer state created_at], + s: %w[number title customer state created_at], + m: %w[number title customer state created_at], view_mode_default: 's', }, ) @@ -62,9 +62,9 @@ class OverviewTest < ActiveSupport::TestCase direction: 'DESC', }, view: { - d: %w(title customer state created_at), - s: %w(number title customer state created_at), - m: %w(number title customer state created_at), + d: %w[title customer state created_at], + s: %w[number title customer state created_at], + m: %w[number title customer state created_at], view_mode_default: 's', }, ) @@ -84,9 +84,9 @@ class OverviewTest < ActiveSupport::TestCase direction: 'DESC', }, view: { - d: %w(title customer state created_at), - s: %w(number title customer state created_at), - m: %w(number title customer state created_at), + d: %w[title customer state created_at], + s: %w[number title customer state created_at], + m: %w[number title customer state created_at], view_mode_default: 's', }, ) @@ -106,9 +106,9 @@ class OverviewTest < ActiveSupport::TestCase direction: 'DESC', }, view: { - d: %w(title customer state created_at), - s: %w(number title customer state created_at), - m: %w(number title customer state created_at), + d: %w[title customer state created_at], + s: %w[number title customer state created_at], + m: %w[number title customer state created_at], view_mode_default: 's', }, ) @@ -126,9 +126,9 @@ class OverviewTest < ActiveSupport::TestCase direction: 'DESC', }, view: { - d: %w(title customer state created_at), - s: %w(number title customer state created_at), - m: %w(number title customer state created_at), + d: %w[title customer state created_at], + s: %w[number title customer state created_at], + m: %w[number title customer state created_at], view_mode_default: 's', }, ) @@ -150,9 +150,9 @@ class OverviewTest < ActiveSupport::TestCase direction: 'DESC', }, view: { - d: %w(title customer state created_at), - s: %w(number title customer state created_at), - m: %w(number title customer state created_at), + d: %w[title customer state created_at], + s: %w[number title customer state created_at], + m: %w[number title customer state created_at], view_mode_default: 's', }, ) @@ -172,9 +172,9 @@ class OverviewTest < ActiveSupport::TestCase direction: 'DESC', }, view: { - d: %w(title customer state created_at), - s: %w(number title customer state created_at), - m: %w(number title customer state created_at), + d: %w[title customer state created_at], + s: %w[number title customer state created_at], + m: %w[number title customer state created_at], view_mode_default: 's', }, ) @@ -195,9 +195,9 @@ class OverviewTest < ActiveSupport::TestCase direction: 'DESC', }, view: { - d: %w(title customer state created_at), - s: %w(number title customer state created_at), - m: %w(number title customer state created_at), + d: %w[title customer state created_at], + s: %w[number title customer state created_at], + m: %w[number title customer state created_at], view_mode_default: 's', }, ) diff --git a/test/unit/permission_test.rb b/test/unit/permission_test.rb index 10d30cf77..b8ccc0268 100644 --- a/test/unit/permission_test.rb +++ b/test/unit/permission_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class PermissionTest < ActiveSupport::TestCase diff --git a/test/unit/recent_view_test.rb b/test/unit/recent_view_test.rb index 6604b87ce..aabd1fe5f 100644 --- a/test/unit/recent_view_test.rb +++ b/test/unit/recent_view_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class RecentViewTest < ActiveSupport::TestCase diff --git a/test/unit/role_test.rb b/test/unit/role_test.rb index 81bb767ef..7c03368d1 100644 --- a/test/unit/role_test.rb +++ b/test/unit/role_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class RoleTest < ActiveSupport::TestCase diff --git a/test/unit/role_validate_agent_limit_test.rb b/test/unit/role_validate_agent_limit_test.rb index b10d8b523..ded98ea6a 100644 --- a/test/unit/role_validate_agent_limit_test.rb +++ b/test/unit/role_validate_agent_limit_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class RoleValidateAgentLimit < ActiveSupport::TestCase @@ -101,7 +101,7 @@ class RoleValidateAgentLimit < ActiveSupport::TestCase active: true, ) - user1.roles = Role.where(name: %w(Admin Agent)) + user1.roles = Role.where(name: %w[Admin Agent]) user1.role_ids = [Role.find_by(name: 'Agent').id] diff --git a/test/unit/session_basic_test.rb b/test/unit/session_basic_test.rb index b3a029774..072cf492d 100644 --- a/test/unit/session_basic_test.rb +++ b/test/unit/session_basic_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class SessionBasicTest < ActiveSupport::TestCase @@ -50,7 +50,7 @@ class SessionBasicTest < ActiveSupport::TestCase test 'c session create / update' do # create users - roles = Role.where(name: %w(Agent)) + roles = Role.where(name: %w[Agent]) groups = Group.all agent1 = User.create_or_update( @@ -124,10 +124,10 @@ class SessionBasicTest < ActiveSupport::TestCase # get whole collections result1 = collection_client1.push - assert(!result1.empty?, 'check collections') + assert(result1.present?, 'check collections') sleep 0.6 result2 = collection_client2.push - assert(!result2.empty?, 'check collections') + assert(result2.present?, 'check collections') assert_equal(result1, result2, 'check collections') # next check should be empty @@ -145,10 +145,10 @@ class SessionBasicTest < ActiveSupport::TestCase # get whole collections result1 = collection_client1.push - assert(!result1.empty?, 'check collections - after touch') + assert(result1.present?, 'check collections - after touch') result2 = collection_client2.push - assert(!result2.empty?, 'check collections - after touch') + assert(result2.present?, 'check collections - after touch') assert_equal(result1, result2, 'check collections') # check again after touch @@ -168,9 +168,9 @@ class SessionBasicTest < ActiveSupport::TestCase # get whole collections result1 = collection_client1.push - assert(!result1.empty?, 'check collections - after create') + assert(result1.present?, 'check collections - after create') result2 = collection_client2.push - assert(!result2.empty?, 'check collections - after create') + assert(result2.present?, 'check collections - after create') assert_equal(result1, result2, 'check collections') # check again after create @@ -186,9 +186,9 @@ class SessionBasicTest < ActiveSupport::TestCase # get whole collections result1 = collection_client1.push - assert(!result1.empty?, 'check collections - after destroy') + assert(result1.present?, 'check collections - after destroy') result2 = collection_client2.push - assert(!result2.empty?, 'check collections - after destroy') + assert(result2.present?, 'check collections - after destroy') assert_equal(result1, result2, 'check collections') # check again after destroy @@ -203,7 +203,7 @@ class SessionBasicTest < ActiveSupport::TestCase test 'c activity stream' do # create users - roles = Role.where(name: %w(Agent Admin)) + roles = Role.where(name: %w[Agent Admin]) groups = Group.all agent1 = User.create_or_update( @@ -265,7 +265,7 @@ class SessionBasicTest < ActiveSupport::TestCase test 'c ticket_create' do # create users - roles = Role.where(name: %w(Agent Admin)) + roles = Role.where(name: %w[Agent Admin]) groups = Group.all agent1 = User.create_or_update( diff --git a/test/unit/session_basic_ticket_test.rb b/test/unit/session_basic_ticket_test.rb index 2defadf8e..20706036e 100644 --- a/test/unit/session_basic_ticket_test.rb +++ b/test/unit/session_basic_ticket_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class SessionBasicTicketTest < ActiveSupport::TestCase @@ -30,7 +30,7 @@ class SessionBasicTicketTest < ActiveSupport::TestCase groups: groups, ) Overview.destroy_all - load "#{Rails.root}/db/seeds/overviews.rb" + load Rails.root.join('db', 'seeds', 'overviews.rb') end test 'asset needed' do diff --git a/test/unit/session_collections_test.rb b/test/unit/session_collections_test.rb index 0af97e5d1..d58b01918 100644 --- a/test/unit/session_collections_test.rb +++ b/test/unit/session_collections_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class SessionCollectionsTest < ActiveSupport::TestCase @@ -8,7 +8,7 @@ class SessionCollectionsTest < ActiveSupport::TestCase UserInfo.current_user_id = 1 # create users - roles = Role.where(name: %w(Agent Admin)) + roles = Role.where(name: %w[Agent Admin]) groups = Group.all agent1 = User.create_or_update( @@ -94,12 +94,12 @@ class SessionCollectionsTest < ActiveSupport::TestCase # next check should be empty result1 = collection_client1.push - assert(result1.empty?, 'check collections - recall') + assert(result1.blank?, 'check collections - recall') travel 0.4.seconds result2 = collection_client2.push - assert(result2.empty?, 'check collections - recall') + assert(result2.blank?, 'check collections - recall') result3 = collection_client3.push - assert(result3.empty?, 'check collections - recall') + assert(result3.blank?, 'check collections - recall') # change collection group = Group.first @@ -123,11 +123,11 @@ class SessionCollectionsTest < ActiveSupport::TestCase # next check should be empty travel 0.5.seconds result1 = collection_client1.push - assert(result1.empty?, 'check collections - recall') + assert(result1.blank?, 'check collections - recall') result2 = collection_client2.push - assert(result2.empty?, 'check collections - recall') + assert(result2.blank?, 'check collections - recall') result3 = collection_client3.push - assert(result3.empty?, 'check collections - recall') + assert(result3.blank?, 'check collections - recall') travel 10.seconds Sessions.destroy_idle_sessions(3) @@ -171,7 +171,7 @@ class SessionCollectionsTest < ActiveSupport::TestCase end test 'b assets' do - roles = Role.where(name: %w(Agent Admin)) + roles = Role.where(name: %w[Agent Admin]) groups = Group.all.order(id: :asc) UserInfo.current_user_id = 2 diff --git a/test/unit/session_enhanced_test.rb b/test/unit/session_enhanced_test.rb index 680933deb..2443adeba 100644 --- a/test/unit/session_enhanced_test.rb +++ b/test/unit/session_enhanced_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class SessionEnhancedTest < ActiveSupport::TestCase @@ -331,13 +331,13 @@ class SessionEnhancedTest < ActiveSupport::TestCase #puts "rc: " next if !message['data'] - message['data'].each do |key, _value| + message['data'].each_key do |key| #puts "rc: #{key}" collections_result[key] = true end end #puts "c: #{collections_result.inspect}" - collections_orig.each do |key, _value| + collections_orig.each_key do |key| if collections_orig[key].nil? assert_nil(collections_result[key], "collection message for #{key} #{type}-check (client_id #{client_id})") else diff --git a/test/unit/stats_ticket_waiting_time_test.rb b/test/unit/stats_ticket_waiting_time_test.rb index bd4229d0c..a1842090c 100644 --- a/test/unit/stats_ticket_waiting_time_test.rb +++ b/test/unit/stats_ticket_waiting_time_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' require 'stats/ticket_waiting_time' diff --git a/test/unit/store_test.rb b/test/unit/store_test.rb index 134c6ae76..bd1732fce 100644 --- a/test/unit/store_test.rb +++ b/test/unit/store_test.rb @@ -1,11 +1,11 @@ -# encoding: utf-8 + require 'test_helper' class StoreTest < ActiveSupport::TestCase test 'store fs - get_location' do sha = 'ed7002b439e9ac845f22357d822bac1444730fbdb6016d3ec9432297b9ec9f73' location = Store::Provider::File.get_location(sha) - assert_equal("#{Rails.root}/storage/fs/ed70/02b4/39e9a/c845f/22357d8/22bac14/44730fbdb6016d3ec9432297b9ec9f73", location) + assert_equal(Rails.root.join('storage', 'fs', 'ed70', '02b4', '39e9a', 'c845f', '22357d8', '22bac14', '44730fbdb6016d3ec9432297b9ec9f73').to_s, location) end test 'store fs - empty dir remove' do @@ -19,13 +19,13 @@ class StoreTest < ActiveSupport::TestCase result = Store::Provider::File.delete(sha) exists = File.exist?(location) assert(!exists) - exists = File.exist?("#{Rails.root}/storage/fs/ed70/02b4") + exists = File.exist?(Rails.root.join('storage', 'fs', 'ed70', '02b4')) assert(!exists) - exists = File.exist?("#{Rails.root}/storage/fs/ed70/") + exists = File.exist?(Rails.root.join('storage', 'fs', 'ed70')) assert(!exists) - exists = File.exist?("#{Rails.root}/storage/fs/") + exists = File.exist?(Rails.root.join('storage', 'fs')) assert(exists) - exists = File.exist?("#{Rails.root}/storage/") + exists = File.exist?(Rails.root.join('storage')) assert(exists) end diff --git a/test/unit/tag_test.rb b/test/unit/tag_test.rb index c54ce4416..a1d1809d3 100644 --- a/test/unit/tag_test.rb +++ b/test/unit/tag_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TagTest < ActiveSupport::TestCase diff --git a/test/unit/ticket_article_communicate_test.rb b/test/unit/ticket_article_communicate_test.rb index 533cbe657..a4d0618f0 100644 --- a/test/unit/ticket_article_communicate_test.rb +++ b/test/unit/ticket_article_communicate_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketArticleCommunicateTest < ActiveSupport::TestCase diff --git a/test/unit/ticket_article_dos_test.rb b/test/unit/ticket_article_dos_test.rb index 1891bcb5b..f22ba38ec 100644 --- a/test/unit/ticket_article_dos_test.rb +++ b/test/unit/ticket_article_dos_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketArticleDos < ActiveSupport::TestCase diff --git a/test/unit/ticket_article_store_empty.rb b/test/unit/ticket_article_store_empty.rb index ad3cd5049..913ef2798 100644 --- a/test/unit/ticket_article_store_empty.rb +++ b/test/unit/ticket_article_store_empty.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketArticleStoreEmpty < ActiveSupport::TestCase diff --git a/test/unit/ticket_article_time_accouting_test.rb b/test/unit/ticket_article_time_accouting_test.rb index 4bb650c7c..54adc448c 100644 --- a/test/unit/ticket_article_time_accouting_test.rb +++ b/test/unit/ticket_article_time_accouting_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketArticleTimeAccoutingTest < ActiveSupport::TestCase diff --git a/test/unit/ticket_article_twitter_test.rb b/test/unit/ticket_article_twitter_test.rb index a4f743a11..d76f9bf11 100644 --- a/test/unit/ticket_article_twitter_test.rb +++ b/test/unit/ticket_article_twitter_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketArticleTwitter < ActiveSupport::TestCase diff --git a/test/unit/ticket_customer_organization_update_test.rb b/test/unit/ticket_customer_organization_update_test.rb index 8327048e9..7d7914d60 100644 --- a/test/unit/ticket_customer_organization_update_test.rb +++ b/test/unit/ticket_customer_organization_update_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketCustomerOrganizationUpdateTest < ActiveSupport::TestCase diff --git a/test/unit/ticket_escalation_test.rb b/test/unit/ticket_escalation_test.rb index a79be51ca..a963874f0 100644 --- a/test/unit/ticket_escalation_test.rb +++ b/test/unit/ticket_escalation_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketEscalationTest < ActiveSupport::TestCase diff --git a/test/unit/ticket_last_owner_update_test.rb b/test/unit/ticket_last_owner_update_test.rb index 80ec7478d..e4dc85bb6 100644 --- a/test/unit/ticket_last_owner_update_test.rb +++ b/test/unit/ticket_last_owner_update_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketLastOwnerUpdateTest < ActiveSupport::TestCase diff --git a/test/unit/ticket_notification_test.rb b/test/unit/ticket_notification_test.rb index 0288f41dd..dee8ec856 100644 --- a/test/unit/ticket_notification_test.rb +++ b/test/unit/ticket_notification_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketNotificationTest < ActiveSupport::TestCase @@ -25,6 +25,7 @@ class TicketNotificationTest < ActiveSupport::TestCase }, perform: { 'notification.email' => { + # rubocop:disable Lint/InterpolationCheck 'body' => '

Your request (Ticket##{ticket.number}) has been received and will be reviewed by our support staff.


To provide additional information, please reply to this email or click on the following link: @@ -34,6 +35,7 @@ class TicketNotificationTest < ActiveSupport::TestCase

Zammad, your customer support system

', 'recipient' => 'ticket_customer', 'subject' => 'Thanks for your inquiry (#{ticket.title})', + # rubocop:enable Lint/InterpolationCheck }, }, disable_notification: true, diff --git a/test/unit/ticket_null_byte_test.rb b/test/unit/ticket_null_byte_test.rb index aa3fdbd6a..0579112bf 100644 --- a/test/unit/ticket_null_byte_test.rb +++ b/test/unit/ticket_null_byte_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketNullByteTest < ActiveSupport::TestCase diff --git a/test/unit/ticket_overview_out_of_office_test.rb b/test/unit/ticket_overview_out_of_office_test.rb index f1901f628..9445f944c 100644 --- a/test/unit/ticket_overview_out_of_office_test.rb +++ b/test/unit/ticket_overview_out_of_office_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketOverviewOutOfOfficeTest < ActiveSupport::TestCase @@ -85,9 +85,9 @@ class TicketOverviewOutOfOfficeTest < ActiveSupport::TestCase direction: 'ASC', }, view: { - d: %w(title customer group created_at), - s: %w(title customer group created_at), - m: %w(number title customer group created_at), + d: %w[title customer group created_at], + s: %w[title customer group created_at], + m: %w[number title customer group created_at], view_mode_default: 's', }, ) @@ -111,9 +111,9 @@ class TicketOverviewOutOfOfficeTest < ActiveSupport::TestCase direction: 'ASC', }, view: { - d: %w(title customer group created_at), - s: %w(title customer group created_at), - m: %w(number title customer group created_at), + d: %w[title customer group created_at], + s: %w[title customer group created_at], + m: %w[number title customer group created_at], view_mode_default: 's', }, ) @@ -140,9 +140,9 @@ class TicketOverviewOutOfOfficeTest < ActiveSupport::TestCase direction: 'DESC', }, view: { - d: %w(title customer state created_at), - s: %w(number title state created_at), - m: %w(number title state created_at), + d: %w[title customer state created_at], + s: %w[number title state created_at], + m: %w[number title state created_at], view_mode_default: 's', }, ) diff --git a/test/unit/ticket_overview_test.rb b/test/unit/ticket_overview_test.rb index 284787ee4..6ab583cab 100644 --- a/test/unit/ticket_overview_test.rb +++ b/test/unit/ticket_overview_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketOverviewTest < ActiveSupport::TestCase @@ -106,9 +106,9 @@ class TicketOverviewTest < ActiveSupport::TestCase direction: 'ASC', }, view: { - d: %w(title customer group created_at), - s: %w(title customer group created_at), - m: %w(number title customer group created_at), + d: %w[title customer group created_at], + s: %w[title customer group created_at], + m: %w[number title customer group created_at], view_mode_default: 's', }, ) @@ -133,9 +133,9 @@ class TicketOverviewTest < ActiveSupport::TestCase direction: 'ASC', }, view: { - d: %w(title customer group created_at), - s: %w(title customer group created_at), - m: %w(number title customer group created_at), + d: %w[title customer group created_at], + s: %w[title customer group created_at], + m: %w[number title customer group created_at], view_mode_default: 's', }, ) @@ -160,9 +160,9 @@ class TicketOverviewTest < ActiveSupport::TestCase direction: 'ASC', }, view: { - d: %w(title customer group created_at), - s: %w(title customer group created_at), - m: %w(number title customer group created_at), + d: %w[title customer group created_at], + s: %w[title customer group created_at], + m: %w[number title customer group created_at], view_mode_default: 's', }, ) @@ -187,9 +187,9 @@ class TicketOverviewTest < ActiveSupport::TestCase direction: 'ASC', }, view: { - d: %w(title customer group created_at), - s: %w(title customer group created_at), - m: %w(number title customer group created_at), + d: %w[title customer group created_at], + s: %w[title customer group created_at], + m: %w[number title customer group created_at], view_mode_default: 's', }, ) @@ -215,9 +215,9 @@ class TicketOverviewTest < ActiveSupport::TestCase direction: 'DESC', }, view: { - d: %w(title customer state created_at), - s: %w(number title state created_at), - m: %w(number title state created_at), + d: %w[title customer state created_at], + s: %w[number title state created_at], + m: %w[number title state created_at], view_mode_default: 's', }, ) @@ -242,9 +242,9 @@ class TicketOverviewTest < ActiveSupport::TestCase direction: 'DESC', }, view: { - d: %w(title customer state created_at), - s: %w(number title customer state created_at), - m: %w(number title customer state created_at), + d: %w[title customer state created_at], + s: %w[number title customer state created_at], + m: %w[number title customer state created_at], view_mode_default: 's', }, ) @@ -270,9 +270,9 @@ class TicketOverviewTest < ActiveSupport::TestCase direction: 'DESC', }, view: { - d: %w(title customer state created_at), - s: %w(number title customer state created_at), - m: %w(number title customer state created_at), + d: %w[title customer state created_at], + s: %w[number title customer state created_at], + m: %w[number title customer state created_at], view_mode_default: 's', }, ) @@ -294,9 +294,9 @@ class TicketOverviewTest < ActiveSupport::TestCase direction: 'DESC', }, view: { - d: %w(title customer state created_at), - s: %w(number title customer state created_at), - m: %w(number title customer state created_at), + d: %w[title customer state created_at], + s: %w[number title customer state created_at], + m: %w[number title customer state created_at], view_mode_default: 's', }, ) diff --git a/test/unit/ticket_priority_test.rb b/test/unit/ticket_priority_test.rb index c6cbe4dee..92ff51064 100644 --- a/test/unit/ticket_priority_test.rb +++ b/test/unit/ticket_priority_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketPriorityTest < ActiveSupport::TestCase diff --git a/test/unit/ticket_ref_object_touch_test.rb b/test/unit/ticket_ref_object_touch_test.rb index 77bb2ed6c..d2957c7a5 100644 --- a/test/unit/ticket_ref_object_touch_test.rb +++ b/test/unit/ticket_ref_object_touch_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketRefObjectTouchTest < ActiveSupport::TestCase diff --git a/test/unit/ticket_selector_test.rb b/test/unit/ticket_selector_test.rb index 374172b09..6ba4e33e7 100644 --- a/test/unit/ticket_selector_test.rb +++ b/test/unit/ticket_selector_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketSelectorTest < ActiveSupport::TestCase diff --git a/test/unit/ticket_sla_test.rb b/test/unit/ticket_sla_test.rb index fa17d4eb9..83f15a403 100644 --- a/test/unit/ticket_sla_test.rb +++ b/test/unit/ticket_sla_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketSlaTest < ActiveSupport::TestCase @@ -141,7 +141,7 @@ class TicketSlaTest < ActiveSupport::TestCase condition: { 'ticket.priority_id' => { operator: 'is', - value: %w(1 2 3), + value: %w[1 2 3], }, }, calendar_id: calendar2.id, @@ -551,7 +551,7 @@ class TicketSlaTest < ActiveSupport::TestCase condition: { 'ticket.priority_id' => { operator: 'is', - value: %w(2), + value: %w[2], }, }, first_response_time: 60, @@ -676,7 +676,7 @@ class TicketSlaTest < ActiveSupport::TestCase condition: { 'ticket.priority_id' => { operator: 'is not', - value: %w(1 2 3), + value: %w[1 2 3], }, }, calendar_id: calendar.id, @@ -1640,7 +1640,7 @@ class TicketSlaTest < ActiveSupport::TestCase condition: { 'ticket.priority_id' => { operator: 'is', - value: %w(1 2 3), + value: %w[1 2 3], }, 'article.subject' => { operator: 'contains', @@ -1670,7 +1670,7 @@ class TicketSlaTest < ActiveSupport::TestCase condition: { 'ticket.priority_id' => { operator: 'is', - value: %w(1 2 3), + value: %w[1 2 3], }, 'ticket.title' => { operator: 'contains', @@ -1700,7 +1700,7 @@ class TicketSlaTest < ActiveSupport::TestCase condition: { 'ticket.priority_id' => { operator: 'is', - value: %w(1 2 3), + value: %w[1 2 3], }, 'ticket.title' => { operator: 'contains', diff --git a/test/unit/ticket_state_test.rb b/test/unit/ticket_state_test.rb index b4f9996e7..3e3cbf7a2 100644 --- a/test/unit/ticket_state_test.rb +++ b/test/unit/ticket_state_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketStateTest < ActiveSupport::TestCase diff --git a/test/unit/ticket_test.rb b/test/unit/ticket_test.rb index 39a51b90f..90dae91ea 100644 --- a/test/unit/ticket_test.rb +++ b/test/unit/ticket_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketTest < ActiveSupport::TestCase diff --git a/test/unit/ticket_trigger_test.rb b/test/unit/ticket_trigger_test.rb index 686827c6c..68aa9da73 100644 --- a/test/unit/ticket_trigger_test.rb +++ b/test/unit/ticket_trigger_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 +# rubocop:disable Lint/InterpolationCheck require 'test_helper' class TicketTriggerTest < ActiveSupport::TestCase @@ -189,7 +189,7 @@ class TicketTriggerTest < ActiveSupport::TestCase assert_equal('new', ticket1.state.name, 'ticket1.state verify') assert_equal('3 high', ticket1.priority.name, 'ticket1.priority verify') assert_equal(2, ticket1.articles.count, 'ticket1.articles verify') - assert_equal(%w(aa kk abc), ticket1.tag_list) + assert_equal(%w[aa kk abc], ticket1.tag_list) article1 = ticket1.articles.last assert_match('Zammad ', article1.from) assert_match('nicole.braun@zammad.org', article1.to) @@ -208,7 +208,7 @@ class TicketTriggerTest < ActiveSupport::TestCase assert_equal('new', ticket1.state.name, 'ticket1.state verify') assert_equal('2 normal', ticket1.priority.name, 'ticket1.priority verify') assert_equal(2, ticket1.articles.count, 'ticket1.articles verify') - assert_equal(%w(aa kk abc), ticket1.tag_list) + assert_equal(%w[aa kk abc], ticket1.tag_list) ticket1.state = Ticket::State.lookup(name: 'open') ticket1.save! @@ -221,7 +221,7 @@ class TicketTriggerTest < ActiveSupport::TestCase assert_equal('open', ticket1.state.name, 'ticket1.state verify') assert_equal('2 normal', ticket1.priority.name, 'ticket1.priority verify') assert_equal(2, ticket1.articles.count, 'ticket1.articles verify') - assert_equal(%w(aa kk abc), ticket1.tag_list) + assert_equal(%w[aa kk abc], ticket1.tag_list) ticket1.state = Ticket::State.lookup(name: 'new') ticket1.save! @@ -234,7 +234,7 @@ class TicketTriggerTest < ActiveSupport::TestCase assert_equal('new', ticket1.state.name, 'ticket1.state verify') assert_equal('3 high', ticket1.priority.name, 'ticket1.priority verify') assert_equal(2, ticket1.articles.count, 'ticket1.articles verify') - assert_equal(%w(aa abc), ticket1.tag_list) + assert_equal(%w[aa abc], ticket1.tag_list) ticket2 = Ticket.create( title: "some title\n äöüß", @@ -303,7 +303,7 @@ class TicketTriggerTest < ActiveSupport::TestCase assert_equal('new', ticket3.state.name, 'ticket3.state verify') assert_equal('3 high', ticket3.priority.name, 'ticket3.priority verify') assert_equal(3, ticket3.articles.count, 'ticket3.articles verify') - assert_equal(%w(aa kk abc article_create_trigger), ticket3.tag_list) + assert_equal(%w[aa kk abc article_create_trigger], ticket3.tag_list) article3 = ticket3.articles[1] assert_match('Zammad ', article3.from) assert_match('nicole.braun@zammad.org', article3.to) @@ -341,7 +341,7 @@ class TicketTriggerTest < ActiveSupport::TestCase assert_equal('new', ticket3.state.name, 'ticket3.state verify') assert_equal('3 high', ticket3.priority.name, 'ticket3.priority verify') assert_equal(4, ticket3.articles.count, 'ticket3.articles verify') - assert_equal(%w(aa abc article_create_trigger), ticket3.tag_list) + assert_equal(%w[aa abc article_create_trigger], ticket3.tag_list) Ticket::Article.create( ticket_id: ticket3.id, @@ -366,7 +366,7 @@ class TicketTriggerTest < ActiveSupport::TestCase assert_equal('new', ticket3.state.name, 'ticket3.state verify') assert_equal('3 high', ticket3.priority.name, 'ticket3.priority verify') assert_equal(5, ticket3.articles.count, 'ticket3.articles verify') - assert_equal(%w(aa abc article_create_trigger), ticket3.tag_list) + assert_equal(%w[aa abc article_create_trigger], ticket3.tag_list) Ticket::Article.create( ticket_id: ticket3.id, @@ -391,7 +391,7 @@ class TicketTriggerTest < ActiveSupport::TestCase assert_equal('new', ticket3.state.name, 'ticket3.state verify') assert_equal('3 high', ticket3.priority.name, 'ticket3.priority verify') assert_equal(7, ticket3.articles.count, 'ticket3.articles verify') - assert_equal(%w(aa abc article_create_trigger), ticket3.tag_list) + assert_equal(%w[aa abc article_create_trigger], ticket3.tag_list) end test '2 actions - create' do @@ -2959,7 +2959,7 @@ class TicketTriggerTest < ActiveSupport::TestCase perform: { 'notification.email' => { 'body' => 'some text
#{ticket.customer.lastname}
#{ticket.title}
#{article.body}', - 'recipient' => %w(ticket_owner article_last_sender), + 'recipient' => %w[ticket_owner article_last_sender], 'subject' => 'Thanks for your inquiry (#{ticket.title})!', }, }, @@ -2975,7 +2975,7 @@ class TicketTriggerTest < ActiveSupport::TestCase email: 'admin+owner_recipient@example.com', password: 'adminpw', active: true, - roles: Role.where(name: %w(Admin Agent)), + roles: Role.where(name: %w[Admin Agent]), updated_by_id: 1, created_by_id: 1, ) @@ -3469,7 +3469,7 @@ class TicketTriggerTest < ActiveSupport::TestCase assert_equal('new', ticket1.state.name, 'ticket1.state verify') assert_equal('3 high', ticket1.priority.name, 'ticket1.priority verify') assert_equal(2, ticket1.articles.count, 'ticket1.articles verify') - assert_equal(%w(aa kk), ticket1.tag_list) + assert_equal(%w[aa kk], ticket1.tag_list) article1 = ticket1.articles.last assert_match('Zammad ', article1.from) assert_match('nicole.braun@zammad.org', article1.to) diff --git a/test/unit/ticket_xss_test.rb b/test/unit/ticket_xss_test.rb index 7ebd33b13..a449b779b 100644 --- a/test/unit/ticket_xss_test.rb +++ b/test/unit/ticket_xss_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TicketXssTest < ActiveSupport::TestCase diff --git a/test/unit/token_test.rb b/test/unit/token_test.rb index f2c1d990f..ec1a2bf5b 100644 --- a/test/unit/token_test.rb +++ b/test/unit/token_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class TokenTest < ActiveSupport::TestCase diff --git a/test/unit/user_ref_object_touch_test.rb b/test/unit/user_ref_object_touch_test.rb index 3060cb474..c30f284b2 100644 --- a/test/unit/user_ref_object_touch_test.rb +++ b/test/unit/user_ref_object_touch_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class UserRefObjectTouchTest < ActiveSupport::TestCase diff --git a/test/unit/user_test.rb b/test/unit/user_test.rb index e04984cf8..a6842b556 100644 --- a/test/unit/user_test.rb +++ b/test/unit/user_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class UserTest < ActiveSupport::TestCase @@ -264,9 +264,7 @@ class UserTest < ActiveSupport::TestCase # check if user exists user = User.find_by(login: test[:create][:login]) - if user - user.destroy! - end + user&.destroy! user = User.create!(test[:create]) @@ -320,7 +318,7 @@ class UserTest < ActiveSupport::TestCase email: " #{email} ", password: 'customerpw', active: true, - roles: Role.where(name: %w(Customer)), + roles: Role.where(name: %w[Customer]), updated_by_id: 1, created_by_id: 1, ) @@ -336,7 +334,7 @@ class UserTest < ActiveSupport::TestCase email: "\u{00a0}#{email}\u{00a0}", password: 'customerpw', active: true, - roles: Role.where(name: %w(Customer)), + roles: Role.where(name: %w[Customer]), updated_by_id: 1, created_by_id: 1, ) @@ -354,7 +352,7 @@ class UserTest < ActiveSupport::TestCase email: "\u{200B}#{email}\u{200B}", password: 'customerpw', active: true, - roles: Role.where(name: %w(Customer)), + roles: Role.where(name: %w[Customer]), updated_by_id: 1, created_by_id: 1, ) @@ -372,7 +370,7 @@ class UserTest < ActiveSupport::TestCase email: "\u{200B}#{email}\u{200B}", password: 'customerpw', active: true, - roles: Role.where(name: %w(Customer)), + roles: Role.where(name: %w[Customer]), updated_by_id: 1, created_by_id: 1, ) @@ -390,7 +388,7 @@ class UserTest < ActiveSupport::TestCase email: "\u{200B}#{email}\u{200B}\u{2007}\u{2008}", password: 'customerpw', active: true, - roles: Role.where(name: %w(Customer)), + roles: Role.where(name: %w[Customer]), updated_by_id: 1, created_by_id: 1, ) @@ -413,7 +411,7 @@ class UserTest < ActiveSupport::TestCase #email: "", password: 'adminpw', active: true, - roles: Role.where(name: %w(Admin Agent)), + roles: Role.where(name: %w[Admin Agent]), updated_by_id: 1, created_by_id: 1, ) @@ -451,7 +449,7 @@ class UserTest < ActiveSupport::TestCase #email: "", password: 'adminpw', active: true, - roles: Role.where(name: %w(Admin Agent)), + roles: Role.where(name: %w[Admin Agent]), updated_by_id: 1, created_by_id: 1, ) @@ -487,7 +485,7 @@ class UserTest < ActiveSupport::TestCase email: email1, password: 'adminpw', active: true, - roles: Role.where(name: %w(Admin Agent)), + roles: Role.where(name: %w[Admin Agent]), updated_by_id: 1, created_by_id: 1, ) @@ -503,7 +501,7 @@ class UserTest < ActiveSupport::TestCase email: email1, password: 'adminpw', active: true, - roles: Role.where(name: %w(Admin Agent)), + roles: Role.where(name: %w[Admin Agent]), updated_by_id: 1, created_by_id: 1, ) @@ -516,7 +514,7 @@ class UserTest < ActiveSupport::TestCase email: email2, password: 'adminpw', active: true, - roles: Role.where(name: %w(Admin Agent)), + roles: Role.where(name: %w[Admin Agent]), updated_by_id: 1, created_by_id: 1, ) @@ -545,7 +543,7 @@ class UserTest < ActiveSupport::TestCase email: email1, password: 'adminpw', active: true, - roles: Role.where(name: %w(Admin Agent)), + roles: Role.where(name: %w[Admin Agent]), updated_by_id: 1, created_by_id: 1, ) @@ -560,7 +558,7 @@ class UserTest < ActiveSupport::TestCase email: email1, password: 'adminpw', active: true, - roles: Role.where(name: %w(Admin Agent)), + roles: Role.where(name: %w[Admin Agent]), updated_by_id: 1, created_by_id: 1, ) @@ -580,7 +578,7 @@ class UserTest < ActiveSupport::TestCase email: "admin-role#{name}@example.com", password: 'adminpw', active: true, - roles: Role.where(name: %w(Admin Agent)), + roles: Role.where(name: %w[Admin Agent]), updated_by_id: 1, created_by_id: 1, ) @@ -654,12 +652,12 @@ class UserTest < ActiveSupport::TestCase ) assert_raises(RuntimeError) do - customer3.roles = Role.where(name: %w(Customer Admin)) + customer3.roles = Role.where(name: %w[Customer Admin]) end assert_raises(RuntimeError) do - customer3.roles = Role.where(name: %w(Customer Agent)) + customer3.roles = Role.where(name: %w[Customer Agent]) end - customer3.roles = Role.where(name: %w(Admin Agent)) + customer3.roles = Role.where(name: %w[Admin Agent]) customer3.roles.each do |role| assert_not_equal(role.name, 'Customer') end @@ -760,7 +758,7 @@ class UserTest < ActiveSupport::TestCase name: 'Test3', note: 'People who create Tickets ask for help.', preferences: { - not: %w(Test1 Test2), + not: %w[Test1 Test2], }, updated_by_id: 1, created_by_id: 1 @@ -872,7 +870,7 @@ class UserTest < ActiveSupport::TestCase email: "admin-role#{name}@example.com", password: 'adminpw', active: true, - roles: Role.where(name: %w(Admin Agent)), + roles: Role.where(name: %w[Admin Agent]), updated_by_id: 1, created_by_id: 1, ) @@ -901,7 +899,7 @@ class UserTest < ActiveSupport::TestCase created_by_id: 1, ) users = User.with_permissions('not_existing') - assert(users.empty?) + assert(users.blank?) users = User.with_permissions('admin') assert_equal(admin_count + 1, users.count) @@ -949,7 +947,7 @@ class UserTest < ActiveSupport::TestCase email: "admin-role#{random}@example.com", password: 'adminpw', active: true, - roles: Role.where(name: %w(Admin Agent)), + roles: Role.where(name: %w[Admin Agent]), updated_by_id: 1, created_by_id: 1, ) @@ -962,7 +960,7 @@ class UserTest < ActiveSupport::TestCase email: "admin-role#{random}@example.com", password: 'adminpw', active: true, - roles: Role.where(name: %w(Admin Agent)), + roles: Role.where(name: %w[Admin Agent]), updated_by_id: 1, created_by_id: 1, ) @@ -975,7 +973,7 @@ class UserTest < ActiveSupport::TestCase email: "admin-role#{random}@example.com", password: 'adminpw', active: true, - roles: Role.where(name: %w(Admin Agent)), + roles: Role.where(name: %w[Admin Agent]), updated_by_id: 1, created_by_id: 1, ) @@ -983,18 +981,18 @@ class UserTest < ActiveSupport::TestCase admin_count_inital = User.with_permissions('admin').count assert_equal(3, admin_count_inital) - admin1.update!(roles: Role.where(name: %w(Agent))) + admin1.update!(roles: Role.where(name: %w[Agent])) admin_count_inital = User.with_permissions('admin').count assert_equal(2, admin_count_inital) - admin2.update!(roles: Role.where(name: %w(Agent))) + admin2.update!(roles: Role.where(name: %w[Agent])) admin_count_inital = User.with_permissions('admin').count assert_equal(1, admin_count_inital) assert_raises(Exceptions::UnprocessableEntity) do - admin3.update!(roles: Role.where(name: %w(Agent))) + admin3.update!(roles: Role.where(name: %w[Agent])) end admin_count_inital = User.with_permissions('admin').count diff --git a/test/unit/user_validate_agent_limit_test.rb b/test/unit/user_validate_agent_limit_test.rb index 2fbfa936c..34dd758a4 100644 --- a/test/unit/user_validate_agent_limit_test.rb +++ b/test/unit/user_validate_agent_limit_test.rb @@ -1,4 +1,4 @@ -# encoding: utf-8 + require 'test_helper' class UserValidateAgentLimit < ActiveSupport::TestCase