diff --git a/.rubocop/default.yml b/.rubocop/default.yml index ac9e8e0c4..a6252d172 100644 --- a/.rubocop/default.yml +++ b/.rubocop/default.yml @@ -273,6 +273,9 @@ Style/StringConcatenation: Exclude: - "config/routes/**/*" +Style/RegexpLiteral: + EnforcedStyle: percent_r + # RSpec tests Style/NumericPredicate: Description: >- diff --git a/app/controllers/application_controller/handles_errors.rb b/app/controllers/application_controller/handles_errors.rb index 651fe996a..20610f2db 100644 --- a/app/controllers/application_controller/handles_errors.rb +++ b/app/controllers/application_controller/handles_errors.rb @@ -82,11 +82,11 @@ module ApplicationController::HandlesErrors error: e.message } - if e.message =~ /Validation failed: (.+?)(,|$)/i + if e.message =~ %r{Validation failed: (.+?)(,|$)}i data[:error_human] = $1 - elsif e.message.match?(/(already exists|duplicate key|duplicate entry)/i) + elsif e.message.match?(%r{(already exists|duplicate key|duplicate entry)}i) data[:error_human] = 'Object already exists!' - elsif e.message =~ /null value in column "(.+?)" violates not-null constraint/i || e.message =~ /Field '(.+?)' doesn't have a default value/i + elsif e.message =~ %r{null value in column "(.+?)" violates not-null constraint}i || e.message =~ %r{Field '(.+?)' doesn't have a default value}i data[:error_human] = "Attribute '#{$1}' required!" elsif e.message == 'Exceptions::Forbidden' data[:error] = 'Not authorized' diff --git a/app/controllers/channels_email_controller.rb b/app/controllers/channels_email_controller.rb index eff163f8d..ed4237c14 100644 --- a/app/controllers/channels_email_controller.rb +++ b/app/controllers/channels_email_controller.rb @@ -224,7 +224,7 @@ class ChannelsEmailController < ApplicationController Channel.where(area: 'Email::Notification').each do |channel| active = false - if adapter.match?(/^#{channel.options[:outbound][:adapter]}$/i) + if adapter.match?(%r{^#{channel.options[:outbound][:adapter]}$}i) active = true channel.options = { outbound: { diff --git a/app/controllers/concerns/creates_ticket_articles.rb b/app/controllers/concerns/creates_ticket_articles.rb index 65570ea5d..0d59f20d1 100644 --- a/app/controllers/concerns/creates_ticket_articles.rb +++ b/app/controllers/concerns/creates_ticket_articles.rb @@ -37,7 +37,7 @@ module CreatesTicketArticles clean_params.delete(:sender) clean_params.delete(:origin_by_id) type = Ticket::Article::Type.lookup(id: clean_params[:type_id]) - if !type.name.match?(/^(note|web)$/) + if !type.name.match?(%r{^(note|web)$}) clean_params[:type_id] = Ticket::Article::Type.lookup(name: 'note').id end clean_params.delete(:type) @@ -91,12 +91,12 @@ module CreatesTicketArticles preferences_keys.each do |key| next if !attachment[key] - store_key = key.tr('-', '_').camelize.gsub(/(.+)([A-Z])/, '\1_\2').tr('_', '-') + store_key = key.tr('-', '_').camelize.gsub(%r{(.+)([A-Z])}, '\1_\2').tr('_', '-') preferences[store_key] = attachment[key] end begin - base64_data = attachment[:data].gsub(/[\r\n]/, '') + base64_data = attachment[:data].gsub(%r{[\r\n]}, '') attachment_data = Base64.strict_decode64(base64_data) rescue ArgumentError raise Exceptions::UnprocessableEntity, "Invalid base64 for attachment with index '#{index}'" diff --git a/app/controllers/getting_started_controller.rb b/app/controllers/getting_started_controller.rb index 4671203a6..89a793288 100644 --- a/app/controllers/getting_started_controller.rb +++ b/app/controllers/getting_started_controller.rb @@ -124,7 +124,7 @@ curl http://localhost/api/v1/getting_started -v -u #{login}:#{password} end # validate image - if params[:logo] && params[:logo] =~ /^data:image/i + if params[:logo] && params[:logo] =~ %r{^data:image}i file = StaticAssets.data_url_attributes(params[:logo]) if !file[:content] || !file[:mime_type] messages[:logo] = 'Unable to process image upload.' @@ -150,7 +150,7 @@ curl http://localhost/api/v1/getting_started -v -u #{login}:#{password} end # save image - if params[:logo] && params[:logo] =~ /^data:image/i + if params[:logo] && params[:logo] =~ %r{^data:image}i # data:image/png;base64 file = StaticAssets.data_url_attributes(params[:logo]) @@ -159,7 +159,7 @@ curl http://localhost/api/v1/getting_started -v -u #{login}:#{password} StaticAssets.store_raw(file[:content], file[:mime_type]) end - if params[:logo_resize] && params[:logo_resize] =~ /^data:image/i + if params[:logo_resize] && params[:logo_resize] =~ %r{^data:image}i # data:image/png;base64 file = StaticAssets.data_url_attributes(params[:logo_resize]) diff --git a/app/controllers/import_otrs_controller.rb b/app/controllers/import_otrs_controller.rb index b9e109ae5..83de2906c 100644 --- a/app/controllers/import_otrs_controller.rb +++ b/app/controllers/import_otrs_controller.rb @@ -23,10 +23,10 @@ class ImportOtrsController < ApplicationController } response = UserAgent.request(params[:url]) - if !response.success? && response.code.to_s !~ /^40.$/ + if !response.success? && response.code.to_s !~ %r{^40.$} message_human = '' translation_map.each do |key, message| - if response.error.to_s.match?(/#{Regexp.escape(key)}/i) + if response.error.to_s.match?(%r{#{Regexp.escape(key)}}i) message_human = message end end @@ -86,7 +86,7 @@ class ImportOtrsController < ApplicationController message_human: migrator_response['Error'] } end - elsif response.body.match?(/(otrs\sag|otrs\.com|otrs\.org)/i) + elsif response.body.match?(%r{(otrs\sag|otrs\.com|otrs\.org)}i) result = { result: 'invalid', message_human: 'Host found, but no OTRS migrator is installed!' diff --git a/app/controllers/import_zendesk_controller.rb b/app/controllers/import_zendesk_controller.rb index a68a3dbe1..ad4d6c9f1 100644 --- a/app/controllers/import_zendesk_controller.rb +++ b/app/controllers/import_zendesk_controller.rb @@ -27,7 +27,7 @@ class ImportZendeskController < ApplicationController if !response.success? message_human = '' translation_map.each do |key, message| - if response.error.to_s.match?(/#{Regexp.escape(key)}/i) + if response.error.to_s.match?(%r{#{Regexp.escape(key)}}i) message_human = message end end @@ -40,7 +40,7 @@ class ImportZendeskController < ApplicationController end # since 2016-10-15 a redirect to a marketing page has been implemented - if !response.body.match?(/#{params[:url]}/) + if !response.body.match?(%r{#{params[:url]}}) render json: { result: 'invalid', message_human: 'Hostname not found!', diff --git a/app/controllers/integration/check_mk_controller.rb b/app/controllers/integration/check_mk_controller.rb index 260d232d2..879a11f1a 100644 --- a/app/controllers/integration/check_mk_controller.rb +++ b/app/controllers/integration/check_mk_controller.rb @@ -61,7 +61,7 @@ UserAgent: #{request.env['HTTP_USER_AGENT'] || '-'} internal: false, ) end - if (!auto_close && params[:state].match(/#{state_recovery_match}/i)) || !params[:state].match(/#{state_recovery_match}/i) + if (!auto_close && params[:state].match(%r{#{state_recovery_match}}i)) || !params[:state].match(%r{#{state_recovery_match}}i) render json: { result: 'ticket already open, added note', ticket_ids: ticket_ids_found, @@ -71,7 +71,7 @@ UserAgent: #{request.env['HTTP_USER_AGENT'] || '-'} end # check if service is recovered - if auto_close && params[:state].present? && params[:state].match(/#{state_recovery_match}/i) + if auto_close && params[:state].present? && params[:state].match(%r{#{state_recovery_match}}i) if ticket_ids_found.blank? render json: { result: 'no open tickets found, ignore action', diff --git a/app/controllers/integration/smime_controller.rb b/app/controllers/integration/smime_controller.rb index 4751557dc..e1771e14f 100644 --- a/app/controllers/integration/smime_controller.rb +++ b/app/controllers/integration/smime_controller.rb @@ -42,7 +42,7 @@ class Integration::SMIMEController < ApplicationController string = params[:file].read.force_encoding('utf-8') end - items = string.scan(/.+?-+END(?: TRUSTED)? CERTIFICATE-+/mi).each_with_object([]) do |cert, result| + items = string.scan(%r{.+?-+END(?: TRUSTED)? CERTIFICATE-+}mi).each_with_object([]) do |cert, result| result << SMIMECertificate.create!(public_key: cert) end diff --git a/app/controllers/monitoring_controller.rb b/app/controllers/monitoring_controller.rb index 00795fbdd..5a7101791 100644 --- a/app/controllers/monitoring_controller.rb +++ b/app/controllers/monitoring_controller.rb @@ -308,7 +308,7 @@ curl http://localhost/api/v1/monitoring/amount_check?token=XXX&periode=1h raise Exceptions::UnprocessableEntity, 'periode is missing!' if params[:periode].blank? scale = params[:periode][-1, 1] - raise Exceptions::UnprocessableEntity, 'periode need to have s, m, h or d as last!' if !scale.match?(/^(s|m|h|d)$/) + raise Exceptions::UnprocessableEntity, 'periode need to have s, m, h or d as last!' if !scale.match?(%r{^(s|m|h|d)$}) periode = params[:periode][0, params[:periode].length - 1] raise Exceptions::UnprocessableEntity, 'periode need to be an integer!' if periode.to_i.zero? diff --git a/app/controllers/object_manager_attributes_controller.rb b/app/controllers/object_manager_attributes_controller.rb index 6f0c999e0..85899f71f 100644 --- a/app/controllers/object_manager_attributes_controller.rb +++ b/app/controllers/object_manager_attributes_controller.rb @@ -76,7 +76,7 @@ class ObjectManagerAttributesController < ApplicationController @permitted_params ||= begin permitted = params.permit!.to_h - if permitted[:data_type].match?(/^(boolean)$/) && permitted[:data_option][:options] + if permitted[:data_type].match?(%r{^(boolean)$}) && permitted[:data_option][:options] # rubocop:disable Lint/BooleanSymbol if permitted[:data_option][:options][:false] permitted[:data_option][:options][false] = permitted[:data_option][:options].delete(:false) @@ -98,7 +98,7 @@ class ObjectManagerAttributesController < ApplicationController if permitted[:data_option] if !permitted[:data_option].key?(:default) - permitted[:data_option][:default] = if permitted[:data_type].match?(/^(input|select|tree_select)$/) + permitted[:data_option][:default] = if permitted[:data_type].match?(%r{^(input|select|tree_select)$}) '' end end diff --git a/app/controllers/settings_controller.rb b/app/controllers/settings_controller.rb index 5368bb221..6207f632d 100644 --- a/app/controllers/settings_controller.rb +++ b/app/controllers/settings_controller.rb @@ -43,7 +43,7 @@ class SettingsController < ApplicationController end # validate image - if !clean_params[:logo].match?(/^data:image/i) + if !clean_params[:logo].match?(%r{^data:image}i) render json: { result: 'invalid', message: 'Invalid payload, need data:image in logo param', @@ -66,7 +66,7 @@ class SettingsController < ApplicationController # store resized image 1:1 setting = Setting.lookup(name: 'product_logo') - if params[:logo_resize] && params[:logo_resize] =~ /^data:image/i + if params[:logo_resize] && params[:logo_resize] =~ %r{^data:image}i # data:image/png;base64 file = StaticAssets.data_url_attributes(params[:logo_resize]) diff --git a/app/controllers/tickets_controller.rb b/app/controllers/tickets_controller.rb index 5c6d2378a..094a00e5b 100644 --- a/app/controllers/tickets_controller.rb +++ b/app/controllers/tickets_controller.rb @@ -96,7 +96,7 @@ class TicketsController < ApplicationController end # try to create customer if needed - if clean_params[:customer_id].present? && clean_params[:customer_id] =~ /^guess:(.+?)$/ + if clean_params[:customer_id].present? && clean_params[:customer_id] =~ %r{^guess:(.+?)$} email_address = $1 email_address_validation = EmailAddressValidation.new(email_address) if !email_address_validation.valid_format? diff --git a/app/helpers/knowledge_base_rich_text_helper.rb b/app/helpers/knowledge_base_rich_text_helper.rb index b9a00dd2b..1409f998d 100644 --- a/app/helpers/knowledge_base_rich_text_helper.rb +++ b/app/helpers/knowledge_base_rich_text_helper.rb @@ -27,7 +27,7 @@ module KnowledgeBaseRichTextHelper end def prepare_rich_text_videos(input) - input.gsub(/\((\s*)widget:(\s*)video\W([\s\S])+?\)/) do |match| + input.gsub(%r{\((\s*)widget:(\s*)video\W([\s\S])+?\)}) do |match| settings = match .slice(1...-1) .split(',') diff --git a/app/jobs/communicate_facebook_job.rb b/app/jobs/communicate_facebook_job.rb index a3acaad4e..5d451eff4 100644 --- a/app/jobs/communicate_facebook_job.rb +++ b/app/jobs/communicate_facebook_job.rb @@ -15,7 +15,7 @@ class CommunicateFacebookJob < ApplicationJob log_error(article, "Can't find ticket.preferences for Ticket.find(#{article.ticket_id})") if !ticket.preferences log_error(article, "Can't find ticket.preferences['channel_id'] for Ticket.find(#{article.ticket_id})") if !ticket.preferences['channel_id'] channel = Channel.lookup(id: ticket.preferences['channel_id']) - log_error(article, "Channel.find(#{channel.id}) isn't a twitter channel!") if !channel.options[:adapter].match?(/\Afacebook/i) + log_error(article, "Channel.find(#{channel.id}) isn't a twitter channel!") if !channel.options[:adapter].match?(%r{\Afacebook}i) # check source object id if !ticket.preferences['channel_fb_object_id'] diff --git a/app/jobs/communicate_telegram_job.rb b/app/jobs/communicate_telegram_job.rb index e808199b2..88fdd41a9 100644 --- a/app/jobs/communicate_telegram_job.rb +++ b/app/jobs/communicate_telegram_job.rb @@ -31,7 +31,7 @@ class CommunicateTelegramJob < ApplicationJob result = api.sendMessage(chat_id, article.body) me = api.getMe() article.attachments.each do |file| - parts = file.filename.split(/^(.*)(\..+?)$/) + parts = file.filename.split(%r{^(.*)(\..+?)$}) t = Tempfile.new([parts[1], parts[2]]) t.binmode t.write(file.content) diff --git a/app/jobs/communicate_twitter_job.rb b/app/jobs/communicate_twitter_job.rb index c4ecd152d..edb5ab634 100644 --- a/app/jobs/communicate_twitter_job.rb +++ b/app/jobs/communicate_twitter_job.rb @@ -30,7 +30,7 @@ class CommunicateTwitterJob < ApplicationJob end log_error(article, "No such channel id #{ticket.preferences['channel_id']}") if !channel - log_error(article, "Channel.find(#{channel.id}) isn't a twitter channel!") if !channel.options[:adapter].try(:match?, /\Atwitter/i) + log_error(article, "Channel.find(#{channel.id}) isn't a twitter channel!") if !channel.options[:adapter].try(:match?, %r{\Atwitter}i) begin tweet = channel.deliver( diff --git a/app/models/application_model/can_assets.rb b/app/models/application_model/can_assets.rb index 035e5f37b..6697d7e51 100644 --- a/app/models/application_model/can_assets.rb +++ b/app/models/application_model/can_assets.rb @@ -81,12 +81,12 @@ get assets and record_ids of selector attribute_ref_class = ::User item_ids = [] Array(content['recipient']).each do |identifier| - next if identifier !~ /\Auserid_(\d+)\z/ + next if identifier !~ %r{\Auserid_(\d+)\z} item_ids.push($1) end else - reflection = attribute[1].sub(/_id$/, '') + reflection = attribute[1].sub(%r{_id$}, '') next if !models[attribute_class] next if !models[attribute_class][:reflections] next if !models[attribute_class][:reflections][reflection] diff --git a/app/models/avatar.rb b/app/models/avatar.rb index 562e0d4eb..0a31cea99 100644 --- a/app/models/avatar.rb +++ b/app/models/avatar.rb @@ -110,10 +110,10 @@ add avatar by url content = data[:url].read filename = data[:url].path mime_type = 'image' - if filename.match?(/\.png/i) + if filename.match?(%r{\.png}i) mime_type = 'image/png' end - if filename.match?(/\.(jpg|jpeg)/i) + if filename.match?(%r{\.(jpg|jpeg)}i) mime_type = 'image/jpeg' end data[:resize] ||= {} @@ -132,7 +132,7 @@ add avatar by url # twitter workaround to get bigger avatar images # see also https://dev.twitter.com/overview/general/user-profile-images-and-banners if url.match?(%r{//pbs.twimg.com/}i) - url.sub!(/normal\.(png|jpg|gif)$/, 'bigger.\1') + url.sub!(%r{normal\.(png|jpg|gif)$}, 'bigger.\1') end # fetch image @@ -151,10 +151,10 @@ add avatar by url end logger.info "Fetchd image '#{url}', http code: #{response.code}" mime_type = 'image' - if url.match?(/\.png/i) + if url.match?(%r{\.png}i) mime_type = 'image/png' end - if url.match?(/\.(jpg|jpeg)/i) + if url.match?(%r{\.(jpg|jpeg)}i) mime_type = 'image/jpeg' end diff --git a/app/models/calendar.rb b/app/models/calendar.rb index 5ce689e7c..7b822d8a8 100644 --- a/app/models/calendar.rb +++ b/app/models/calendar.rb @@ -27,7 +27,7 @@ returns calendar object def self.init_setup(ip = nil) # ignore client ip if not public ip - if ip && ip =~ /^(::1|127\.|10\.|172\.1[6-9]\.|172\.2[0-9]\.|172\.3[0-1]\.|192\.168\.)/ + if ip && ip =~ %r{^(::1|127\.|10\.|172\.1[6-9]\.|172\.2[0-9]\.|172\.3[0-1]\.|192\.168\.)} ip = nil end @@ -214,7 +214,7 @@ returns end def self.fetch_parse(location) - if location.match?(/^http/i) + if location.match?(%r{^http}i) result = UserAgent.get(location) if !result.success? raise result.error @@ -262,7 +262,7 @@ returns comment = comment.to_utf8(fallback: :read_as_sanitized_binary) # ignore daylight saving time entries - return if comment.match?(/(daylight saving|sommerzeit|summertime)/i) + return if comment.match?(%r{(daylight saving|sommerzeit|summertime)}i) [day, comment] end diff --git a/app/models/channel/driver/imap.rb b/app/models/channel/driver/imap.rb index 90b95b4ff..e460feed5 100644 --- a/app/models/channel/driver/imap.rb +++ b/app/models/channel/driver/imap.rb @@ -226,7 +226,7 @@ example headers = self.class.extract_rfc822_headers(message_meta) subject = headers['Subject'] next if !subject - next if !subject.match?(/#{verify_string}/) + next if !subject.match?(%r{#{verify_string}}) Rails.logger.info " - verify email #{verify_string} found" timeout(600) do @@ -406,7 +406,7 @@ returns array = string .gsub("\r\n\t", ' ') # Some servers (e.g. microsoft365) may put attribute value on a separate line and tab it .lines(chomp: true) - .map { |line| line.split(/:\s*/, 2).map(&:strip) } + .map { |line| line.split(%r{:\s*}, 2).map(&:strip) } array.each { |elem| elem.append(nil) if elem.one? } diff --git a/app/models/channel/driver/pop3.rb b/app/models/channel/driver/pop3.rb index c73231585..5c34afd85 100644 --- a/app/models/channel/driver/pop3.rb +++ b/app/models/channel/driver/pop3.rb @@ -91,7 +91,7 @@ returns next if !mail # check how many content messages we have, for notice used - if !mail.match?(/(X-Zammad-Ignore: true|X-Zammad-Verify: true)/) + if !mail.match?(%r{(X-Zammad-Ignore: true|X-Zammad-Verify: true)}) content_messages += 1 break if content_max_check < content_messages end @@ -117,7 +117,7 @@ returns next if !mail # check if verify message exists - next if !mail.match?(/#{verify_string}/) + next if !mail.match?(%r{#{verify_string}}) Rails.logger.info " - verify email #{verify_string} found" m.delete @@ -149,7 +149,7 @@ returns next if !mail # ignore verify messages - if mail.match?(/(X-Zammad-Ignore: true|X-Zammad-Verify: true)/) && mail =~ /X-Zammad-Verify-Time:\s(.+?)\s/ + if mail.match?(%r{(X-Zammad-Ignore: true|X-Zammad-Verify: true)}) && mail =~ %r{X-Zammad-Verify-Time:\s(.+?)\s} begin verify_time = Time.zone.parse($1) if verify_time > Time.zone.now - 30.minutes diff --git a/app/models/channel/driver/smtp.rb b/app/models/channel/driver/smtp.rb index a1f32fe39..4bba2f6c7 100644 --- a/app/models/channel/driver/smtp.rb +++ b/app/models/channel/driver/smtp.rb @@ -36,7 +36,7 @@ class Channel::Driver::Smtp if !options.key?(:domain) # set fqdn, if local fqdn - use domain of sender fqdn = Setting.get('fqdn') - if fqdn =~ /(localhost|\.local^|\.loc^)/i && (attr['from'] || attr[:from]) + if fqdn =~ %r{(localhost|\.local^|\.loc^)}i && (attr['from'] || attr[:from]) domain = Mail::Address.new(attr['from'] || attr[:from]).domain if domain fqdn = domain diff --git a/app/models/channel/email_build.rb b/app/models/channel/email_build.rb index 6f78de39e..4deb0b58a 100644 --- a/app/models/channel/email_build.rb +++ b/app/models/channel/email_build.rb @@ -157,7 +157,7 @@ returns =end def self.recipient_line(realname, email) - return "#{realname} <#{email}>" if realname.match?(/^[A-z]+$/i) + return "#{realname} <#{email}>" if realname.match?(%r{^[A-z]+$}i) "\"#{realname.gsub('"', '\"')}\" <#{email}>" end @@ -175,7 +175,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.match?(//i) + return html if html.match?(%r{}i) html_email_body = File.read(Rails.root.join('app/views/mailer/application_wrapper.html.erb').to_s) @@ -198,7 +198,7 @@ Add/change markup to display html in any mail client nice. # https://github.com/martini/zammad/issues/165 new_html = html.gsub('
', '
') - new_html.gsub!(/

/mxi, '

') + new_html.gsub!(%r{

}mxi, '

') new_html.gsub!(%r{}mxi, '


') new_html end diff --git a/app/models/channel/email_parser.rb b/app/models/channel/email_parser.rb index e6646f025..e46085ca5 100644 --- a/app/models/channel/email_parser.rb +++ b/app/models/channel/email_parser.rb @@ -4,7 +4,7 @@ class Channel::EmailParser PROZESS_TIME_MAX = 180 - EMAIL_REGEX = /.+@.+/.freeze + EMAIL_REGEX = %r{.+@.+}.freeze RECIPIENT_FIELDS = %w[to cc delivered-to x-original-to envelope-to].freeze SENDER_FIELDS = %w[from reply-to return-path sender].freeze EXCESSIVE_LINKS_MSG = 'This message cannot be displayed because it contains over 5,000 links. Download the raw message below and open it via an Email client if you still wish to view it.'.freeze @@ -351,7 +351,7 @@ returns # skip check attributes if it is tags return true if header_name == 'x-zammad-ticket-tags' - if header_name =~ /^x-zammad-(.+?)-(followup-|)(.*)$/i + if header_name =~ %r{^x-zammad-(.+?)-(followup-|)(.*)$}i class_name = $1 attribute = $3 end @@ -401,7 +401,7 @@ returns data[:from_local] = mail_address.local data[:from_domain] = mail_address.domain data[:from_display_name] = mail_address.display_name || mail_address.comments&.first - elsif from =~ /^(.+?)<((.+?)@(.+?))>/ + elsif from =~ %r{^(.+?)<((.+?)@(.+?))>} data[:from_email] = $2 data[:from_local] = $3 data[:from_domain] = $4 @@ -419,7 +419,7 @@ returns .to_s .delete('"') .strip - .gsub(/(^'|'$)/, '') + .gsub(%r{(^'|'$)}, '') data end @@ -539,7 +539,7 @@ process unprocessable_mails (tmp/unprocessable_mail/*.eml) again part.body = force_japanese_encoding part.body.encoded.unpack1('M') end - ISO2022JP_REGEXP = /=\?ISO-2022-JP\?B\?(.+?)\?=/.freeze + ISO2022JP_REGEXP = %r{=\?ISO-2022-JP\?B\?(.+?)\?=}.freeze # https://github.com/zammad/zammad/issues/3115 def header_field_unpack_japanese(field) @@ -630,7 +630,7 @@ process unprocessable_mails (tmp/unprocessable_mail/*.eml) again return body_text if !options[:strict_html] # Issue #2390 - emails with >5k HTML links should be rejected - return EXCESSIVE_LINKS_MSG if body_text.scan(/= 5_000 + return EXCESSIVE_LINKS_MSG if body_text.scan(%r{= 5_000 body_text.html2html_strict end @@ -717,7 +717,7 @@ process unprocessable_mails (tmp/unprocessable_mail/*.eml) again rescue begin case file.header[:content_disposition].to_s - when /(filename|name)(\*{0,1})="(.+?)"/i, /(filename|name)(\*{0,1})='(.+?)'/i, /(filename|name)(\*{0,1})=(.+?);/i + when %r{(filename|name)(\*{0,1})="(.+?)"}i, %r{(filename|name)(\*{0,1})='(.+?)'}i, %r{(filename|name)(\*{0,1})=(.+?);}i filename = $3 end rescue @@ -727,7 +727,7 @@ process unprocessable_mails (tmp/unprocessable_mail/*.eml) again begin case file.header[:content_disposition].to_s - when /(filename|name)(\*{0,1})="(.+?)"/i, /(filename|name)(\*{0,1})='(.+?)'/i, /(filename|name)(\*{0,1})=(.+?);/i + when %r{(filename|name)(\*{0,1})="(.+?)"}i, %r{(filename|name)(\*{0,1})='(.+?)'}i, %r{(filename|name)(\*{0,1})=(.+?);}i filename = $3 end rescue @@ -737,7 +737,7 @@ process unprocessable_mails (tmp/unprocessable_mail/*.eml) again # as fallback, use raw values if filename.blank? case headers_store['Content-Disposition'].to_s - when /(filename|name)(\*{0,1})="(.+?)"/i, /(filename|name)(\*{0,1})='(.+?)'/i, /(filename|name)(\*{0,1})=(.+?);/i + when %r{(filename|name)(\*{0,1})="(.+?)"}i, %r{(filename|name)(\*{0,1})='(.+?)'}i, %r{(filename|name)(\*{0,1})=(.+?);}i filename = $3 end end @@ -767,7 +767,7 @@ process unprocessable_mails (tmp/unprocessable_mail/*.eml) again # e. g. Content-Type: video/quicktime; name="Video.MOV"; if filename.blank? ['(filename|name)(\*{0,1})="(.+?)"(;|$)', '(filename|name)(\*{0,1})=\'(.+?)\'(;|$)', '(filename|name)(\*{0,1})=(.+?)(;|$)'].each do |regexp| - if headers_store['Content-Type'] =~ /#{regexp}/i + if headers_store['Content-Type'] =~ %r{#{regexp}}i filename = $3 break end @@ -785,7 +785,7 @@ process unprocessable_mails (tmp/unprocessable_mail/*.eml) again end # generate file name based on content-id with file extention - if filename.blank? && headers_store['Content-ID'].present? && headers_store['Content-ID'] =~ /(.+?\..{2,6})@.+?/i + if filename.blank? && headers_store['Content-ID'].present? && headers_store['Content-ID'] =~ %r{(.+?\..{2,6})@.+?}i filename = $1 end @@ -802,7 +802,7 @@ process unprocessable_mails (tmp/unprocessable_mail/*.eml) again 'image/gif': %w[gif image], } map.each do |type, ext| - next if !content_type.match?(/^#{Regexp.quote(type)}/i) + next if !content_type.match?(%r{^#{Regexp.quote(type)}}i) filename = if headers_store['Content-Description'].present? "#{headers_store['Content-Description']}.#{ext[0]}".to_s.force_encoding('utf-8') @@ -814,7 +814,7 @@ process unprocessable_mails (tmp/unprocessable_mail/*.eml) again end # generate file name based on content-id without file extention - if filename.blank? && headers_store['Content-ID'].present? && headers_store['Content-ID'] =~ /(.+?)@.+?/i + if filename.blank? && headers_store['Content-ID'].present? && headers_store['Content-ID'] =~ %r{(.+?)@.+?}i filename = $1 end @@ -826,7 +826,7 @@ process unprocessable_mails (tmp/unprocessable_mail/*.eml) again # create uniq filename local_filename = '' local_extention = '' - if filename =~ /^(.*?)\.(.+?)$/ + if filename =~ %r{^(.*?)\.(.+?)$} local_filename = $1 local_extention = $2 end @@ -925,7 +925,7 @@ process unprocessable_mails (tmp/unprocessable_mail/*.eml) again reply.merge( to: parsed_incoming_mail[:from_email], - body: reply[:body].gsub(/\n/, "\r\n"), + body: reply[:body].gsub(%r{\n}, "\r\n"), content_type: 'text/plain', References: parsed_incoming_mail[:message_id], 'In-Reply-To': parsed_incoming_mail[:message_id], @@ -978,7 +978,7 @@ module Mail end return value if value.blank? - value.sub(/^.+?:(\s|)/, '') + value.sub(%r{^.+?:(\s|)}, '') end end diff --git a/app/models/channel/filter/auto_response_check.rb b/app/models/channel/filter/auto_response_check.rb index b22b9b80b..aaa4caf0d 100644 --- a/app/models/channel/filter/auto_response_check.rb +++ b/app/models/channel/filter/auto_response_check.rb @@ -15,17 +15,17 @@ module Channel::Filter::AutoResponseCheck mail[ :'x-zammad-article-preferences' ]['is-auto-response'] = true # do not send an auto response if one of the following headers exists - return if mail[ :'list-unsubscribe' ] && mail[ :'list-unsubscribe' ] =~ /.../ - return if mail[ :'x-loop' ] && mail[ :'x-loop' ] =~ /(yes|true)/i - return if mail[ :precedence ] && mail[ :precedence ] =~ /(bulk|list|junk)/i - return if mail[ :'auto-submitted' ] && mail[ :'auto-submitted' ] =~ /auto-(generated|replied)/i - return if mail[ :'x-auto-response-suppress' ] && mail[ :'x-auto-response-suppress' ] =~ /all/i + return if mail[ :'list-unsubscribe' ] && mail[ :'list-unsubscribe' ] =~ %r{...} + return if mail[ :'x-loop' ] && mail[ :'x-loop' ] =~ %r{(yes|true)}i + return if mail[ :precedence ] && mail[ :precedence ] =~ %r{(bulk|list|junk)}i + return if mail[ :'auto-submitted' ] && mail[ :'auto-submitted' ] =~ %r{auto-(generated|replied)}i + return if mail[ :'x-auto-response-suppress' ] && mail[ :'x-auto-response-suppress' ] =~ %r{all}i # do not send an auto response if sender is system itself message_id = mail[ :message_id ] if message_id fqdn = Setting.get('fqdn') - return if message_id.match?(/@#{Regexp.quote(fqdn)}/i) + return if message_id.match?(%r{@#{Regexp.quote(fqdn)}}i) end mail[ :'x-zammad-send-auto-response' ] = true diff --git a/app/models/channel/filter/bounce_delivery_permanent_failed.rb b/app/models/channel/filter/bounce_delivery_permanent_failed.rb index b35addda2..4b384b93c 100644 --- a/app/models/channel/filter/bounce_delivery_permanent_failed.rb +++ b/app/models/channel/filter/bounce_delivery_permanent_failed.rb @@ -53,7 +53,7 @@ module Channel::Filter::BounceDeliveryPermanentFailed # get recipient bounce mail, mark this user to not sent notifications anymore final_recipient = mail[:mail_instance].final_recipient if final_recipient.present? - final_recipient.sub!(/rfc822;\s{0,10}/, '') + final_recipient.sub!(%r{rfc822;\s{0,10}}, '') if final_recipient.present? recipients.push final_recipient.downcase end diff --git a/app/models/channel/filter/follow_up_check.rb b/app/models/channel/filter/follow_up_check.rb index 3a5353afd..c20539a4c 100644 --- a/app/models/channel/filter/follow_up_check.rb +++ b/app/models/channel/filter/follow_up_check.rb @@ -72,7 +72,7 @@ module Channel::Filter::FollowUpCheck references += mail[:'in-reply-to'] end if references != '' - message_ids = references.split(/\s+/) + message_ids = references.split(%r{\s+}) message_ids.each do |message_id| message_id_md5 = Digest::MD5.hexdigest(message_id) article = Ticket::Article.where(message_id_md5: message_id_md5).order('created_at DESC, id DESC').limit(1).first @@ -86,7 +86,7 @@ module Channel::Filter::FollowUpCheck # remove leading "..:\s" and "..[\d+]:\s" e. g. "Re: " or "Re[5]: " subject_to_check = mail[:subject] - subject_to_check.gsub!(/^(..(\[\d+\])?:\s+)+/, '') + subject_to_check.gsub!(%r{^(..(\[\d+\])?:\s+)+}, '') # if subject is different, it's no followup next if subject_to_check != article_first.subject @@ -119,7 +119,7 @@ module Channel::Filter::FollowUpCheck def self.follow_up_by_md5(mail) return if mail[:'x-zammad-ticket-id'] - mail_references(mail).split(/\s+/).each do |message_id| + mail_references(mail).split(%r{\s+}).each do |message_id| article = message_id_article(message_id) next if article.blank? diff --git a/app/models/channel/filter/follow_up_possible_check.rb b/app/models/channel/filter/follow_up_possible_check.rb index a1b1a6cd0..599f12f5a 100644 --- a/app/models/channel/filter/follow_up_possible_check.rb +++ b/app/models/channel/filter/follow_up_possible_check.rb @@ -8,7 +8,7 @@ module Channel::Filter::FollowUpPossibleCheck ticket = Ticket.lookup(id: ticket_id) return true if !ticket - return true if !ticket.state.state_type.name.match?(/^(closed|merged|removed)/i) + return true if !ticket.state.state_type.name.match?(%r{^(closed|merged|removed)}i) # in case of closed tickets, remove follow-up information case ticket.group.follow_up_possible diff --git a/app/models/channel/filter/identify_sender.rb b/app/models/channel/filter/identify_sender.rb index 7ec42123f..c5f4f50ab 100644 --- a/app/models/channel/filter/identify_sender.rb +++ b/app/models/channel/filter/identify_sender.rb @@ -123,10 +123,10 @@ module Channel::Filter::IdentifySender recipients.each do |recipient| address = nil display_name = nil - if recipient =~ /.*<(.+?)>/ + if recipient =~ %r{.*<(.+?)>} address = $1 end - if recipient =~ /^(.+?)<(.+?)>/ + if recipient =~ %r{^(.+?)<(.+?)>} display_name = $1 end @@ -162,7 +162,7 @@ module Channel::Filter::IdentifySender end def self.populate_attributes!(attrs, **extras) - if attrs[:email].match?(/\S\s+\S/) || attrs[:email].match?(/^<|>$/) + if attrs[:email].match?(%r{\S\s+\S}) || attrs[:email].match?(%r{^<|>$}) attrs[:preferences] = { mail_delivery_failed: true, mail_delivery_failed_reason: 'invalid email', mail_delivery_failed_data: Time.zone.now } @@ -187,7 +187,7 @@ module Channel::Filter::IdentifySender .delete('"') .delete_prefix("'") .delete_suffix("'") - .gsub(/.+?\s\(.+?\)$/, '') + .gsub(%r{.+?\s\(.+?\)$}, '') end def self.sanitize_email(string) @@ -197,10 +197,10 @@ module Channel::Filter::IdentifySender .strip .delete('"') .delete("'") - .delete(' ') # see https://github.com/zammad/zammad/issues/2254 - .sub(/^<|>$/, '') # see https://github.com/zammad/zammad/issues/2254 - .sub(/\A'(.*)'\z/, '\1') # see https://github.com/zammad/zammad/issues/2154 - .gsub(/\s/, '') # see https://github.com/zammad/zammad/issues/2198 + .delete(' ') # see https://github.com/zammad/zammad/issues/2254 + .sub(%r{^<|>$}, '') # see https://github.com/zammad/zammad/issues/2254 + .sub(%r{\A'(.*)'\z}, '\1') # see https://github.com/zammad/zammad/issues/2154 + .gsub(%r{\s}, '') # see https://github.com/zammad/zammad/issues/2198 .delete_suffix('.') end diff --git a/app/models/channel/filter/match/email_regex.rb b/app/models/channel/filter/match/email_regex.rb index 846257211..a83ed1016 100644 --- a/app/models/channel/filter/match/email_regex.rb +++ b/app/models/channel/filter/match/email_regex.rb @@ -2,20 +2,20 @@ module Channel::Filter::Match::EmailRegex def self.match(value:, match_rule:, check_mode: false) regexp = false - if match_rule =~ /^(regex:)(.+?)$/ + if match_rule =~ %r{^(regex:)(.+?)$} regexp = true match_rule = $2 end if regexp == false - match_rule_quoted = Regexp.quote(match_rule).gsub(/\\\*/, '.*') - return true if value.match?(/#{match_rule_quoted}/i) + match_rule_quoted = Regexp.quote(match_rule).gsub(%r{\\\*}, '.*') + return true if value.match?(%r{#{match_rule_quoted}}i) return false end begin - return true if value.match?(/#{match_rule}/i) + return true if value.match?(%r{#{match_rule}}i) return false rescue => e diff --git a/app/models/channel/filter/monitoring_base.rb b/app/models/channel/filter/monitoring_base.rb index cc3ec66cc..f6e5e9604 100644 --- a/app/models/channel/filter/monitoring_base.rb +++ b/app/models/channel/filter/monitoring_base.rb @@ -47,26 +47,26 @@ class Channel::Filter::MonitoringBase return if result['host'].blank? # icinga - get state by body - new templates - if result['state'].blank? && mail[:body] =~ /.+?\sis\s(.+?)!/ + if result['state'].blank? && mail[:body] =~ %r{.+?\sis\s(.+?)!} result['state'] = $1 end # icinga - get state by subject - new templates "state:" is not in body anymore # Subject: [PROBLEM] Ping IPv4 on host1234.dc.example.com is WARNING! # Subject: [PROBLEM] Host host1234.dc.example.com is DOWN! - if result['state'].blank? && mail[:subject] =~ /(on|Host)\s.+?\sis\s(.+?)!/ + if result['state'].blank? && mail[:subject] =~ %r{(on|Host)\s.+?\sis\s(.+?)!} result['state'] = $2 end # monit - get missing attributes from body - if result['service'].blank? && mail[:body] =~ /\sService\s(.+?)\s/ + if result['service'].blank? && mail[:body] =~ %r{\sService\s(.+?)\s} result['service'] = $1 end # possible event types https://mmonit.com/monit/documentation/#Setting-an-event-filter if result['state'].blank? result['state'] = case mail[:body] - when /\s(done|recovery|succeeded|bytes\sok|packets\sok)\s/, /(instance\schanged\snot|Link\sup|Exists|Saturation\sok|Speed\sok)/ + when %r{\s(done|recovery|succeeded|bytes\sok|packets\sok)\s}, %r{(instance\schanged\snot|Link\sup|Exists|Saturation\sok|Speed\sok)} 'OK' else 'CRITICAL' @@ -89,7 +89,7 @@ class Channel::Filter::MonitoringBase mail[ :'x-zammad-ticket-id' ] = ticket.id # check if service is recovered - if auto_close && result['state'].present? && result['state'].match(/#{state_recovery_match}/i) + if auto_close && result['state'].present? && result['state'].match(%r{#{state_recovery_match}}i) Rails.logger.info "MonitoringBase.#{integration} set autoclose to state_id #{auto_close_state_id}" state = Ticket::State.lookup(id: auto_close_state_id) if state @@ -112,13 +112,13 @@ class Channel::Filter::MonitoringBase end # ignore states - if state_ignore_match.present? && result['state'].present? && result['state'].match(/#{state_ignore_match}/i) + if state_ignore_match.present? && result['state'].present? && result['state'].match(%r{#{state_ignore_match}}i) mail[ :'x-zammad-ignore' ] = true return true end # if now problem exists, just ignore the email - if result['state'].present? && result['state'].match(/#{state_recovery_match}/i) + if result['state'].present? && result['state'].match(%r{#{state_recovery_match}}i) mail[ :'x-zammad-ignore' ] = true return true end diff --git a/app/models/channel/filter/out_of_office_check.rb b/app/models/channel/filter/out_of_office_check.rb index 76f6f3334..3d964357d 100644 --- a/app/models/channel/filter/out_of_office_check.rb +++ b/app/models/channel/filter/out_of_office_check.rb @@ -8,7 +8,7 @@ module Channel::Filter::OutOfOfficeCheck # check ms out of office characteristics if mail[ :'x-auto-response-suppress' ] - return if !mail[ :'x-auto-response-suppress' ].match?(/all/i) + return if !mail[ :'x-auto-response-suppress' ].match?(%r{all}i) return if !mail[ :'x-ms-exchange-inbox-rules-loop' ] mail[ :'x-zammad-out-of-office' ] = true @@ -18,17 +18,17 @@ module Channel::Filter::OutOfOfficeCheck if mail[ :'auto-submitted' ] # check zimbra out of office characteristics - if mail[ :'auto-submitted' ].match?(/vacation/i) + if mail[ :'auto-submitted' ].match?(%r{vacation}i) mail[ :'x-zammad-out-of-office' ] = true end # check cloud out of office characteristics - if mail[ :'auto-submitted' ].match?(/auto-replied;\sowner-email=/i) + if mail[ :'auto-submitted' ].match?(%r{auto-replied;\sowner-email=}i) mail[ :'x-zammad-out-of-office' ] = true end # gmail check out of office characteristics - if mail[ :'auto-submitted' ] =~ /auto-replied/i && mail[ :subject ] =~ /vacation/i + if mail[ :'auto-submitted' ] =~ %r{auto-replied}i && mail[ :subject ] =~ %r{vacation}i mail[ :'x-zammad-out-of-office' ] = true end diff --git a/app/models/channel/filter/own_notification_loop_detection.rb b/app/models/channel/filter/own_notification_loop_detection.rb index 086fe04c4..f7ed90b67 100644 --- a/app/models/channel/filter/own_notification_loop_detection.rb +++ b/app/models/channel/filter/own_notification_loop_detection.rb @@ -9,10 +9,10 @@ module Channel::Filter::OwnNotificationLoopDetection recedence = mail[:precedence] return if !recedence - return if !recedence.match?(/bulk/i) + return if !recedence.match?(%r{bulk}i) fqdn = Setting.get('fqdn') - return if !message_id.match?(/@#{Regexp.quote(fqdn)}>/i) + return if !message_id.match?(%r{@#{Regexp.quote(fqdn)}>}i) mail[ :'x-zammad-ignore' ] = true Rails.logger.info "Detected own sent notification mail and dropped it to prevent loops (message_id: #{message_id}, from: #{mail[:from]}, to: #{mail[:to]})" diff --git a/app/models/channel/filter/service_now_check.rb b/app/models/channel/filter/service_now_check.rb index 6ead40c3f..bc43823a6 100644 --- a/app/models/channel/filter/service_now_check.rb +++ b/app/models/channel/filter/service_now_check.rb @@ -44,7 +44,7 @@ returns: # check if we can find the service now relation source_id = nil - if subject =~ /\s(INC\d+)\s/ + if subject =~ %r{\s(INC\d+)\s} source_id = $1 end diff --git a/app/models/channel/filter/trusted.rb b/app/models/channel/filter/trusted.rb index a5bf57a20..9a2d4cc83 100644 --- a/app/models/channel/filter/trusted.rb +++ b/app/models/channel/filter/trusted.rb @@ -8,7 +8,7 @@ module Channel::Filter::Trusted # check if trust x-headers if !trusted(channel) mail.each_key do |key| - next if !key.match?(/^x-zammad/i) + next if !key.match?(%r{^x-zammad}i) mail.delete(key) end @@ -17,7 +17,7 @@ module Channel::Filter::Trusted # verify values mail.each do |key, value| - next if !key.match?(/^x-zammad/i) + next if !key.match?(%r{^x-zammad}i) # no assoc exists, remove header next if Channel::EmailParser.check_attributes_by_x_headers(key, value) diff --git a/app/models/chat.rb b/app/models/chat.rb index 5c8069441..b1bb85a76 100644 --- a/app/models/chat.rb +++ b/app/models/chat.rb @@ -611,7 +611,7 @@ check if ip address is blocked for chat ips = block_ip.split(';') ips.each do |local_ip| return true if ip == local_ip.strip - return true if ip.match?(/#{local_ip.strip.gsub(/\*/, '.+?')}/) + return true if ip.match?(%r{#{local_ip.strip.gsub(%r{\*}, '.+?')}}) end false end diff --git a/app/models/concerns/can_clone_attachments.rb b/app/models/concerns/can_clone_attachments.rb index 347ea22d4..4419db6f2 100644 --- a/app/models/concerns/can_clone_attachments.rb +++ b/app/models/concerns/can_clone_attachments.rb @@ -37,7 +37,7 @@ returns if options[:only_attached_attachments] == true && is_html_content == true content_id = new_attachment.preferences['Content-ID'] || new_attachment.preferences['content_id'] - next if content_id.present? && body.present? && body.match?(/#{Regexp.quote(content_id)}/i) + next if content_id.present? && body.present? && body.match?(%r{#{Regexp.quote(content_id)}}i) end # only_inline_attachments mode is used when quoting HTML mail with #{article.body_as_html} @@ -46,11 +46,11 @@ returns next if body.blank? content_disposition = new_attachment.preferences['Content-Disposition'] || new_attachment.preferences['content_disposition'] - next if content_disposition.present? && content_disposition !~ /inline/ + next if content_disposition.present? && content_disposition !~ %r{inline} content_id = new_attachment.preferences['Content-ID'] || new_attachment.preferences['content_id'] next if content_id.blank? - next if !body.match?(/#{Regexp.quote(content_id)}/i) + next if !body.match?(%r{#{Regexp.quote(content_id)}}i) end already_added = false diff --git a/app/models/concerns/checks_client_notification.rb b/app/models/concerns/checks_client_notification.rb index 85862c6bc..25b9e5716 100644 --- a/app/models/concerns/checks_client_notification.rb +++ b/app/models/concerns/checks_client_notification.rb @@ -12,7 +12,7 @@ module ChecksClientNotification def notify_clients_data(event) class_name = self.class.name - class_name.gsub!(/::/, '') + class_name.gsub!(%r{::}, '') { message: { diff --git a/app/models/concerns/has_rich_text.rb b/app/models/concerns/has_rich_text.rb index 7015239c5..e4fd1d30c 100644 --- a/app/models/concerns/has_rich_text.rb +++ b/app/models/concerns/has_rich_text.rb @@ -58,7 +58,7 @@ Checks if file is used inline node.remove when 'div' - node.children.to_a.select { |t| t.text.match?(/\A([\n\r]+)\z/) }.each(&:remove) + node.children.to_a.select { |t| t.text.match?(%r{\A([\n\r]+)\z}) }.each(&:remove) node.remove if node.children.none? && node.classes.none? end @@ -138,7 +138,7 @@ Checks if file is used inline next if node.name != 'img' next if !node['src']&.start_with?('cid:') - cid = node['src'].sub(/^cid:/, '') + cid = node['src'].sub(%r{^cid:}, '') lookup_cids = [cid, "<#{cid}>"] attachment = attachments.find do |file| @@ -164,7 +164,7 @@ Checks if file is used inline next if node.name != 'img' next if !node['src']&.start_with? 'cid:' - cid = node['src'].sub(/^cid:/, '') + cid = node['src'].sub(%r{^cid:}, '') inline_cids << cid end diff --git a/app/models/cti/caller_id.rb b/app/models/cti/caller_id.rb index e865b08b8..583dae415 100644 --- a/app/models/cti/caller_id.rb +++ b/app/models/cti/caller_id.rb @@ -226,19 +226,19 @@ returns # see specs for example return [] if !text.is_a?(String) - text.scan(/([\d\s\-(|)]{6,26})/).map do |match| + text.scan(%r{([\d\s\-(|)]{6,26})}).map do |match| normalize_number(match[0]) end end def self.normalize_number(number) - number = number.gsub(/[\s-]/, '') - number.gsub!(/^(00)?(\+?\d\d)\(0?(\d*)\)/, '\\1\\2\\3') - number.gsub!(/\D/, '') + number = number.gsub(%r{[\s-]}, '') + number.gsub!(%r{^(00)?(\+?\d\d)\(0?(\d*)\)}, '\\1\\2\\3') + number.gsub!(%r{\D}, '') case number - when /^00/ + when %r{^00} number[2..] - when /^0/ + when %r{^0} DEFAULT_COUNTRY_ID + number[1..] else number diff --git a/app/models/cti/driver/base.rb b/app/models/cti/driver/base.rb index f378463a3..4e796d49a 100644 --- a/app/models/cti/driver/base.rb +++ b/app/models/cti/driver/base.rb @@ -97,8 +97,8 @@ class Cti::Driver::Base if routing_table.present? routing_table.each do |row| - dest = row[:dest].gsub(/\*/, '.+?') - next if !to.match?(/^#{dest}$/) + dest = row[:dest].gsub(%r{\*}, '.+?') + next if !to.match?(%r{^#{dest}$}) return { action: 'set_caller_id', diff --git a/app/models/cti/log.rb b/app/models/cti/log.rb index 21fdc64c3..6b8a5d178 100644 --- a/app/models/cti/log.rb +++ b/app/models/cti/log.rb @@ -6,7 +6,7 @@ module Cti store :preferences, accessors: %i[from_pretty to_pretty] - validates :state, format: { with: /\A(newCall|answer|hangup)\z/,  message: 'newCall|answer|hangup is allowed' } + validates :state, format: { with: %r{\A(newCall|answer|hangup)\z},  message: 'newCall|answer|hangup is allowed' } before_create :set_pretty before_update :set_pretty @@ -506,7 +506,7 @@ optional you can put the max oldest chat entries as argument def set_pretty %i[from to].each do |field| - parsed = TelephoneNumber.parse(send(field)&.sub(/^\+?/, '+')) + parsed = TelephoneNumber.parse(send(field)&.sub(%r{^\+?}, '+')) preferences[:"#{field}_pretty"] = parsed.send(parsed.valid? ? :international_number : :original_number) end end diff --git a/app/models/job.rb b/app/models/job.rb index d7982bbc0..496182b52 100644 --- a/app/models/job.rb +++ b/app/models/job.rb @@ -264,7 +264,7 @@ job.run(true) def match_minutes(minutes) return 0 if minutes < 10 - "#{minutes.to_s.gsub(/(\d)\d/, '\\1')}0".to_i + "#{minutes.to_s.gsub(%r{(\d)\d}, '\\1')}0".to_i end end diff --git a/app/models/object_manager/attribute.rb b/app/models/object_manager/attribute.rb index 969531957..9f4e5054e 100644 --- a/app/models/object_manager/attribute.rb +++ b/app/models/object_manager/attribute.rb @@ -569,22 +569,22 @@ to send no browser reload event, pass false data_type = nil case attribute.data_type - when /^input|select|tree_select|richtext|textarea|checkbox$/ + when %r{^input|select|tree_select|richtext|textarea|checkbox$} data_type = :string - when /^integer|user_autocompletion$/ + when %r{^integer|user_autocompletion$} data_type = :integer - when /^boolean|active$/ + when %r{^boolean|active$} data_type = :boolean - when /^datetime$/ + when %r{^datetime$} data_type = :datetime - when /^date$/ + when %r{^date$} data_type = :date end # change field if model.column_names.include?(attribute.name) case attribute.data_type - when /^input|select|tree_select|richtext|textarea|checkbox$/ + when %r{^input|select|tree_select|richtext|textarea|checkbox$} ActiveRecord::Migration.change_column( model.table_name, attribute.name, @@ -592,7 +592,7 @@ to send no browser reload event, pass false limit: attribute.data_option[:maxlength], null: true ) - when /^integer|user_autocompletion|datetime|date$/, /^boolean|active$/ + when %r{^integer|user_autocompletion|datetime|date$}, %r{^boolean|active$} ActiveRecord::Migration.change_column( model.table_name, attribute.name, @@ -616,7 +616,7 @@ to send no browser reload event, pass false # create field case attribute.data_type - when /^input|select|tree_select|richtext|textarea|checkbox$/ + when %r{^input|select|tree_select|richtext|textarea|checkbox$} ActiveRecord::Migration.add_column( model.table_name, attribute.name, @@ -624,7 +624,7 @@ to send no browser reload event, pass false limit: attribute.data_option[:maxlength], null: true ) - when /^integer|user_autocompletion$/, /^boolean|active$/, /^datetime|date$/ + when %r{^integer|user_autocompletion$}, %r{^boolean|active$}, %r{^datetime|date$} ActiveRecord::Migration.add_column( model.table_name, attribute.name, @@ -780,22 +780,22 @@ is certain attribute used by triggers, overviews or schedulers def check_name return if !name - if name.match?(/.+?_(id|ids)$/i) + if name.match?(%r{.+?_(id|ids)$}i) errors.add(:name, "can't get used because *_id and *_ids are not allowed") end - if name.match?(/\s/) + if name.match?(%r{\s}) errors.add(:name, 'spaces are not allowed') end - if !name.match?(/^[a-z0-9_]+$/) + if !name.match?(%r{^[a-z0-9_]+$}) errors.add(:name, 'Only letters from a-z because numbers from 0-9 and _ are allowed') end - if !name.match?(/[a-z]/) + if !name.match?(%r{[a-z]}) errors.add(:name, 'At least one letters is needed') end # do not allow model method names as attributes reserved_words = %w[destroy true false integer select drop create alter index table varchar blob date datetime timestamp url icon initials avatar permission validate subscribe unsubscribe translate search _type _doc _id id] - if name.match?(/^(#{reserved_words.join('|')})$/) + if name.match?(%r{^(#{reserved_words.join('|')})$}) errors.add(:name, "#{name} is a reserved word! (1)") end @@ -833,7 +833,7 @@ is certain attribute used by triggers, overviews or schedulers local_data_option[:null] = true if local_data_option[:null].nil? case data_type - when /^((tree_)?select|checkbox)$/ + when %r{^((tree_)?select|checkbox)$} local_data_option[:nulloption] = true if local_data_option[:nulloption].nil? local_data_option[:maxlength] ||= 255 end @@ -882,17 +882,17 @@ is certain attribute used by triggers, overviews or schedulers when 'input' [{ failed: %w[text password tel fax email url].exclude?(local_data_option[:type]), message: 'must have one of text/password/tel/fax/email/url for :type' }, - { failed: !local_data_option[:maxlength].to_s.match?(/^\d+$/), + { failed: !local_data_option[:maxlength].to_s.match?(%r{^\d+$}), message: 'must have integer for :maxlength' }] when 'richtext' - [{ failed: !local_data_option[:maxlength].to_s.match?(/^\d+$/), + [{ failed: !local_data_option[:maxlength].to_s.match?(%r{^\d+$}), message: 'must have integer for :maxlength' }] when 'integer' - [{ failed: !local_data_option[:min].to_s.match?(/^\d+$/), + [{ failed: !local_data_option[:min].to_s.match?(%r{^\d+$}), message: 'must have integer for :min' }, - { failed: !local_data_option[:max].to_s.match?(/^\d+$/), + { failed: !local_data_option[:max].to_s.match?(%r{^\d+$}), message: 'must have integer for :max' }] - when /^((tree_)?select|checkbox)$/ + when %r{^((tree_)?select|checkbox)$} [{ failed: !local_data_option.key?(:default), message: 'must have value for :default' }, { failed: local_data_option[:options].nil? && local_data_option[:relation].nil?, diff --git a/app/models/organization.rb b/app/models/organization.rb index 9ac1ce3a8..b0afaefcf 100644 --- a/app/models/organization.rb +++ b/app/models/organization.rb @@ -38,8 +38,8 @@ class Organization < ApplicationModel def domain_cleanup return true if domain.blank? - domain.gsub!(/@/, '') - domain.gsub!(/\s*/, '') + domain.gsub!(%r{@}, '') + domain.gsub!(%r{\s*}, '') domain.strip! domain.downcase! true diff --git a/app/models/overview.rb b/app/models/overview.rb index d3f119b5f..2a3a6b209 100644 --- a/app/models/overview.rb +++ b/app/models/overview.rb @@ -98,7 +98,7 @@ class Overview < ApplicationModel def link_name(name) local_link = name.downcase local_link = local_link.parameterize(separator: '_') - local_link.gsub!(/\s/, '_') + local_link.gsub!(%r{\s}, '_') local_link.squeeze!('_') local_link = CGI.escape(local_link) if local_link.blank? diff --git a/app/models/package.rb b/app/models/package.rb index 98e333f22..8fe84021b 100644 --- a/app/models/package.rb +++ b/app/models/package.rb @@ -64,7 +64,7 @@ install all packages located under auto_install/*.zpm data = [] Dir.foreach(path) do |entry| - if entry.include?('.zpm') && entry !~ /^\./ + if entry.include?('.zpm') && entry !~ %r{^\.} data.push entry end end @@ -133,7 +133,7 @@ execute migration down + unlink files Dir.glob("#{package_base_dir}/**/*") do |entry| entry = entry.sub('//', '/') file = entry - file = file.sub(/#{package_base_dir}/, '') + file = file.sub(%r{#{package_base_dir}}, '') dest = "#{@@root}/#{file}" if File.symlink?(dest.to_s) @@ -166,7 +166,7 @@ link files + execute migration up Dir.glob("#{package_base_dir}/**/*") do |entry| entry = entry.sub('//', '/') file = entry - file = file.sub(/#{package_base_dir}/, '') + file = file.sub(%r{#{package_base_dir}}, '') file = file.sub(%r{^/}, '') # ignore files diff --git a/app/models/package/migration.rb b/app/models/package/migration.rb index 5d3689435..6dbeeeb82 100644 --- a/app/models/package/migration.rb +++ b/app/models/package/migration.rb @@ -41,7 +41,7 @@ class Package::Migration < ApplicationModel version = nil name = nil - if migration =~ /^(.+?)_(.*)\.rb$/ + if migration =~ %r{^(.+?)_(.*)\.rb$} version = $1 name = $2 end diff --git a/app/models/postmaster_filter.rb b/app/models/postmaster_filter.rb index da110f1a4..3116bfa8c 100644 --- a/app/models/postmaster_filter.rb +++ b/app/models/postmaster_filter.rb @@ -12,7 +12,7 @@ class PostmasterFilter < ApplicationModel raise Exceptions::UnprocessableEntity, 'Min. one match rule needed!' if match.blank? 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, 'operator invalid, ony "contains" and "contains not" is supported' if meta['operator'].blank? || meta['operator'] !~ %r{^(contains|contains not)$} raise Exceptions::UnprocessableEntity, 'value invalid/empty' if meta['value'].blank? begin diff --git a/app/models/setting.rb b/app/models/setting.rb index a3a2658f5..46094e8da 100644 --- a/app/models/setting.rb +++ b/app/models/setting.rb @@ -120,7 +120,7 @@ reload config settings @@current[key] = value next end - @@current[key] = value.gsub(/\#\{config\.(.+?)\}/) do + @@current[key] = value.gsub(%r{\#\{config\.(.+?)\}}) do @@raw[$1].to_s end end diff --git a/app/models/smime_certificate.rb b/app/models/smime_certificate.rb index ed9efcaef..d121fc1fb 100644 --- a/app/models/smime_certificate.rb +++ b/app/models/smime_certificate.rb @@ -4,7 +4,7 @@ class SMIMECertificate < ApplicationModel validates :fingerprint, uniqueness: true def self.parse(raw) - OpenSSL::X509::Certificate.new(raw.gsub(/(?:TRUSTED\s)?(CERTIFICATE---)/, '\1')) + OpenSSL::X509::Certificate.new(raw.gsub(%r{(?:TRUSTED\s)?(CERTIFICATE---)}, '\1')) end # Search for the certificate of the given sender email address @@ -94,7 +94,7 @@ class SMIMECertificate < ApplicationModel def email_addresses_from_subject_alt_name(subject_alt_name) # ["IP Address:192.168.7.23", "IP Address:192.168.7.42", "email:jd@example.com", "email:John.Doe@example.com", "dirName:dir_sect"] - entries = subject_alt_name.value.split(/,\s?/) + entries = subject_alt_name.value.split(%r{,\s?}) entries.each_with_object([]) do |entry, result| # ["email:jd@example.com", "email:John.Doe@example.com"] diff --git a/app/models/text_module.rb b/app/models/text_module.rb index 024b82850..9dc3c53cb 100644 --- a/app/models/text_module.rb +++ b/app/models/text_module.rb @@ -114,9 +114,9 @@ push text_modules to online def validate_content return true if content.blank? - return true if content.match?(/<.+?>/) + return true if content.match?(%r{<.+?>}) - content.gsub!(/(\r\n|\n\r|\r)/, "\n") + content.gsub!(%r{(\r\n|\n\r|\r)}, "\n") self.content = content.text2html true end diff --git a/app/models/ticket.rb b/app/models/ticket.rb index c2519b245..04d0b50e7 100644 --- a/app/models/ticket.rb +++ b/app/models/ticket.rb @@ -627,7 +627,7 @@ condition example selector = selector_raw.stringify_keys raise "Invalid selector, operator missing #{selector.inspect}" if !selector['operator'] - raise "Invalid selector, operator #{selector['operator']} is invalid #{selector.inspect}" if !selector['operator'].match?(/^(is|is\snot|contains|contains\s(not|all|one|all\snot|one\snot)|(after|before)\s\(absolute\)|(within\snext|within\slast|after|before|till|from)\s\(relative\))|(is\sin\sworking\stime|is\snot\sin\sworking\stime)$/) + raise "Invalid selector, operator #{selector['operator']} is invalid #{selector.inspect}" if !selector['operator'].match?(%r{^(is|is\snot|contains|contains\s(not|all|one|all\snot|one\snot)|(after|before)\s\(absolute\)|(within\snext|within\slast|after|before|till|from)\s\(relative\))|(is\sin\sworking\stime|is\snot\sin\sworking\stime)$}) # validate value / allow blank but only if pre_condition exists and is not specific if !selector.key?('value') || @@ -639,7 +639,7 @@ condition example end # validate pre_condition values - return nil if selector['pre_condition'] && selector['pre_condition'] !~ /^(not_set|current_user\.|specific)/ + return nil if selector['pre_condition'] && selector['pre_condition'] !~ %r{^(not_set|current_user\.|specific)} # get attributes attributes = attribute.split('.') @@ -699,7 +699,7 @@ condition example if selector['operator'] == 'is' if selector['pre_condition'] == 'not_set' - if attributes[1].match?(/^(created_by|updated_by|owner|customer|user)_id/) + if attributes[1].match?(%r{^(created_by|updated_by|owner|customer|user)_id}) query += "(#{attribute} IS NULL OR #{attribute} IN (?))" bind_params.push 1 else @@ -744,7 +744,7 @@ condition example end elsif selector['operator'] == 'is not' if selector['pre_condition'] == 'not_set' - if attributes[1].match?(/^(created_by|updated_by|owner|customer|user)_id/) + if attributes[1].match?(%r{^(created_by|updated_by|owner|customer|user)_id}) query += "(#{attribute} IS NOT NULL AND #{attribute} NOT IN (?))" bind_params.push 1 else @@ -1444,7 +1444,7 @@ result def check_title return true if !title - title.gsub!(/\s|\t|\r/, ' ') + title.gsub!(%r{\s|\t|\r}, ' ') true end @@ -1476,7 +1476,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.match?(/^pending/i) + return true if current_state_type.name.match?(%r{^pending}i) self.pending_time = nil true @@ -1561,7 +1561,7 @@ result User.group_access(group_id, 'full').sort_by(&:login).each do |user| recipients_raw.push(user.email) end - when /\Auserid_(\d+)\z/ + when %r{\Auserid_(\d+)\z} user = User.lookup(id: $1) if !user logger.warn "Can't find configured Trigger Email recipient User with ID '#{$1}'" @@ -1592,7 +1592,7 @@ result end rescue if recipient_email.present? - if recipient_email !~ /^(.+?)<(.+?)@(.+?)>$/ + if recipient_email !~ %r{^(.+?)<(.+?)@(.+?)>$} next # no usable format found end @@ -1609,15 +1609,15 @@ result # 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.match?(/#{send_no_auto_response_reg_exp}/i) + next if recipient_email.match?(%r{#{send_no_auto_response_reg_exp}}i) rescue => e logger.error "Invalid regex '#{send_no_auto_response_reg_exp}' in setting send_no_auto_response_reg_exp" logger.error e - next if recipient_email.match?(/(mailer-daemon|postmaster|abuse|root|noreply|noreply.+?|no-reply|no-reply.+?)@.+?/i) + next if recipient_email.match?(%r{(mailer-daemon|postmaster|abuse|root|noreply|noreply.+?|no-reply|no-reply.+?)@.+?}i) end # check if notification should be send because of customer emails - if article.present? && article.preferences.fetch('is-auto-response', false) == true && article.from && article.from =~ /#{Regexp.quote(recipient_email)}/i + if article.present? && article.preferences.fetch('is-auto-response', false) == true && article.from && article.from =~ %r{#{Regexp.quote(recipient_email)}}i logger.info "Send no trigger based notification to #{recipient_email} because of auto response tagged incoming email" next end @@ -1812,7 +1812,7 @@ result owner_id when 'ticket_agents' User.group_access(group_id, 'full').sort_by(&:login) - when /\Auserid_(\d+)\z/ + when %r{\Auserid_(\d+)\z} return $1 if User.exists?($1) logger.warn "Can't find configured Trigger SMS recipient User with ID '#{$1}'" diff --git a/app/models/ticket/article.rb b/app/models/ticket/article.rb index 80429d63b..b9bb81ae4 100644 --- a/app/models/ticket/article.rb +++ b/app/models/ticket/article.rb @@ -85,10 +85,10 @@ returns def self.insert_urls(article) return article if article['attachments'].blank? return article if !article['content_type'].match?(%r{text/html}i) - return article if article['body'] !~ //im ) do |item| + article['body'].gsub!( %r{(}im ) do |item| tag_start = $1 cid = $3 tag_end = $4 @@ -129,7 +129,7 @@ returns def attachments_inline inline_attachments = {} - body.gsub( //im ) do |_item| + body.gsub( %r{}im ) do |_item| cid = $2 # look for attachment @@ -251,7 +251,7 @@ returns: return true if attribute != :body return false if content_type.blank? - content_type =~ /html/i + content_type =~ %r{html}i end =begin @@ -306,7 +306,7 @@ returns def check_subject return true if subject.blank? - subject.gsub!(/\s|\t|\r/, ' ') + subject.gsub!(%r{\s|\t|\r}, ' ') true end diff --git a/app/models/ticket/article/enqueue_communicate_telegram_job.rb b/app/models/ticket/article/enqueue_communicate_telegram_job.rb index ba24a4599..d896970eb 100644 --- a/app/models/ticket/article/enqueue_communicate_telegram_job.rb +++ b/app/models/ticket/article/enqueue_communicate_telegram_job.rb @@ -26,7 +26,7 @@ module Ticket::Article::EnqueueCommunicateTelegramJob return true if !type_id type = Ticket::Article::Type.lookup(id: type_id) - return true if !type.name.match?(/\Atelegram/i) + return true if !type.name.match?(%r{\Atelegram}i) CommunicateTelegramJob.perform_later(id) end diff --git a/app/models/ticket/article/enqueue_communicate_twitter_job.rb b/app/models/ticket/article/enqueue_communicate_twitter_job.rb index 2c55ba376..5c37f722c 100644 --- a/app/models/ticket/article/enqueue_communicate_twitter_job.rb +++ b/app/models/ticket/article/enqueue_communicate_twitter_job.rb @@ -31,7 +31,7 @@ module Ticket::Article::EnqueueCommunicateTwitterJob type = Ticket::Article::Type.lookup(id: type_id) return true if type.nil? - return true if !type.name.match?(/\Atwitter/i) + return true if !type.name.match?(%r{\Atwitter}i) raise Exceptions::UnprocessableEntity, 'twitter to: parameter is missing' if to.blank? && type['name'] == 'twitter direct-message' diff --git a/app/models/ticket/number/date.rb b/app/models/ticket/number/date.rb index 5f1f3338b..7a44d9645 100644 --- a/app/models/ticket/number/date.rb +++ b/app/models/ticket/number/date.rb @@ -40,12 +40,12 @@ module Ticket::Number::Date # probe format # NOTE: we use `(?<=\W|^)` at the start of the regular expressions below # because `\b` fails when ticket_hook begins with a non-word character (like '#') - string.scan(/(?<=\W|^)#{Regexp.quote(ticket_hook)}#{Regexp.quote(ticket_hook_divider)}(\d{4,10}#{system_id}\d{2,40})\b/i) do + string.scan(%r{(?<=\W|^)#{Regexp.quote(ticket_hook)}#{Regexp.quote(ticket_hook_divider)}(\d{4,10}#{system_id}\d{2,40})\b}i) do ticket = Ticket.find_by(number: $1) break if ticket end if !ticket - string.scan(/(?<=\W|^)#{Regexp.quote(ticket_hook)}\s{0,2}(\d{4,10}#{system_id}\d{2,40})\b/i) do + string.scan(%r{(?<=\W|^)#{Regexp.quote(ticket_hook)}\s{0,2}(\d{4,10}#{system_id}\d{2,40})\b}i) do ticket = Ticket.find_by(number: $1) break if ticket end diff --git a/app/models/ticket/number/increment.rb b/app/models/ticket/number/increment.rb index 0db856caf..96747ee91 100644 --- a/app/models/ticket/number/increment.rb +++ b/app/models/ticket/number/increment.rb @@ -38,13 +38,13 @@ module Ticket::Number::Increment # probe format # NOTE: we use `(?<=\W|^)` at the start of the regular expressions below # because `\b` fails when ticket_hook begins with a non-word character (like '#') - string.scan(/(?<=\W|^)#{Regexp.quote(ticket_hook)}#{Regexp.quote(ticket_hook_divider)}(#{system_id}\d{2,48})\b/i) do + string.scan(%r{(?<=\W|^)#{Regexp.quote(ticket_hook)}#{Regexp.quote(ticket_hook_divider)}(#{system_id}\d{2,48})\b}i) do ticket = Ticket.find_by(number: $1) break if ticket end if !ticket - string.scan(/(?<=\W|^)#{Regexp.quote(ticket_hook)}\s{0,2}(#{system_id}\d{2,48})\b/i) do + string.scan(%r{(?<=\W|^)#{Regexp.quote(ticket_hook)}\s{0,2}(#{system_id}\d{2,48})\b}i) do ticket = Ticket.find_by(number: $1) break if ticket end diff --git a/app/models/ticket/overviews.rb b/app/models/ticket/overviews.rb index 7e7072213..a24627a41 100644 --- a/app/models/ticket/overviews.rb +++ b/app/models/ticket/overviews.rb @@ -103,7 +103,7 @@ returns order_by = overview.order[:by] # validate direction - raise "Invalid order direction '#{direction}'" if direction && direction !~ /^(ASC|DESC)$/i + raise "Invalid order direction '#{direction}'" if direction && direction !~ %r{^(ASC|DESC)$}i # check if order by exists if !ticket_attributes.key?(order_by) diff --git a/app/models/ticket/search_index.rb b/app/models/ticket/search_index.rb index c33a91805..2aa3b51a9 100644 --- a/app/models/ticket/search_index.rb +++ b/app/models/ticket/search_index.rb @@ -98,7 +98,7 @@ module Ticket::SearchIndex return true if attachment.filename.blank? filename_extention = attachment.filename.downcase - filename_extention.gsub!(/^.*(\..+?)$/, '\\1') + filename_extention.gsub!(%r{^.*(\..+?)$}, '\\1') # list ignored file extensions attachments_ignore = Setting.get('es_attachment_ignore') || [ '.png', '.jpg', '.jpeg', '.mpeg', '.mpg', '.mov', '.bin', '.exe' ] diff --git a/app/models/ticket/subject.rb b/app/models/ticket/subject.rb index 802b688c2..0d85481c8 100644 --- a/app/models/ticket/subject.rb +++ b/app/models/ticket/subject.rb @@ -57,17 +57,17 @@ returns ticket_subject_size = Setting.get('ticket_subject_size') # remove all possible ticket hook formats with [] - subject = subject.gsub(/\[#{ticket_hook}: #{number}\](\s+?|)/, '') - subject = subject.gsub(/\[#{ticket_hook}:#{number}\](\s+?|)/, '') - subject = subject.gsub(/\[#{ticket_hook}#{ticket_hook_divider}#{number}\](\s+?|)/, '') + subject = subject.gsub(%r{\[#{ticket_hook}: #{number}\](\s+?|)}, '') + subject = subject.gsub(%r{\[#{ticket_hook}:#{number}\](\s+?|)}, '') + subject = subject.gsub(%r{\[#{ticket_hook}#{ticket_hook_divider}#{number}\](\s+?|)}, '') # remove all possible ticket hook formats without [] - subject = subject.gsub(/#{ticket_hook}: #{number}(\s+?|)/, '') - subject = subject.gsub(/#{ticket_hook}:#{number}(\s+?|)/, '') - subject = subject.gsub(/#{ticket_hook}#{ticket_hook_divider}#{number}(\s+?|)/, '') + subject = subject.gsub(%r{#{ticket_hook}: #{number}(\s+?|)}, '') + subject = subject.gsub(%r{#{ticket_hook}:#{number}(\s+?|)}, '') + subject = subject.gsub(%r{#{ticket_hook}#{ticket_hook_divider}#{number}(\s+?|)}, '') # remove leading "..:\s" and "..[\d+]:\s" e. g. "Re: " or "Re[5]: " - subject = subject.gsub(/^(..(\[\d+\])?:\s)+/, '') + subject = subject.gsub(%r{^(..(\[\d+\])?:\s)+}, '') # resize subject based on config if subject.length > ticket_subject_size.to_i diff --git a/app/models/transaction/slack.rb b/app/models/transaction/slack.rb index 9225247a1..268574941 100644 --- a/app/models/transaction/slack.rb +++ b/app/models/transaction/slack.rb @@ -106,7 +106,7 @@ class Transaction::Slack if ticket.pending_time && ticket.pending_time < Time.zone.now color = '#faab00' end - elsif ticket_state_type.match?(/^(new|open)$/) + elsif ticket_state_type.match?(%r{^(new|open)$}) color = '#faab00' elsif ticket_state_type == 'closed' color = '#38ad69' diff --git a/app/models/translation.rb b/app/models/translation.rb index 53260d211..8431e1071 100644 --- a/app/models/translation.rb +++ b/app/models/translation.rb @@ -416,7 +416,7 @@ Get source file at https://i18n.zammad.com/api/v1/translations_empty_translation next end raise "Can't import translation, format is missing" if row[2].blank? - raise "Can't import translation, format is invalid (#{row[2]})" if !row[2].match?(/^(time|string)$/) + raise "Can't import translation, format is invalid (#{row[2]})" if !row[2].match?(%r{^(time|string)$}) item = { 'locale' => locale.locale, diff --git a/app/models/user.rb b/app/models/user.rb index 8eb1421e0..167855710 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -841,7 +841,7 @@ try to find correct name end # "Firstname Lastname" - if string =~ /^(((Dr\.|Prof\.)[[:space:]]|).+?)[[:space:]](.+?)$/i + if string =~ %r{^(((Dr\.|Prof\.)[[:space:]]|).+?)[[:space:]](.+?)$}i if $1.present? firstname = $1.strip end @@ -853,7 +853,7 @@ try to find correct name # -no name- "firstname.lastname@example.com" if string.blank? && email.present? - scan = email.scan(/^(.+?)\.(.+?)@.+?$/) + scan = email.scan(%r{^(.+?)\.(.+?)@.+?$}) if scan[0].present? if scan[0][0].present? firstname = scan[0][0].strip @@ -900,10 +900,10 @@ try to find correct name self.firstname = local_firstname if local_firstname.present? self.lastname = local_lastname if local_lastname.present? - if firstname.present? && firstname.match(/^[A-z]+$/) && (firstname.downcase == firstname || firstname.upcase == firstname) + if firstname.present? && firstname.match(%r{^[A-z]+$}) && (firstname.downcase == firstname || firstname.upcase == firstname) firstname.capitalize! end - if lastname.present? && lastname.match(/^[A-z]+$/) && (lastname.downcase == lastname || lastname.upcase == lastname) + if lastname.present? && lastname.match(%r{^[A-z]+$}) && (lastname.downcase == lastname || lastname.upcase == lastname) lastname.capitalize! end true diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb index ab5925cb1..1b3424958 100644 --- a/config/initializers/inflections.rb +++ b/config/initializers/inflections.rb @@ -19,7 +19,7 @@ ActiveSupport::Inflector.inflections(:en) do |inflect| # Rails thinks the singularized version of knowledge_bases is knowledge_basis?! # see: KnowledgeBase.table_name.singularize - inflect.singular(/(knowledge_base)s$/i, '\1') + inflect.singular(%r{(knowledge_base)s$}i, '\1') inflect.acronym 'SMIME' inflect.acronym 'GitLab' inflect.acronym 'GitHub' diff --git a/config/routes/http_log.rb b/config/routes/http_log.rb index 0258934e0..2878ff806 100644 --- a/config/routes/http_log.rb +++ b/config/routes/http_log.rb @@ -2,7 +2,7 @@ Zammad::Application.routes.draw do api_path = Rails.configuration.api_path match api_path + '/http_logs', to: 'http_logs#index', via: :get - match api_path + '/http_logs/:facility', to: 'http_logs#index', via: :get, constraints: { facility: /.*/ } + match api_path + '/http_logs/:facility', to: 'http_logs#index', via: :get, constraints: { facility: %r{.*} } match api_path + '/http_logs', to: 'http_logs#create', via: :post end diff --git a/lib/calendar_subscriptions.rb b/lib/calendar_subscriptions.rb index 06689f10c..6c6a26575 100644 --- a/lib/calendar_subscriptions.rb +++ b/lib/calendar_subscriptions.rb @@ -9,7 +9,7 @@ class CalendarSubscriptions default_preferences = Setting.where(area: 'Defaults::CalendarSubscriptions') default_preferences.each do |calendar_subscription| - next if calendar_subscription.name !~ /\Adefaults_calendar_subscriptions_(.*)\z/ + next if calendar_subscription.name !~ %r{\Adefaults_calendar_subscriptions_(.*)\z} object_name = $1 # rubocop:disable Lint/OutOfRangeRegexpRef @preferences[ object_name ] = calendar_subscription.state_current[:value] diff --git a/lib/color_validator.rb b/lib/color_validator.rb index 000c29f3c..b7add5b5b 100644 --- a/lib/color_validator.rb +++ b/lib/color_validator.rb @@ -1,8 +1,8 @@ class ColorValidator < ActiveModel::EachValidator REGEXP = { - RGB: /^rgb\((((((((1?[1-9]?\d)|10\d|(2[0-4]\d)|25[0-5]),\s?)){2}|((((1?[1-9]?\d)|10\d|(2[0-4]\d)|25[0-5])\s)){2})((1?[1-9]?\d)|10\d|(2[0-4]\d)|25[0-5]))|((((([1-9]?\d(\.\d+)?)|100|(\.\d+))%,\s?){2}|((([1-9]?\d(\.\d+)?)|100|(\.\d+))%\s){2})(([1-9]?\d(\.\d+)?)|100|(\.\d+))%))\)$/i, - HSL: /^hsl\(((((([12]?[1-9]?\d)|[12]0\d|(3[0-6]\d))(\.\d+)?)|(\.\d+))(deg)?|(0|0?\.\d+)turn|(([0-6](\.\d+)?)|(\.\d+))rad)((,\s?(([1-9]?\d(\.\d+)?)|100|(\.\d+))%){2}|(\s(([1-9]?\d(\.\d+)?)|100|(\.\d+))%){2})\)$/i, - HEX: /^#([\da-f]{3}){1,2}$/i + RGB: %r{^rgb\((((((((1?[1-9]?\d)|10\d|(2[0-4]\d)|25[0-5]),\s?)){2}|((((1?[1-9]?\d)|10\d|(2[0-4]\d)|25[0-5])\s)){2})((1?[1-9]?\d)|10\d|(2[0-4]\d)|25[0-5]))|((((([1-9]?\d(\.\d+)?)|100|(\.\d+))%,\s?){2}|((([1-9]?\d(\.\d+)?)|100|(\.\d+))%\s){2})(([1-9]?\d(\.\d+)?)|100|(\.\d+))%))\)$}i, + HSL: %r{^hsl\(((((([12]?[1-9]?\d)|[12]0\d|(3[0-6]\d))(\.\d+)?)|(\.\d+))(deg)?|(0|0?\.\d+)turn|(([0-6](\.\d+)?)|(\.\d+))rad)((,\s?(([1-9]?\d(\.\d+)?)|100|(\.\d+))%){2}|(\s(([1-9]?\d(\.\d+)?)|100|(\.\d+))%){2})\)$}i, + HEX: %r{^#([\da-f]{3}){1,2}$}i }.freeze def validate_each(record, attribute, value) diff --git a/lib/core_ext/active_record/connection_adapters/postgresql/schema_statements.rb b/lib/core_ext/active_record/connection_adapters/postgresql/schema_statements.rb index ae9bc6ee2..442b7a286 100644 --- a/lib/core_ext/active_record/connection_adapters/postgresql/schema_statements.rb +++ b/lib/core_ext/active_record/connection_adapters/postgresql/schema_statements.rb @@ -13,7 +13,7 @@ module ActiveRecord if column_names.instance_of?(Array) index_columns_new = [] column_names.each do |i| - if i =~ /^"(name|login|locale|alias)"$/ || i.end_with?('name"') + if i =~ %r{^"(name|login|locale|alias)"$} || i.end_with?('name"') index_columns_new.push "LOWER(#{i})" else index_columns_new.push i diff --git a/lib/core_ext/class.rb b/lib/core_ext/class.rb index be4a97a5e..afe75550c 100644 --- a/lib/core_ext/class.rb +++ b/lib/core_ext/class.rb @@ -1,15 +1,15 @@ class Class def to_app_model_url @to_app_model_url ||= begin - to_s.gsub(/::/, '_') - .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') - .gsub(/([a-z\d])([A-Z])/, '\1_\2') + to_s.gsub(%r{::}, '_') + .gsub(%r{([A-Z]+)([A-Z][a-z])}, '\1_\2') + .gsub(%r{([a-z\d])([A-Z])}, '\1_\2') .tr('-', '_') .downcase end end def to_app_model - @to_app_model ||= to_s.gsub(/::/, '').to_sym + @to_app_model ||= to_s.gsub(%r{::}, '').to_sym end end diff --git a/lib/core_ext/string.rb b/lib/core_ext/string.rb index 4adfa75bd..3c9efa5ab 100644 --- a/lib/core_ext/string.rb +++ b/lib/core_ext/string.rb @@ -6,8 +6,8 @@ class String def strip! begin - sub!(/\A[[[:space:]]\u{200B}\u{FEFF}]+/, '') - sub!(/[[[:space:]]\u{200B}\u{FEFF}]+\Z/, '') + sub!(%r{\A[[[:space:]]\u{200B}\u{FEFF}]+}, '') + sub!(%r{[[[:space:]]\u{200B}\u{FEFF}]+\Z}, '') # if incompatible encoding regexp match (UTF-8 regexp with ASCII-8BIT string) (Encoding::CompatibilityError), use default rescue Encoding::CompatibilityError @@ -18,8 +18,8 @@ class String def strip begin - new_string = sub(/\A[[[:space:]]\u{200B}\u{FEFF}]+/, '') - new_string.sub!(/[[[:space:]]\u{200B}\u{FEFF}]+\Z/, '') + new_string = sub(%r{\A[[[:space:]]\u{200B}\u{FEFF}]+}, '') + new_string.sub!(%r{[[[:space:]]\u{200B}\u{FEFF}]+\Z}, '') # if incompatible encoding regexp match (UTF-8 regexp with ASCII-8BIT string) (Encoding::CompatibilityError), use default rescue Encoding::CompatibilityError @@ -46,7 +46,7 @@ class String lines = self lines.split("\n").collect do |line| - line.length > options[:line_width] ? line.gsub(/(.{1,#{options[:line_width]}})(\s+|$)/, "\\1\n").strip : line + line.length > options[:line_width] ? line.gsub(%r{(.{1,#{options[:line_width]}})(\s+|$)}, "\\1\n").strip : line end * "\n" end @@ -61,9 +61,9 @@ class String def to_filename camel_cased_word = dup - camel_cased_word.gsub(/::/, '/') - .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') - .gsub(/([a-z\d])([A-Z])/, '\1_\2') + camel_cased_word.gsub(%r{::}, '/') + .gsub(%r{([A-Z]+)([A-Z][a-z])}, '\1_\2') + .gsub(%r{([a-z\d])([A-Z])}, '\1_\2') .tr('-', '_').downcase end @@ -119,7 +119,7 @@ class String end # remove html comments - string.gsub!(//m, '') + string.gsub!(%r{}m, '') # find and replace it with [x] link_list = '' @@ -128,7 +128,7 @@ class String string.gsub!(%r{]*)>(.+?)<[[:space:]]*/a[[:space:]]*>}mxi) do |_placeholder| link = $3 text = $6 - text.gsub!(/<.+?>/, '') + text.gsub!(%r{<.+?>}, '') link_compare = link.dup if link_compare.present? @@ -147,18 +147,18 @@ class String if link_compare.present? && text_compare.blank? link - elsif (link_compare.blank? && text_compare.present?) || (link_compare && link_compare =~ /^mailto/i) + elsif (link_compare.blank? && text_compare.present?) || (link_compare && link_compare =~ %r{^mailto}i) text 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/ + elsif text !~ %r{^http} "#{text} (######LINKRAW:#{link}######)" else "#{link} (######LINKRAW:#{text}######)" end end - elsif string.scan(//ix) do + elsif string.scan(%r{}ix) do link = $2 counter = counter + 1 link_list += "[#{counter}] #{link}\n" @@ -170,35 +170,35 @@ class String string.gsub!(%r{(.+?)}im, '') # remove empty lines - string.gsub!(/^[[:space:]]*/m, '') + string.gsub!(%r{^[[:space:]]*}m, '') if strict string.gsub!(%r{< [[:space:]]* (/*) [[:space:]]* (b|i|ul|ol|li|u|h1|h2|h3|hr) ([[:space:]]*|[[:space:]]+[^>]*) >}mxi, '######\1\2######') end # pre/code handling 1/2 string.gsub!(%r{
(.+?)
}m) do |placeholder| - placeholder.gsub(/\n/, '###BR###') + placeholder.gsub(%r{\n}, '###BR###') end string.gsub!(%r{(.+?)}m) do |placeholder| - placeholder.gsub(/\n/, '###BR###') + placeholder.gsub(%r{\n}, '###BR###') end # insert spaces on [A-z]\n[A-z] - string.gsub!(/([A-z])[[:space:]]([A-z])/m, '\1 \2') + string.gsub!(%r{([A-z])[[:space:]]([A-z])}m, '\1 \2') # remove all new lines - string.gsub!(/(\n\r|\r\r\n|\r\n|\n)/, '') + string.gsub!(%r{(\n\r|\r\r\n|\r\n|\n)}, '') # blockquote handling string.gsub!(%r{]*)>(.+?)
}m) do - "\n#{$2.html2text(true).gsub(/^(.*)$/, '> \1')}\n" + "\n#{$2.html2text(true).gsub(%r{^(.*)$}, '> \1')}\n" end # pre/code handling 2/2 - string.gsub!(/###BR###/, "\n") + string.gsub!(%r{###BR###}, "\n") # add counting - string.gsub!(/]*)>/i, "\n* ") + string.gsub!(%r{]*)>}i, "\n* ") # add hr string.gsub!(%r{]*)>}i, "\n___\n") @@ -214,10 +214,10 @@ class String string.gsub!(%r{}i, ' ') # strip all other tags - string.gsub!(/<.+?>/, '') + string.gsub!(%r{<.+?>}, '') # replace multiple spaces with one - string.gsub!(/ /, ' ') + string.gsub!(%r{ }, ' ') # add hyperlinks if strict @@ -225,11 +225,11 @@ class String pre = $1 content = $2 post = $5 - if content.match?(/^www/i) + if content.match?(%r{^www}i) content = "http://#{content}" end - if content =~ /^(http|https|ftp|tel)/i + if content =~ %r{^(http|https|ftp|tel)}i "#{pre}######LINKRAW:#{content}#######{post}" else "#{pre}#{content}#{post}" @@ -250,12 +250,12 @@ class String string.gsub!(' ', ' ') # encode html entities like "–" - string.gsub!(/(&\#(\d+);?)/x) do + string.gsub!(%r{(&\#(\d+);?)}x) do $2.chr end # encode html entities like "d;" - string.gsub!(/(&\#[xX]([0-9a-fA-F]+);?)/x) do + string.gsub!(%r{(&\#[xX]([0-9a-fA-F]+);?)}x) do chr_orig = $1 hex = $2.hex if hex @@ -283,10 +283,10 @@ class String string = string.utf8_encode(fallback: :read_as_sanitized_binary) # remove tailing empty spaces - string.gsub!(/[[:blank:]]+$/, '') + string.gsub!(%r{[[:blank:]]+$}, '') # remove double multiple empty lines - string.gsub!(/\n\n\n+/, "\n\n") + string.gsub!(%r{\n\n\n+}, "\n\n") # add extracted links if link_list != '' @@ -294,7 +294,7 @@ class String end # remove double multiple empty lines - string.gsub!(/\n\n\n+/, "\n\n") + string.gsub!(%r{\n\n\n+}, "\n\n") string.strip end @@ -307,7 +307,7 @@ class String def text2html text = CGI.escapeHTML(self) - text.gsub!(/\n/, '
') + text.gsub!(%r{\n}, '
') text.chomp end @@ -327,8 +327,8 @@ class String string = html2text.text2html string.signature_identify('text') marker_template = '' - string.sub!(/######SIGNATURE_MARKER######/, marker_template) - string.gsub!(/######SIGNATURE_MARKER######/, '') + string.sub!(%r{######SIGNATURE_MARKER######}, marker_template) + string.gsub!(%r{######SIGNATURE_MARKER######}, '') return string.chomp end string.gsub!(%r{(

[[:space:]]*

([[:space:]]*)){2,}}im, '

 

\2') @@ -340,7 +340,7 @@ class String string.gsub!(%r{

[[:space:]]*

([[:space:]]*)+

[[:space:]]*

}im, '

') string.gsub!(%r\(
[[:space:]]*
[[:space:]]*){2,}\im, '
') string.gsub!(%r{
 
[[:space:]]*(
 
){1,}}im, '
 
') - string.gsub!(/(
[[:space:]]*){3,}/im, '

') + string.gsub!(%r{(
[[:space:]]*){3,}}im, '

') string.gsub!(%r\([[:space:]]*){3,}\im, '

') string.gsub!(%r{

[[:space:]]+

}im, '

 

') string.gsub!(%r{\A([[:space:]]*)*}i, '') @@ -350,8 +350,8 @@ class String string.signature_identify('html') marker_template = '' - string.sub!(/######SIGNATURE_MARKER######/, marker_template) - string.gsub!(/######SIGNATURE_MARKER######/, '') + string.sub!(%r{######SIGNATURE_MARKER######}, marker_template) + string.gsub!(%r{######SIGNATURE_MARKER######}, '') string.chomp end @@ -371,7 +371,7 @@ class String '[[:space:]]*
[[:space:]]*(On|Am|Le|El|Den|Dňa|W dniu|Il|Op|Dne|Dana)[[:space:]].{1,500} tags if node.is_a?(Nokogiri::XML::Text) && node.content.present? && node.content.include?(':') && node.ancestors.map(&:name).exclude?('a') urls = URI.extract(node.content, LINKABLE_URL_SCHEMES) - .map { |u| u.sub(/[,.]$/, '') } # URI::extract captures trailing dots/commas - .reject { |u| u.match?(/^[^:]+:$/) } # URI::extract will match, e.g., 'tel:' + .map { |u| u.sub(%r{[,.]$}, '') } # URI::extract captures trailing dots/commas + .reject { |u| u.match?(%r{^[^:]+:$}) } # URI::extract will match, e.g., 'tel:' next if urls.blank? @@ -170,14 +170,14 @@ satinize html string based on whiltelist # prepare links if node['href'] href = cleanup_target(node['href'], keep_spaces: true) - href_without_spaces = href.gsub(/[[:space:]]/, '') + href_without_spaces = href.gsub(%r{[[:space:]]}, '') if external && href_without_spaces.present? && !href_without_spaces.downcase.start_with?('mailto:') && !href_without_spaces.downcase.start_with?('//') && href_without_spaces.downcase !~ %r{^.{1,6}://.+?} node['href'] = "http://#{node['href']}" href = node['href'] - href_without_spaces = href.gsub(/[[:space:]]/, '') + href_without_spaces = href.gsub(%r{[[:space:]]}, '') end - next if !CGI.unescape(href_without_spaces).utf8_encode(fallback: :read_as_sanitized_binary).gsub(/[[:space:]]/, '').downcase.start_with?('http', 'ftp', '//') + next if !CGI.unescape(href_without_spaces).utf8_encode(fallback: :read_as_sanitized_binary).gsub(%r{[[:space:]]}, '').downcase.start_with?('http', 'ftp', '//') node.set_attribute('href', href) node.set_attribute('rel', 'nofollow noreferrer noopener') @@ -219,15 +219,15 @@ cleanup html string: def self.cleanup(string, timeout: true) Timeout.timeout(timeout ? PROCESSING_TIMEOUT : nil) do - string.gsub!(/<[A-z]:[A-z]>/, '') + string.gsub!(%r{<[A-z]:[A-z]>}, '') string.gsub!(%r{}, '') string.delete!("\t") # remove all new lines - string.gsub!(/(\n\r|\r\r\n|\r\n|\n)/, "\n") + string.gsub!(%r{(\n\r|\r\r\n|\r\n|\n)}, "\n") # remove double multiple empty lines - string.gsub!(/\n\n\n+/, "\n\n") + string.gsub!(%r{\n\n\n+}, "\n\n") string = cleanup_structure(string, 'pre') string = cleanup_structure(string) @@ -302,7 +302,7 @@ cleanup html string: content = node.content if content if content != ' ' && content != "\n" - content.gsub!(/[[:space:]]+/, ' ') + content.gsub!(%r{[[:space:]]+}, ' ') end if node.previous if node.previous.name == 'div' || node.previous.name == 'p' @@ -329,11 +329,11 @@ cleanup html string: end url = urls.shift - if content =~ /^(.*)#{Regexp.quote(url)}(.*)$/mx + if content =~ %r{^(.*)#{Regexp.quote(url)}(.*)$}mx pre = $1 post = $2 - if url.match?(/^www/i) + if url.match?(%r{^www}i) url = "http://#{url}" end @@ -367,11 +367,11 @@ cleanup html string: def self.cleanup_target(string, **options) cleaned_string = string.utf8_encode(fallback: :read_as_sanitized_binary) - cleaned_string = cleaned_string.gsub(/[[:space:]]/, '') if !options[:keep_spaces] + cleaned_string = cleaned_string.gsub(%r{[[:space:]]}, '') if !options[:keep_spaces] cleaned_string = cleaned_string.strip .delete("\t\n\r\u0000") .gsub(%r{/\*.*?\*/}, '') - .gsub(//, '') + .gsub(%r{}, '') sanitize_attachment_disposition(cleaned_string) end @@ -392,8 +392,8 @@ cleanup html string: end def self.url_same?(url_new, url_old) - url_new = CGI.unescape(url_new.to_s).utf8_encode(fallback: :read_as_sanitized_binary).downcase.delete_suffix('/').gsub(/[[:space:]]|\t|\n|\r/, '').strip - url_old = CGI.unescape(url_old.to_s).utf8_encode(fallback: :read_as_sanitized_binary).downcase.delete_suffix('/').gsub(/[[:space:]]|\t|\n|\r/, '').strip + url_new = CGI.unescape(url_new.to_s).utf8_encode(fallback: :read_as_sanitized_binary).downcase.delete_suffix('/').gsub(%r{[[:space:]]|\t|\n|\r}, '').strip + url_old = CGI.unescape(url_old.to_s).utf8_encode(fallback: :read_as_sanitized_binary).downcase.delete_suffix('/').gsub(%r{[[: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 @@ -460,7 +460,7 @@ satinize style of img tags if node['src'] style = 'max-width:100%;' if node['style'] - pears = node['style'].downcase.gsub(/\t|\n|\r/, '').split(';') + pears = node['style'].downcase.gsub(%r{\t|\n|\r}, '').split(';') pears.each do |local_pear| prop = local_pear.split(':') next if !prop[0] diff --git a/lib/idoit.rb b/lib/idoit.rb index a40a1d112..f7fdaf9b4 100644 --- a/lib/idoit.rb +++ b/lib/idoit.rb @@ -124,7 +124,7 @@ or with filter: }, ) - raise "Can't fetch objects from #{url}: Unable to parse response from server. Invalid JSON response." if !result.success? && result.error =~ /JSON::ParserError:.+?\s+unexpected\s+token\s+at\s+']+)/ + return from if from !~ %r{<\s*([^>]+)} $1.strip end diff --git a/lib/import/otrs/dynamic_field.rb b/lib/import/otrs/dynamic_field.rb index c91b850a9..cb747f04d 100644 --- a/lib/import/otrs/dynamic_field.rb +++ b/lib/import/otrs/dynamic_field.rb @@ -14,7 +14,7 @@ module Import end def self.convert_name(dynamic_field_name) - dynamic_field_name.underscore.sub(/_id(s)?\z/, '_no\1') + dynamic_field_name.underscore.sub(%r{_id(s)?\z}, '_no\1') end private diff --git a/lib/import/otrs/history/move.rb b/lib/import/otrs/history/move.rb index 4c07ac959..4fa5d34ad 100644 --- a/lib/import/otrs/history/move.rb +++ b/lib/import/otrs/history/move.rb @@ -7,7 +7,7 @@ module Import # "%%Queue1%%5%%Postmaster%%1" from = nil to = nil - if data =~ /%%(.+?)%%(.+?)%%(.+?)%%(.+?)$/ + if data =~ %r{%%(.+?)%%(.+?)%%(.+?)%%(.+?)$} from = $1 from_id = $2 to = $3 diff --git a/lib/import/otrs/history/priority_update.rb b/lib/import/otrs/history/priority_update.rb index bad17f2e0..e0a024fbd 100644 --- a/lib/import/otrs/history/priority_update.rb +++ b/lib/import/otrs/history/priority_update.rb @@ -7,7 +7,7 @@ module Import # "%%3 normal%%3%%5 very high%%5" from = nil to = nil - if data =~ /%%(.+?)%%(.+?)%%(.+?)%%(.+?)$/ + if data =~ %r{%%(.+?)%%(.+?)%%(.+?)%%(.+?)$} from = $1 from_id = $2 to = $3 diff --git a/lib/import/otrs/history/state_update.rb b/lib/import/otrs/history/state_update.rb index 0e199c517..94372de88 100644 --- a/lib/import/otrs/history/state_update.rb +++ b/lib/import/otrs/history/state_update.rb @@ -7,7 +7,7 @@ module Import # "%%new%%open%%" from = nil to = nil - if data =~ /%%(.+?)%%(.+?)%%/ + if data =~ %r{%%(.+?)%%(.+?)%%} from = $1 to = $2 state_from = ::Ticket::State.lookup(name: from) diff --git a/lib/import/otrs/user.rb b/lib/import/otrs/user.rb index b76c84e9d..aa38f546f 100644 --- a/lib/import/otrs/user.rb +++ b/lib/import/otrs/user.rb @@ -161,7 +161,7 @@ module Import result.push 'Admin' end - return result if !group['Name'].match?(/^(stats|report)/) + return result if !group['Name'].match?(%r{^(stats|report)}) return result if !( permissions.include?('ro') || permissions.include?('rw') ) result.push 'Report' diff --git a/lib/ldap.rb b/lib/ldap.rb index f11c4bd7d..c04d2e6e4 100644 --- a/lib/ldap.rb +++ b/lib/ldap.rb @@ -189,7 +189,7 @@ class Ldap end def parse_host - return if @host !~ /\A([^:]+):(.+?)\z/ + return if @host !~ %r{\A([^:]+):(.+?)\z} @host = $1 @port = $2.to_i diff --git a/lib/ldap/guid.rb b/lib/ldap/guid.rb index f9371ab22..7a44cba0e 100644 --- a/lib/ldap/guid.rb +++ b/lib/ldap/guid.rb @@ -16,7 +16,7 @@ class Ldap # # @return [Boolean] def self.valid?(string) - string.match?(/\w{8}-\w{4}-\w{4}-\w{4}-\w+/) + string.match?(%r{\w{8}-\w{4}-\w{4}-\w{4}-\w+}) end # Convers a given GUID string into the HEX equivalent. @@ -88,7 +88,7 @@ class Ldap string.delete!('-') # split every two chars - parts = string.scan(/.{1,2}/) + parts = string.scan(%r{.{1,2}}) # re-order according to oracle format index and join oracle_format_indices = [3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15] diff --git a/lib/mixin/required_sub_paths.rb b/lib/mixin/required_sub_paths.rb index b59445b47..ed2852c72 100644 --- a/lib/mixin/required_sub_paths.rb +++ b/lib/mixin/required_sub_paths.rb @@ -30,7 +30,7 @@ module Mixin if File.directory?(sub_path) sub_paths.push(sub_path) - elsif sub_path =~ /\A(.*)\.rb\z/ + elsif sub_path =~ %r{\A(.*)\.rb\z} require_path = $1 require_dependency(require_path) end diff --git a/lib/models.rb b/lib/models.rb index 303e6e8ed..32b9c699d 100644 --- a/lib/models.rb +++ b/lib/models.rb @@ -30,7 +30,7 @@ returns dir = Rails.root.join('app/models').to_s tables = ActiveRecord::Base.connection.tables Dir.glob("#{dir}/**/*.rb") do |entry| - next if entry.match?(/application_model/i) + next if entry.match?(%r{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) diff --git a/lib/notification_factory/mailer.rb b/lib/notification_factory/mailer.rb index d927c2a43..1711e17c7 100644 --- a/lib/notification_factory/mailer.rb +++ b/lib/notification_factory/mailer.rb @@ -244,8 +244,8 @@ retunes result.each do |item| next if item['type'] != 'notification' next if item['object'] != 'Ticket' - next if !item['value_to'].match?(/#{recipient.email}/i) - next if !item['value_to'].match?(/#{type}/i) + next if !item['value_to'].match?(%r{#{recipient.email}}i) + next if !item['value_to'].match?(%r{#{type}}i) count += 1 end diff --git a/lib/notification_factory/renderer.rb b/lib/notification_factory/renderer.rb index 6c7086fcc..9f507ed7f 100644 --- a/lib/notification_factory/renderer.rb +++ b/lib/notification_factory/renderer.rb @@ -106,7 +106,7 @@ examples how to use end arguments = nil - if /\A(?[^(]+)\((?[^)]+)\)\z/ =~ method + if %r{\A(?[^(]+)\((?[^)]+)\)\z} =~ method if parameter != parameter.to_i.to_s value = "\#{#{object_name}.#{object_methods_s} / invalid parameter: #{parameter}}" @@ -185,7 +185,7 @@ examples how to use end def data_key_valid?(key) - return false if key =~ /`|\.(|\s*)(save|destroy|delete|remove|drop|update|create|new|all|where|find|raise|dump|rollback|freeze)/i && key !~ /(update|create)d_(at|by)/i + return false if key =~ %r{`|\.(|\s*)(save|destroy|delete|remove|drop|update|create|new|all|where|find|raise|dump|rollback|freeze)}i && key !~ %r{(update|create)d_(at|by)}i true end diff --git a/lib/notification_factory/template.rb b/lib/notification_factory/template.rb index 945eba14d..22e2e90be 100644 --- a/lib/notification_factory/template.rb +++ b/lib/notification_factory/template.rb @@ -17,17 +17,17 @@ examples how to use end def to_s - @template.gsub(/\#{\s*(.*?)\s*}/m) do + @template.gsub(%r{\#{\s*(.*?)\s*}}m) do # some browsers start adding HTML tags # fixes https://github.com/zammad/zammad/issues/385 - input_template = $1.gsub(/\A<.+?>\s*|\s*<.+?>\z/, '') + input_template = $1.gsub(%r{\A<.+?>\s*|\s*<.+?>\z}, '') case input_template - when /\At\('(.+?)'\)\z/m + when %r{\At\('(.+?)'\)\z}m %(<%= t "#{sanitize_text($1)}", #{@escape} %>) - when /\At\((.+?)\)\z/m + when %r{\At\((.+?)\)\z}m %(<%= t d"#{sanitize_object_name($1)}", #{@escape} %>) - when /\Aconfig\.(.+?)\z/m + when %r{\Aconfig\.(.+?)\z}m %(<%= c "#{sanitize_object_name($1)}", #{@escape} %>) else %(<%= d "#{sanitize_object_name(input_template)}", #{@escape} %>) @@ -37,7 +37,7 @@ examples how to use def sanitize_text(string) string&.tr("\t\r\n", '') - &.gsub(/(?]+)/ + return source if source !~ %r{<\s*([^>]+)} $1.strip end diff --git a/lib/sequencer/unit/import/zendesk/sub_sequence/base.rb b/lib/sequencer/unit/import/zendesk/sub_sequence/base.rb index ac25648a9..48fb74a6a 100644 --- a/lib/sequencer/unit/import/zendesk/sub_sequence/base.rb +++ b/lib/sequencer/unit/import/zendesk/sub_sequence/base.rb @@ -65,7 +65,7 @@ class Sequencer return true if e.message.include?('execution expired') status = e.response.status.to_s - status.match?(/^(4|5)\d\d$/) + status.match?(%r{^(4|5)\d\d$}) end def resource_collection diff --git a/lib/service/geo_calendar/zammad.rb b/lib/service/geo_calendar/zammad.rb index 4b9204be3..b4187f564 100644 --- a/lib/service/geo_calendar/zammad.rb +++ b/lib/service/geo_calendar/zammad.rb @@ -27,7 +27,7 @@ class Service::GeoCalendar::Zammad total_timeout: 12, }, ) - if !response.success? && response.code.to_s !~ /^40.$/ + if !response.success? && response.code.to_s !~ %r{^40.$} raise "#{response.code}/#{response.body}" end diff --git a/lib/service/geo_ip/zammad.rb b/lib/service/geo_ip/zammad.rb index b2a5025d1..095ce3f57 100644 --- a/lib/service/geo_ip/zammad.rb +++ b/lib/service/geo_ip/zammad.rb @@ -25,7 +25,7 @@ class Service::GeoIp::Zammad total_timeout: 4, }, ) - if !response.success? && response.code.to_s !~ /^40.$/ + if !response.success? && response.code.to_s !~ %r{^40.$} raise "#{response.code}/#{response.body}" end diff --git a/lib/service/image/zammad.rb b/lib/service/image/zammad.rb index 335eed867..29379b6e2 100644 --- a/lib/service/image/zammad.rb +++ b/lib/service/image/zammad.rb @@ -12,7 +12,7 @@ class Service::Image::Zammad email.downcase! - return if email.match?(/@example.com$/) + return if email.match?(%r{@example.com$}) # fetch image response = UserAgent.post( @@ -42,7 +42,7 @@ class Service::Image::Zammad raise Exceptions::UnprocessableEntity, 'no domain given' if domain.blank? # strip, just use domain name - domain = domain.sub(/^.+?@(.+?)$/, '\1') + domain = domain.sub(%r{^.+?@(.+?)$}, '\1') domain.downcase! return if domain == 'example.com' diff --git a/lib/signature_detection.rb b/lib/signature_detection.rb index 1421af25c..17669ff21 100644 --- a/lib/signature_detection.rb +++ b/lib/signature_detection.rb @@ -42,7 +42,7 @@ returns # Take up to 10 lines from this "gap" (i.e., the common substring) match_content = diff_lines[sig_range.first..sig_range.last] - .map { |l| l.sub(/^./, '') } + .map { |l| l.sub(%r{^.}, '') } .first(10).join("\n") # Add this substring to the signature_candidates hash and increment its match score diff --git a/lib/sql_helper.rb b/lib/sql_helper.rb index aac91e318..0f3ff605c 100644 --- a/lib/sql_helper.rb +++ b/lib/sql_helper.rb @@ -9,7 +9,7 @@ class SqlHelper def get_param_key(key, params) sort_by = [] if params[key].present? && params[key].is_a?(String) - params[key] = params[key].split(/\s*,\s*/) + params[key] = params[key].split(%r{\s*,\s*}) elsif params[key].blank? params[key] = [] end @@ -79,7 +79,7 @@ order_by = [ # check order params[:order_by].each do |value| - raise "Found invalid order by value #{value}. Please use 'asc' or 'desc'." if !value.match?(/\A(asc|desc)\z/i) + raise "Found invalid order by value #{value}. Please use 'asc' or 'desc'." if !value.match?(%r{\A(asc|desc)\z}i) order_by.push(value.downcase) end diff --git a/lib/static_assets.rb b/lib/static_assets.rb index 1b27f339a..1b3d0b278 100644 --- a/lib/static_assets.rb +++ b/lib/static_assets.rb @@ -16,7 +16,7 @@ returns def self.data_url_attributes(data_url) data = {} - if data_url =~ /^data:(.+?);base64,(.+?)$/ + if data_url =~ %r{^data:(.+?);base64,(.+?)$} data[:mime_type] = $1 data[:content] = Base64.decode64($2) if data[:mime_type] =~ %r{/(.+?)$} @@ -146,13 +146,13 @@ generate filename based on Store model hash = Digest::MD5.hexdigest(file.content) extention = '' case file.preferences['Content-Type'] - when /jpg|jpeg/i + when %r{jpg|jpeg}i extention = '.jpg' - when /png/i + when %r{png}i extention = '.png' - when /gif/i + when %r{gif}i extention = '.gif' - when /svg/i + when %r{svg}i extention = '.svg' end "#{hash}#{extention}" diff --git a/lib/stats/ticket_channel_distribution.rb b/lib/stats/ticket_channel_distribution.rb index cad03db9c..31fcbc38b 100644 --- a/lib/stats/ticket_channel_distribution.rb +++ b/lib/stats/ticket_channel_distribution.rb @@ -86,7 +86,7 @@ class Stats::TicketChannelDistribution } type_ids = [] Ticket::Article::Type.all.each do |type| - next if !type.name.match?(/^#{channel[:sender]}/i) + next if !type.name.match?(%r{^#{channel[:sender]}}i) type_ids.push type.id end diff --git a/lib/twitter_sync.rb b/lib/twitter_sync.rb index 4557dcd81..ba313a0a0 100644 --- a/lib/twitter_sync.rb +++ b/lib/twitter_sync.rb @@ -203,9 +203,9 @@ class TwitterSync next if local_url['url'].blank? if local_url['expanded_url'].present? - text.gsub!(/#{Regexp.quote(local_url['url'])}/, local_url['expanded_url']) + text.gsub!(%r{#{Regexp.quote(local_url['url'])}}, local_url['expanded_url']) elsif local_url['display_url'] - text.gsub!(/#{Regexp.quote(local_url['url'])}/, local_url['display_url']) + text.gsub!(%r{#{Regexp.quote(local_url['url'])}}, local_url['display_url']) end end end @@ -266,9 +266,9 @@ class TwitterSync if local_media['url'].present? if local_media['expanded_url'].present? - text.gsub!(/#{Regexp.quote(local_media['url'])}/, local_media['expanded_url']) + text.gsub!(%r{#{Regexp.quote(local_media['url'])}}, local_media['expanded_url']) elsif local_media['display_url'] - text.gsub!(/#{Regexp.quote(local_media['url'])}/, local_media['display_url']) + text.gsub!(%r{#{Regexp.quote(local_media['url'])}}, local_media['display_url']) end end end @@ -277,9 +277,9 @@ class TwitterSync if local_media['url'].present? if local_media['expanded_url'].present? - text.gsub!(/#{Regexp.quote(local_media['url'])}/, local_media['expanded_url']) + text.gsub!(%r{#{Regexp.quote(local_media['url'])}}, local_media['expanded_url']) elsif local_media['display_url'] - text.gsub!(/#{Regexp.quote(local_media['url'])}/, local_media['display_url']) + text.gsub!(%r{#{Regexp.quote(local_media['url'])}}, local_media['display_url']) end end @@ -723,7 +723,7 @@ process webhook messages from twitter channel.options[:sync][:search].each do |local_search| next if local_search[:term].blank? next if local_search[:group_id].blank? - next if !item['text'].match?(/#{Regexp.quote(local_search[:term])}/i) + next if !item['text'].match?(%r{#{Regexp.quote(local_search[:term])}}i) group_id = local_search[:group_id] break diff --git a/lib/user_agent.rb b/lib/user_agent.rb index 7d2af693b..58881a7e4 100644 --- a/lib/user_agent.rb +++ b/lib/user_agent.rb @@ -287,9 +287,9 @@ returns uri = URI.parse(url) case uri.scheme.downcase - when /ftp/ + when %r{ftp} ftp(uri, options) - when /http|https/ + when %r{http|https} get(url, {}, options) end @@ -302,7 +302,7 @@ returns proxy_no = proxy_no.split(',').map(&:strip) || [] proxy_no.push('localhost', '127.0.0.1', '::1') if proxy.present? && proxy_no.exclude?(uri.host.downcase) - if proxy =~ /^(.+?):(.+?)$/ + if proxy =~ %r{^(.+?):(.+?)$} proxy_host = $1 proxy_port = $2 end @@ -328,7 +328,7 @@ returns http.open_timeout = options[:open_timeout] || 4 http.read_timeout = options[:read_timeout] || 10 - if uri.scheme.match?(/https/i) + if uri.scheme.match?(%r{https}i) http.use_ssl = true if !options.fetch(:verify_ssl, false) diff --git a/spec/lib/external_credential/google_spec.rb b/spec/lib/external_credential/google_spec.rb index aa593f679..e26cfc1e1 100644 --- a/spec/lib/external_credential/google_spec.rb +++ b/spec/lib/external_credential/google_spec.rb @@ -299,7 +299,7 @@ RSpec.describe ExternalCredential::Google do error_description: 'The OAuth client was not found.' } end - let(:exception_message) { /The OAuth client was not found/ } + let(:exception_message) { %r{The OAuth client was not found} } include_examples 'failed attempt' end @@ -307,7 +307,7 @@ RSpec.describe ExternalCredential::Google do context '500 Internal Server Error' do let(:response_status) { 500 } let(:response_payload) { nil } - let(:exception_message) { /code: 500/ } + let(:exception_message) { %r{code: 500} } include_examples 'failed attempt' end diff --git a/spec/lib/external_credential/microsoft365_spec.rb b/spec/lib/external_credential/microsoft365_spec.rb index 7e429e43f..afd49f1bc 100644 --- a/spec/lib/external_credential/microsoft365_spec.rb +++ b/spec/lib/external_credential/microsoft365_spec.rb @@ -260,7 +260,7 @@ RSpec.describe ExternalCredential::Microsoft365 do error_description: 'The OAuth client was not found.' } end - let(:exception_message) { /The OAuth client was not found/ } + let(:exception_message) { %r{The OAuth client was not found} } include_examples 'failed attempt' end @@ -268,7 +268,7 @@ RSpec.describe ExternalCredential::Microsoft365 do context '500 Internal Server Error' do let(:response_status) { 500 } let(:response_payload) { nil } - let(:exception_message) { /code: 500/ } + let(:exception_message) { %r{code: 500} } include_examples 'failed attempt' end diff --git a/spec/lib/html_sanitizer_spec.rb b/spec/lib/html_sanitizer_spec.rb index e387178cb..7f1d0628d 100644 --- a/spec/lib/html_sanitizer_spec.rb +++ b/spec/lib/html_sanitizer_spec.rb @@ -24,7 +24,7 @@ RSpec.describe HtmlSanitizer do let(:html) { '' } it 'converts embedded image to cid' do - expect(body).to match(//) + expect(body).to match(%r{}) end it 'extracts one attachment' do @@ -40,7 +40,7 @@ RSpec.describe HtmlSanitizer do end it 'sets Content-ID based on Zammad fqdn' do - expect(inline_attachments.first[:preferences]['Content-ID']).to match(/@#{Setting.get('fqdn')}/) + expect(inline_attachments.first[:preferences]['Content-ID']).to match(%r{@#{Setting.get('fqdn')}}) end it 'sets Content-Disposition to inline' do @@ -52,7 +52,7 @@ RSpec.describe HtmlSanitizer do let(:html) { 'abc' } it 'converts embedded image to cid' do - expect(body).to match(/abc/) + expect(body).to match(%r{abc}) end it 'extracts one attachment' do @@ -68,7 +68,7 @@ RSpec.describe HtmlSanitizer do end it 'sets Content-ID based on Zammad fqdn' do - expect(inline_attachments.first[:preferences]['Content-ID']).to match(/@#{Setting.get('fqdn')}/) + expect(inline_attachments.first[:preferences]['Content-ID']).to match(%r{@#{Setting.get('fqdn')}}) end it 'sets Content-Disposition to inline' do @@ -80,7 +80,7 @@ RSpec.describe HtmlSanitizer do let(:html) { 'abc/) + expect(body).to match(%r{abc}) end it 'extracts one attachment' do @@ -96,7 +96,7 @@ RSpec.describe HtmlSanitizer do end it 'sets Content-ID based on Zammad fqdn' do - expect(inline_attachments.first[:preferences]['Content-ID']).to match(/@#{Setting.get('fqdn')}/) + expect(inline_attachments.first[:preferences]['Content-ID']).to match(%r{@#{Setting.get('fqdn')}}) end it 'sets Content-Disposition to inline' do @@ -126,8 +126,8 @@ RSpec.describe HtmlSanitizer do end it 'sets Content-IDs based on Zammad fqdn' do - expect(inline_attachments.first[:preferences]['Content-ID']).to match(/@#{Setting.get('fqdn')}/) - expect(inline_attachments.second[:preferences]['Content-ID']).to match(/@#{Setting.get('fqdn')}/) + expect(inline_attachments.first[:preferences]['Content-ID']).to match(%r{@#{Setting.get('fqdn')}}) + expect(inline_attachments.second[:preferences]['Content-ID']).to match(%r{@#{Setting.get('fqdn')}}) end it 'sets Content-Dispositions to inline' do diff --git a/spec/lib/import/zendesk/object_attribute/base_examples.rb b/spec/lib/import/zendesk/object_attribute/base_examples.rb index 451b9ba70..81d59d01e 100644 --- a/spec/lib/import/zendesk/object_attribute/base_examples.rb +++ b/spec/lib/import/zendesk/object_attribute/base_examples.rb @@ -25,7 +25,7 @@ RSpec.shared_examples Import::Zendesk::ObjectAttribute::Base do expect do described_class.new('Ticket', 'example_field', attribute) - end.to raise_error(RuntimeError, /'example_field': #{error_text}$/) + end.to raise_error(RuntimeError, %r{'example_field': #{error_text}$}) end end diff --git a/spec/lib/ldap/user_spec.rb b/spec/lib/ldap/user_spec.rb index ad9deef6f..fb8968225 100644 --- a/spec/lib/ldap/user_spec.rb +++ b/spec/lib/ldap/user_spec.rb @@ -204,7 +204,7 @@ RSpec.describe Ldap::User do # stored in test/data/tcr_cassettes. context 'on mocked LDAP connections' do around do |example| - cassette_name = example.description.gsub(/[^0-9A-Za-z.\-]+/, '_') + cassette_name = example.description.gsub(%r{[^0-9A-Za-z.\-]+}, '_') begin original_tcr_format = TCR.configuration.format diff --git a/spec/lib/notification_factory/slack_spec.rb b/spec/lib/notification_factory/slack_spec.rb index cbe620939..11140fd82 100644 --- a/spec/lib/notification_factory/slack_spec.rb +++ b/spec/lib/notification_factory/slack_spec.rb @@ -33,8 +33,8 @@ RSpec.describe NotificationFactory::Slack do it 'returns a hash with body:
' do expect(template[:body]) - .to match(/Created by #{current_user.fullname}/) - .and match(/#{article.body}\z/) + .to match(%r{Created by #{current_user.fullname}}) + .and match(%r{#{article.body}\z}) end end @@ -55,11 +55,11 @@ RSpec.describe NotificationFactory::Slack do it 'returns a hash with body:
' do expect(template[:body]) - .to match(/Updated by #{current_user.fullname}/) - .and match(/state: aaa -> bbb/) - .and match(/group: xxx -> yyy/) + .to match(%r{Updated by #{current_user.fullname}}) + .and match(%r{state: aaa -> bbb}) + .and match(%r{group: xxx -> yyy}) .and match(%r{pending_time: 04/01/2019 12:00 \(Europe/Berlin\) -> 04/02/2019 01:00 \(Europe/Berlin\)}) - .and match(/#{article.body}\z/) + .and match(%r{#{article.body}\z}) end end @@ -87,9 +87,9 @@ RSpec.describe NotificationFactory::Slack do it 'returns a hash with body: ' do expect(template[:body]) - .to match(/A ticket \(#{ticket.title}\) from "#{ticket.customer.fullname}"/) + .to match(%r{A ticket \(#{ticket.title}\) from "#{ticket.customer.fullname}"}) .and match(%r{is escalated since "04/01/2019 12:00 \(Europe/Berlin\)"!}) - .and match(/#{article.body}\z/) + .and match(%r{#{article.body}\z}) end end end diff --git a/spec/lib/secure_mailing/smime_spec.rb b/spec/lib/secure_mailing/smime_spec.rb index 7af7f08cc..a7cdd5308 100644 --- a/spec/lib/secure_mailing/smime_spec.rb +++ b/spec/lib/secure_mailing/smime_spec.rb @@ -470,7 +470,7 @@ RSpec.describe SecureMailing::SMIME do expect(mail['x-zammad-article-preferences'][:security][:encryption][:success]).to be false expect(mail['x-zammad-article-preferences'][:security][:encryption][:comment]).to be nil - expect(Rails.logger).not_to have_received(:warn).with(/#{Regexp.escape(ca_certificate_subject)}/) + expect(Rails.logger).not_to have_received(:warn).with(%r{#{Regexp.escape(ca_certificate_subject)}}) end end end diff --git a/spec/lib/sequencer/unit/import/common/mapping/flat_keys_spec.rb b/spec/lib/sequencer/unit/import/common/mapping/flat_keys_spec.rb index c9bbb1a32..ee9ca6bb9 100644 --- a/spec/lib/sequencer/unit/import/common/mapping/flat_keys_spec.rb +++ b/spec/lib/sequencer/unit/import/common/mapping/flat_keys_spec.rb @@ -9,7 +9,7 @@ RSpec.describe Sequencer::Unit::Import::Common::Mapping::FlatKeys, sequencer: :u remote_attribute: 'value', } ) - end.to raise_error(RuntimeError, /mapping/) + end.to raise_error(RuntimeError, %r{mapping}) end it 'maps flat key structures' do diff --git a/spec/lib/static_assets_spec.rb b/spec/lib/static_assets_spec.rb index ee9c05f29..c72ef7499 100644 --- a/spec/lib/static_assets_spec.rb +++ b/spec/lib/static_assets_spec.rb @@ -3,11 +3,11 @@ require 'rails_helper' RSpec.describe StaticAssets do describe '.data_url_attributes' do it 'raises error if empty string given' do - expect { described_class.data_url_attributes('') }.to raise_error(/Unable to parse data url/) + expect { described_class.data_url_attributes('') }.to raise_error(%r{Unable to parse data url}) end it 'raises error if nil' do - expect { described_class.data_url_attributes(nil) }.to raise_error(/Unable to parse data url/) + expect { described_class.data_url_attributes(nil) }.to raise_error(%r{Unable to parse data url}) end end end diff --git a/spec/models/channel/driver/twitter_spec.rb b/spec/models/channel/driver/twitter_spec.rb index 3c4907371..b24f48732 100644 --- a/spec/models/channel/driver/twitter_spec.rb +++ b/spec/models/channel/driver/twitter_spec.rb @@ -901,8 +901,8 @@ RSpec.describe Channel::Driver::Twitter do it 'creates articles for parent tweets as well' do channel.fetch - expect(thread.articles.last.body).to match(/zammad/i) # search result - expect(thread.articles.first.body).not_to match(/zammad/i) # parent tweet + expect(thread.articles.last.body).to match(%r{zammad}i) # search result + expect(thread.articles.first.body).not_to match(%r{zammad}i) # parent tweet end end diff --git a/spec/models/channel/email_parser_spec.rb b/spec/models/channel/email_parser_spec.rb index 080431fe3..ca819792f 100644 --- a/spec/models/channel/email_parser_spec.rb +++ b/spec/models/channel/email_parser_spec.rb @@ -1159,7 +1159,7 @@ RSpec.describe Channel::EmailParser, type: :model do context 'for “delivery failed” notifications (a.k.a. bounce messages)' do let(:ticket) { article.ticket } let(:article) { create(:ticket_article, sender_name: 'Agent', message_id: message_id) } - let(:message_id) { raw_mail[/(?<=^(References|Message-ID): )\S*/] } + let(:message_id) { raw_mail[%r{(?<=^(References|Message-ID): )\S*}] } context 'with future retries (delayed)' do let(:mail_file) { Rails.root.join('test/data/mail/mail078.box') } @@ -1347,7 +1347,7 @@ RSpec.describe Channel::EmailParser, type: :model do Postmaster of zammad.example.com BODY - body.gsub(/\n/, "\r\n") + body.gsub(%r{\n}, "\r\n") end end end @@ -1370,7 +1370,7 @@ RSpec.describe Channel::EmailParser, type: :model do Postmaster von zammad.example.com BODY - body.gsub(/\n/, "\r\n") + body.gsub(%r{\n}, "\r\n") end end end diff --git a/spec/models/channel/filter/internal_article_check_spec.rb b/spec/models/channel/filter/internal_article_check_spec.rb index 27181534b..33e4cc214 100644 --- a/spec/models/channel/filter/internal_article_check_spec.rb +++ b/spec/models/channel/filter/internal_article_check_spec.rb @@ -21,7 +21,7 @@ RSpec.describe Channel::Filter::InternalArticleCheck do let(:email_parse_mail_answer) do channel_as_model = Channel.new(options: {}) - email_raw_string.sub!(/^Subject: .+?$/, subject) + email_raw_string.sub!(%r{^Subject: .+?$}, subject) email_raw_string.sub!('From: ', from) email_raw_string.sub!('Message-Id: <053EA3703574649ABDAF24D43A05604F327A130@MEMASFRK004.example.com>', "Message-Id: <053EA3703574649ABDAF24D43A05604F327A130@MEMASFRK004.example.com>\nIn-Reply-To: #{in_reply_to}") Channel::EmailParser.new.process(channel_as_model, email_raw_string) diff --git a/spec/models/channel_spec.rb b/spec/models/channel_spec.rb index bafe1f696..c8ecec4ff 100644 --- a/spec/models/channel_spec.rb +++ b/spec/models/channel_spec.rb @@ -86,7 +86,7 @@ RSpec.describe Channel, type: :model do end it 'raises RuntimeError' do - expect { channel.refresh_xoauth2! }.to raise_exception(RuntimeError, /#{exception.message}/) + expect { channel.refresh_xoauth2! }.to raise_exception(RuntimeError, %r{#{exception.message}}) end end diff --git a/spec/models/cti/log_spec.rb b/spec/models/cti/log_spec.rb index a5a1bdd37..4fd54b09b 100644 --- a/spec/models/cti/log_spec.rb +++ b/spec/models/cti/log_spec.rb @@ -161,7 +161,7 @@ RSpec.describe Cti::Log do before { create(:'cti/log', call_id: '1') } it 'raises an error' do - expect { described_class.process(attributes) }.to raise_error(/call_id \S+ already exists!/) + expect { described_class.process(attributes) }.to raise_error(%r{call_id \S+ already exists!}) end end end @@ -171,7 +171,7 @@ RSpec.describe Cti::Log do context 'with unrecognized "call_id"' do it 'raises an error' do - expect { described_class.process(attributes) }.to raise_error(/No such call_id/) + expect { described_class.process(attributes) }.to raise_error(%r{No such call_id}) end end @@ -202,7 +202,7 @@ RSpec.describe Cti::Log do context 'with unrecognized "call_id"' do it 'raises an error' do - expect { described_class.process(attributes) }.to raise_error(/No such call_id/) + expect { described_class.process(attributes) }.to raise_error(%r{No such call_id}) end end diff --git a/spec/models/knowledge_base/answer/translation_spec.rb b/spec/models/knowledge_base/answer/translation_spec.rb index 530d002b4..603e8522f 100644 --- a/spec/models/knowledge_base/answer/translation_spec.rb +++ b/spec/models/knowledge_base/answer/translation_spec.rb @@ -7,7 +7,7 @@ RSpec.describe KnowledgeBase::Answer::Translation, type: :model, current_user_id include_context 'factory' it { is_expected.to validate_presence_of(:title) } - it { is_expected.to validate_uniqueness_of(:kb_locale_id).scoped_to(:answer_id).with_message(//) } + it { is_expected.to validate_uniqueness_of(:kb_locale_id).scoped_to(:answer_id).with_message(%r{}) } it { is_expected.to belong_to(:answer) } it { is_expected.to belong_to(:kb_locale) } diff --git a/spec/models/knowledge_base/category/translation_spec.rb b/spec/models/knowledge_base/category/translation_spec.rb index 5980b568a..cd8e8f69e 100644 --- a/spec/models/knowledge_base/category/translation_spec.rb +++ b/spec/models/knowledge_base/category/translation_spec.rb @@ -7,7 +7,7 @@ RSpec.describe KnowledgeBase::Category::Translation, type: :model do include_context 'factory' it { is_expected.to validate_presence_of(:title) } - it { is_expected.to validate_uniqueness_of(:kb_locale_id).scoped_to(:category_id).with_message(//) } + it { is_expected.to validate_uniqueness_of(:kb_locale_id).scoped_to(:category_id).with_message(%r{}) } it { is_expected.to belong_to(:category) } it { is_expected.to belong_to(:kb_locale) } diff --git a/spec/models/knowledge_base/translation_spec.rb b/spec/models/knowledge_base/translation_spec.rb index d3f558585..eccc20a45 100644 --- a/spec/models/knowledge_base/translation_spec.rb +++ b/spec/models/knowledge_base/translation_spec.rb @@ -7,7 +7,7 @@ RSpec.describe KnowledgeBase::Translation, type: :model do include_context 'factory' it { is_expected.to validate_presence_of(:title) } - it { is_expected.to validate_uniqueness_of(:kb_locale_id).scoped_to(:knowledge_base_id).with_message(//) } + it { is_expected.to validate_uniqueness_of(:kb_locale_id).scoped_to(:knowledge_base_id).with_message(%r{}) } it { is_expected.to belong_to(:knowledge_base) } it { is_expected.to belong_to(:kb_locale) } diff --git a/spec/models/knowledge_base_spec.rb b/spec/models/knowledge_base_spec.rb index f6da2f16e..31b2b45e8 100644 --- a/spec/models/knowledge_base_spec.rb +++ b/spec/models/knowledge_base_spec.rb @@ -14,7 +14,7 @@ RSpec.describe KnowledgeBase, type: :model do it { is_expected.to validate_presence_of(:color_highlight) } it { is_expected.to validate_presence_of(:color_header) } - it { is_expected.to validate_presence_of(:iconset).with_message(//) } + it { is_expected.to validate_presence_of(:iconset).with_message(%r{}) } it { is_expected.to validate_inclusion_of(:iconset).in_array(KnowledgeBase::ICONSETS) } it { is_expected.to validate_inclusion_of(:category_layout).in_array(KnowledgeBase::LAYOUTS) } it { is_expected.to validate_inclusion_of(:homepage_layout).in_array(KnowledgeBase::LAYOUTS) } diff --git a/spec/models/object_manager/attribute_spec.rb b/spec/models/object_manager/attribute_spec.rb index 870d59993..cac8d5eab 100644 --- a/spec/models/object_manager/attribute_spec.rb +++ b/spec/models/object_manager/attribute_spec.rb @@ -62,7 +62,7 @@ RSpec.describe ObjectManager::Attribute, type: :model do it "rejects Zammad reserved word '#{reserved_word}'" do expect do described_class.add attributes_for :object_manager_attribute_text, name: reserved_word - end.to raise_error(ActiveRecord::RecordInvalid, /is a reserved word! \(1\)/) + end.to raise_error(ActiveRecord::RecordInvalid, %r{is a reserved word! \(1\)}) end end diff --git a/spec/models/overview_spec.rb b/spec/models/overview_spec.rb index 081f6235b..d1c1e96ee 100644 --- a/spec/models/overview_spec.rb +++ b/spec/models/overview_spec.rb @@ -46,7 +46,7 @@ RSpec.describe Overview, type: :model do it 'handles special chars' do overview = create(:overview, name: 'Д дФ ф') - expect(overview.link).to match(/^\d{1,3}$/) + expect(overview.link).to match(%r{^\d{1,3}$}) end it 'removes special char fallback if possible' do diff --git a/spec/models/role_spec.rb b/spec/models/role_spec.rb index 94b118aa3..023c16f79 100644 --- a/spec/models/role_spec.rb +++ b/spec/models/role_spec.rb @@ -72,13 +72,13 @@ RSpec.describe Role do it 'cannot be created' do expect { create(:role, permissions: [permission]) } - .to raise_error(/is disabled/) + .to raise_error(%r{is disabled}) .and change(described_class, :count).by(0) end it 'cannot be added' do expect { role.permissions << permission } - .to raise_error(/is disabled/) + .to raise_error(%r{is disabled}) .and change { role.permissions.count }.by(0) end end @@ -88,7 +88,7 @@ RSpec.describe Role do it 'cannot be created' do expect { create(:role, permissions: [Permission.first, permission]) } - .to raise_error(/conflicts with/) + .to raise_error(%r{conflicts with}) .and change(described_class, :count).by(0) end @@ -96,7 +96,7 @@ RSpec.describe Role do role.permissions << Permission.first expect { role.permissions << permission } - .to raise_error(/conflicts with/) + .to raise_error(%r{conflicts with}) .and change { role.permissions.count }.by(0) end end @@ -148,14 +148,14 @@ RSpec.describe Role do role.default_at_signup = true expect { role.save } - .to raise_error(Exceptions::UnprocessableEntity, /Cannot set default at signup/) + .to raise_error(Exceptions::UnprocessableEntity, %r{Cannot set default at signup}) end it 'cannot be changed to true' do role.save expect { role.update(default_at_signup: true) } - .to raise_error(Exceptions::UnprocessableEntity, /Cannot set default at signup/) + .to raise_error(Exceptions::UnprocessableEntity, %r{Cannot set default at signup}) end end @@ -168,14 +168,14 @@ RSpec.describe Role do role.default_at_signup = true expect { role.save } - .to raise_error(Exceptions::UnprocessableEntity, /Cannot set default at signup/) + .to raise_error(Exceptions::UnprocessableEntity, %r{Cannot set default at signup}) end it 'cannot be changed to true' do role.save expect { role.update(default_at_signup: true) } - .to raise_error(Exceptions::UnprocessableEntity, /Cannot set default at signup/) + .to raise_error(Exceptions::UnprocessableEntity, %r{Cannot set default at signup}) end end @@ -186,14 +186,14 @@ RSpec.describe Role do role.default_at_signup = true expect { role.save } - .to raise_error(Exceptions::UnprocessableEntity, /Cannot set default at signup/) + .to raise_error(Exceptions::UnprocessableEntity, %r{Cannot set default at signup}) end it 'cannot be changed to true' do role.save expect { role.update(default_at_signup: true) } - .to raise_error(Exceptions::UnprocessableEntity, /Cannot set default at signup/) + .to raise_error(Exceptions::UnprocessableEntity, %r{Cannot set default at signup}) end end end diff --git a/spec/models/smime_certificate_spec.rb b/spec/models/smime_certificate_spec.rb index 65e590356..c2cd84b8a 100644 --- a/spec/models/smime_certificate_spec.rb +++ b/spec/models/smime_certificate_spec.rb @@ -192,6 +192,6 @@ RSpec.describe SMIMECertificate, type: :model do end it 'ensures uniqueness of records' do - expect { create_list(:smime_certificate, 2, fixture: 'smime1@example.com') }.to raise_error(ActiveRecord::RecordInvalid, /Validation failed/) + expect { create_list(:smime_certificate, 2, fixture: 'smime1@example.com') }.to raise_error(ActiveRecord::RecordInvalid, %r{Validation failed}) end end diff --git a/spec/models/ticket/number/increment_spec.rb b/spec/models/ticket/number/increment_spec.rb index 01a76f96f..3085476b4 100644 --- a/spec/models/ticket/number/increment_spec.rb +++ b/spec/models/ticket/number/increment_spec.rb @@ -24,12 +24,12 @@ RSpec.describe Ticket::Number::Increment do before { Setting.set('system_id', 123_456) } it 'still adheres to numbering pattern (and does not require padding zeroes)' do - expect(number).to match(/^#{system_id}#{ticket_count}$/) + expect(number).to match(%r{^#{system_id}#{ticket_count}$}) end end it 'returns a string following the pattern system_id + padding zeroes + ticket_count' do - expect(number).to match(/^#{system_id}0*#{ticket_count}$/) + expect(number).to match(%r{^#{system_id}0*#{ticket_count}$}) end context '/ checksum: false (default)' do @@ -41,14 +41,14 @@ RSpec.describe Ticket::Number::Increment do end it 'returns a string following the pattern system_id + padding zeroes + ticket_counter' do - expect(number).to match(/^#{system_id}0*#{ticket_count}$/) + expect(number).to match(%r{^#{system_id}0*#{ticket_count}$}) end context 'when "system_id" setting exceeds :min_size' do before { Setting.set('system_id', 123_456) } it 'still adheres to numbering pattern (and does not require padding zeroes)' do - expect(number).to match(/^#{system_id}#{ticket_count}$/) + expect(number).to match(%r{^#{system_id}#{ticket_count}$}) end end end @@ -63,14 +63,14 @@ RSpec.describe Ticket::Number::Increment do end it 'returns a string following the pattern system_id + padding zeroes + ticket_counter + checksum' do - expect(number).to match(/^#{system_id}0*#{ticket_count}\d$/) + expect(number).to match(%r{^#{system_id}0*#{ticket_count}\d$}) end context 'when "system_id" setting exceeds :min_size' do before { Setting.set('system_id', 123_456) } it 'still adheres to numbering pattern (and does not require padding zeroes)' do - expect(number).to match(/^#{system_id}#{ticket_count}\d$/) + expect(number).to match(%r{^#{system_id}#{ticket_count}\d$}) end end end diff --git a/spec/models/trigger/sms_spec.rb b/spec/models/trigger/sms_spec.rb index bc5967078..1ab0ce0a7 100644 --- a/spec/models/trigger/sms_spec.rb +++ b/spec/models/trigger/sms_spec.rb @@ -42,7 +42,7 @@ RSpec.describe Trigger do end it 'renders HTML chars' do - expect(triggered_article.body).to match(/space between/) + expect(triggered_article.body).to match(%r{space between}) end it 'interpolates ticket properties' do diff --git a/spec/models/trigger_spec.rb b/spec/models/trigger_spec.rb index cf0bc1eb9..f7a246c60 100644 --- a/spec/models/trigger_spec.rb +++ b/spec/models/trigger_spec.rb @@ -452,8 +452,8 @@ RSpec.describe Trigger, type: :model do let!(:article) do create(:ticket_article, ticket: ticket, - message_id: raw_email[/(?<=^References: )\S*/], - subject: raw_email[/(?<=^Subject: Re: ).*$/]) + message_id: raw_email[%r{(?<=^References: )\S*}], + subject: raw_email[%r{(?<=^Subject: Re: ).*$}]) end let(:raw_email) { File.read(Rails.root.join('test/data/mail/mail005.box')) } @@ -470,7 +470,7 @@ RSpec.describe Trigger, type: :model do let!(:article) do create(:ticket_article, ticket: ticket, - message_id: raw_email[/(?<=^Message-ID: )\S*/]) + message_id: raw_email[%r{(?<=^Message-ID: )\S*}]) end let(:raw_email) { File.read(Rails.root.join('test/data/mail/mail055.box')) } diff --git a/spec/models/webhook_spec.rb b/spec/models/webhook_spec.rb index 3846367c0..1b69f91f8 100644 --- a/spec/models/webhook_spec.rb +++ b/spec/models/webhook_spec.rb @@ -73,7 +73,7 @@ RSpec.describe Webhook, type: :model do let!(:trigger) { create(:trigger, perform: { 'notification.webhook' => { 'webhook_id' => webhook.id.to_s } }) } it 'raises error with details' do - expect { webhook.destroy }.to raise_error(Exceptions::UnprocessableEntity, /#{Regexp.escape("Trigger: #{trigger.name} (##{trigger.id})")}/) + expect { webhook.destroy }.to raise_error(Exceptions::UnprocessableEntity, %r{#{Regexp.escape("Trigger: #{trigger.name} (##{trigger.id})")}}) end end end diff --git a/spec/requests/api_auth_spec.rb b/spec/requests/api_auth_spec.rb index e924b151a..3856f069d 100644 --- a/spec/requests/api_auth_spec.rb +++ b/spec/requests/api_auth_spec.rb @@ -39,7 +39,7 @@ RSpec.describe 'Api Auth', type: :request do get '/api/v1/sessions', params: {}, as: :json expect(response).to have_http_status(:ok) expect(response.header['Access-Control-Allow-Origin']).to eq('*') - expect(response.header['Cache-Control']).to match(/no-cache, no-store/) + expect(response.header['Cache-Control']).to match(%r{no-cache, no-store}) expect(response.header['Pragma']).to eq('no-cache') expect(response.header['Expires']).to eq('-1') expect(json_response).to be_a_kind_of(Hash) @@ -60,7 +60,7 @@ RSpec.describe 'Api Auth', type: :request do get '/api/v1/tickets', params: {}, as: :json expect(response).to have_http_status(:ok) expect(response.header['Access-Control-Allow-Origin']).to eq('*') - expect(response.header['Cache-Control']).to match(/no-cache, no-store/) + expect(response.header['Cache-Control']).to match(%r{no-cache, no-store}) expect(response.header['Pragma']).to eq('no-cache') expect(response.header['Expires']).to eq('-1') expect(json_response).to be_a_kind_of(Array) @@ -81,7 +81,7 @@ RSpec.describe 'Api Auth', type: :request do get '/api/v1/tickets', params: {}, as: :json expect(response).to have_http_status(:ok) expect(response.header['Access-Control-Allow-Origin']).to eq('*') - expect(response.header['Cache-Control']).to match(/no-cache, no-store/) + expect(response.header['Cache-Control']).to match(%r{no-cache, no-store}) expect(response.header['Pragma']).to eq('no-cache') expect(response.header['Expires']).to eq('-1') expect(json_response).to be_a_kind_of(Array) @@ -113,7 +113,7 @@ RSpec.describe 'Api Auth', type: :request do get '/api/v1/sessions', params: {}, as: :json expect(response).to have_http_status(:ok) expect(response.header['Access-Control-Allow-Origin']).to eq('*') - expect(response.header['Cache-Control']).to match(/no-cache, no-store/) + expect(response.header['Cache-Control']).to match(%r{no-cache, no-store}) expect(response.header['Pragma']).to eq('no-cache') expect(response.header['Expires']).to eq('-1') @@ -263,7 +263,7 @@ RSpec.describe 'Api Auth', type: :request do get '/api/v1/tickets', params: {}, as: :json expect(response).to have_http_status(:ok) expect(response.header['Access-Control-Allow-Origin']).to eq('*') - expect(response.header['Cache-Control']).to match(/no-cache, no-store/) + expect(response.header['Cache-Control']).to match(%r{no-cache, no-store}) expect(response.header['Pragma']).to eq('no-cache') expect(response.header['Expires']).to eq('-1') expect(json_response).to be_a_kind_of(Array) @@ -301,7 +301,7 @@ RSpec.describe 'Api Auth', type: :request do Setting.set('api_token_access', true) get '/api/v1/tickets', params: {}, as: :json expect(response.header['Access-Control-Allow-Origin']).to eq('*') - expect(response.header['Cache-Control']).to match(/no-cache, no-store/) + expect(response.header['Cache-Control']).to match(%r{no-cache, no-store}) expect(response.header['Pragma']).to eq('no-cache') expect(response.header['Expires']).to eq('-1') expect(response).to have_http_status(:ok) @@ -388,7 +388,7 @@ RSpec.describe 'Api Auth', type: :request do get '/api/v1/tickets', params: {}, as: :json expect(response).to have_http_status(:ok) expect(response.header['Access-Control-Allow-Origin']).to eq('*') - expect(response.header['Cache-Control']).to match(/no-cache, no-store/) + expect(response.header['Cache-Control']).to match(%r{no-cache, no-store}) expect(response.header['Pragma']).to eq('no-cache') expect(response.header['Expires']).to eq('-1') expect(json_response).to be_a_kind_of(Array) diff --git a/spec/requests/channels_twitter_spec.rb b/spec/requests/channels_twitter_spec.rb index 129edadb8..e456bfcb7 100644 --- a/spec/requests/channels_twitter_spec.rb +++ b/spec/requests/channels_twitter_spec.rb @@ -46,7 +46,7 @@ RSpec.describe 'Twitter channel API endpoints', type: :request do end describe 'POST /api/v1/channels_twitter_webhook' do - let(:payload) { params.stringify_keys.to_s.gsub(/=>/, ':').delete(' ') } + let(:payload) { params.stringify_keys.to_s.gsub(%r{=>}, ':').delete(' ') } let(:headers) { { 'x-twitter-webhooks-signature': hash_signature } } let(:params) { { foo: 'bar', for_user_id: twitter_channel.options[:user][:id] } } diff --git a/spec/requests/external_credentials_spec.rb b/spec/requests/external_credentials_spec.rb index ceaf4ae3b..9252feed0 100644 --- a/spec/requests/external_credentials_spec.rb +++ b/spec/requests/external_credentials_spec.rb @@ -372,7 +372,7 @@ RSpec.describe 'External Credentials', type: :request do expect(WebMock) .to have_requested(:post, 'https://api.twitter.com/oauth/request_token') - .with(headers: { 'Authorization' => /oauth_consumer_key="#{twitter_credential.credentials[:consumer_key]}"/ } ) + .with(headers: { 'Authorization' => %r{oauth_consumer_key="#{twitter_credential.credentials[:consumer_key]}"} } ) end it 'redirects to Twitter authorization URL' do diff --git a/spec/requests/integration/telegram_spec.rb b/spec/requests/integration/telegram_spec.rb index a67216021..dfe387505 100644 --- a/spec/requests/integration/telegram_spec.rb +++ b/spec/requests/integration/telegram_spec.rb @@ -181,7 +181,7 @@ RSpec.describe 'Telegram Webhook Integration', type: :request do post callback_url, params: read_message('private', 'document'), as: :json expect(response).to have_http_status(:ok) ticket = Ticket.last - expect(ticket.articles.last.body).to match(/Red dot match(/Full/).and(match(/is invalid/))) + expect(json_response).to include('error' => match(%r{Full}).and(match(%r{is invalid}))) end it 'returns verbose error when resized image is missing' do make_request(avatar_full: base64) - expect(json_response).to include('error' => match(/Resized/).and(match(/is invalid/))) + expect(json_response).to include('error' => match(%r{Resized}).and(match(%r{is invalid}))) end it 'successfully changes avatar' do diff --git a/spec/support/assets_matchers.rb b/spec/support/assets_matchers.rb index 4c4a6d300..61e02e80f 100644 --- a/spec/support/assets_matchers.rb +++ b/spec/support/assets_matchers.rb @@ -52,7 +52,7 @@ RSpec::Matchers.define :include_assets_of do # # @return [Hash, nil] def find_assets_of(object, actual) - actual.dig(object.class.name.gsub(/::/, ''), object.id.to_s) + actual.dig(object.class.name.gsub(%r{::}, ''), object.id.to_s) end end diff --git a/spec/support/searchindex_backend.rb b/spec/support/searchindex_backend.rb index c59d8612e..3b9be72f1 100644 --- a/spec/support/searchindex_backend.rb +++ b/spec/support/searchindex_backend.rb @@ -42,7 +42,7 @@ prepares elasticsearch if ENV['ES_INDEX_RAND'].present? rand_id = ENV.fetch('CI_JOB_ID', "r#{rand(999)}") - test_method_name = self.class.description.gsub(/[^\w]/, '_') + test_method_name = self.class.description.gsub(%r{[^\w]}, '_') ENV['ES_INDEX'] = "es_index_#{test_method_name.downcase}_#{rand_id}_#{rand(999_999_999)}" end if ENV['ES_INDEX'].blank? diff --git a/spec/support/vcr.rb b/spec/support/vcr.rb index bc7d4e158..41fe39ce5 100644 --- a/spec/support/vcr.rb +++ b/spec/support/vcr.rb @@ -1,5 +1,5 @@ VCR_IGNORE_MATCHING_HOSTS = %w[elasticsearch selenium zammad.org zammad.com znuny.com google.com login.microsoftonline.com github.com].freeze -VCR_IGNORE_MATCHING_REGEXPS = [/^192\.168\.\d+\.\d+$/].freeze +VCR_IGNORE_MATCHING_REGEXPS = [%r{^192\.168\.\d+\.\d+$}].freeze VCR.configure do |config| config.cassette_library_dir = 'test/data/vcr_cassettes' @@ -14,7 +14,7 @@ VCR.configure do |config| end config.register_request_matcher(:oauth_headers) do |r1, r2| - without_onetime_oauth_params = ->(params) { params.gsub(/oauth_(nonce|signature|timestamp)="[^"]+", /, '') } + without_onetime_oauth_params = ->(params) { params.gsub(%r{oauth_(nonce|signature|timestamp)="[^"]+", }, '') } r1.headers.except('Authorization') == r2.headers.except('Authorization') && r1.headers['Authorization']&.map(&without_onetime_oauth_params) == @@ -75,8 +75,8 @@ RSpec.configure do |config| vcr_options = Array(example.metadata[:use_vcr]) spec_path = Pathname.new(example.file_path).realpath - cassette_path = spec_path.relative_path_from(Rails.root.join('spec')).sub(/_spec\.rb$/, '') - cassette_name = "#{example.example_group.description} #{example.description}".gsub(/[^0-9A-Za-z.\-]+/, '_').downcase + cassette_path = spec_path.relative_path_from(Rails.root.join('spec')).sub(%r{_spec\.rb$}, '') + cassette_name = "#{example.example_group.description} #{example.description}".gsub(%r{[^0-9A-Za-z.\-]+}, '_').downcase request_profile = [ :method, :uri, diff --git a/spec/system/admin/knowledge_base/public_menu_spec.rb b/spec/system/admin/knowledge_base/public_menu_spec.rb index d5162aa00..047d52547 100644 --- a/spec/system/admin/knowledge_base/public_menu_spec.rb +++ b/spec/system/admin/knowledge_base/public_menu_spec.rb @@ -64,7 +64,7 @@ RSpec.describe 'Admin Panel > Knowledge Base > Public Menu', type: :system, auth def find_locale(location, locale) find_location(location) - .find('.label', text: /#{Regexp.escape locale.system_locale.name}/i) + .find('.label', text: %r{#{Regexp.escape locale.system_locale.name}}i) .ancestor('.kb-menu-preview') end diff --git a/spec/system/basic/richtext_spec.rb b/spec/system/basic/richtext_spec.rb index b9d5bd2e6..f638602a9 100644 --- a/spec/system/basic/richtext_spec.rb +++ b/spec/system/basic/richtext_spec.rb @@ -33,7 +33,7 @@ RSpec.describe 'Richtext', type: :system do 'and some other for browser' ) - expect(element).to have_content(/some test for browser\s?\nand some other for browser/) + expect(element).to have_content(%r{some test for browser\s?\nand some other for browser}) end end @@ -49,7 +49,7 @@ RSpec.describe 'Richtext', type: :system do 'and some other for browser' ) - expect(element).to have_content(/some test for browser\s?\nand some other for browser/) + expect(element).to have_content(%r{some test for browser\s?\nand some other for browser}) end end end diff --git a/spec/system/dashboard_spec.rb b/spec/system/dashboard_spec.rb index f076a7759..8c24aca15 100644 --- a/spec/system/dashboard_spec.rb +++ b/spec/system/dashboard_spec.rb @@ -6,12 +6,12 @@ RSpec.describe 'Dashboard', type: :system, authenticated_as: true do visit 'dashboard' expect(page).to have_css('.stat-widgets') - expect(page).to have_css('.ticket_waiting_time > div > div.stat-title', text: /∅ Waiting time today/i) - expect(page).to have_css('.ticket_escalation > div > div.stat-title', text: /Mood/i) - expect(page).to have_css('.ticket_channel_distribution > div > div.stat-title', text: /Channel Distribution/i) - expect(page).to have_css('.ticket_load_measure > div > div.stat-title', text: /Assigned/i) - expect(page).to have_css('.ticket_in_process > div > div.stat-title', text: /Your tickets in process/i) - expect(page).to have_css('.ticket_reopen > div > div.stat-title', text: /Reopening rate/i) + expect(page).to have_css('.ticket_waiting_time > div > div.stat-title', text: %r{∅ Waiting time today}i) + expect(page).to have_css('.ticket_escalation > div > div.stat-title', text: %r{Mood}i) + expect(page).to have_css('.ticket_channel_distribution > div > div.stat-title', text: %r{Channel Distribution}i) + expect(page).to have_css('.ticket_load_measure > div > div.stat-title', text: %r{Assigned}i) + expect(page).to have_css('.ticket_in_process > div > div.stat-title', text: %r{Your tickets in process}i) + expect(page).to have_css('.ticket_reopen > div > div.stat-title', text: %r{Reopening rate}i) end context 'when customer role is named different', authenticated_as: :authenticate do diff --git a/spec/system/knowledge_base_public/editor_spec.rb b/spec/system/knowledge_base_public/editor_spec.rb index 45a5cef7c..c5c7c564d 100644 --- a/spec/system/knowledge_base_public/editor_spec.rb +++ b/spec/system/knowledge_base_public/editor_spec.rb @@ -14,7 +14,7 @@ RSpec.describe 'Public Knowledge Base for editor', type: :system, authenticated_ it 'expect to have edit button' do button = find '.topbar-btn' - expect(button['href']).to match(/edit$/) + expect(button['href']).to match(%r{edit$}) end end diff --git a/spec/system/settings/proxy_spec.rb b/spec/system/settings/proxy_spec.rb index dff8df964..c1d0c1cdc 100644 --- a/spec/system/settings/proxy_spec.rb +++ b/spec/system/settings/proxy_spec.rb @@ -43,7 +43,7 @@ RSpec.describe 'Manage > Settings > System > Network', type: :system do click_on 'Test Connection' expect(page).to have_css('h1.modal-title', text: 'Error', wait: 5) - expect(page).to have_css('div.modal-body', text: /Invalid proxy address/, wait: 5) + expect(page).to have_css('div.modal-body', text: %r{Invalid proxy address}, wait: 5) expect(page).to have_button('Test Connection', visible: :visible, wait: 5) expect(page).to have_button('Submit', visible: :hidden, wait: 5) @@ -61,7 +61,7 @@ RSpec.describe 'Manage > Settings > System > Network', type: :system do click_on 'Test Connection' expect(page).to have_css('h1.modal-title', text: 'Error', wait: 5) - expect(page).to have_css('div.modal-body', text: /Failed to open TCP connection/, wait: 5) + expect(page).to have_css('div.modal-body', text: %r{Failed to open TCP connection}, wait: 5) expect(page).to have_button('Test Connection', visible: :visible, wait: 5) expect(page).to have_button('Submit', visible: :hidden, wait: 5) @@ -79,7 +79,7 @@ RSpec.describe 'Manage > Settings > System > Network', type: :system do click_on 'Test Connection' expect(page).to have_css('h1.modal-title', text: 'Error', wait: 5) - expect(page).to have_css('div.modal-body', text: /Access Denied/, wait: 5) + expect(page).to have_css('div.modal-body', text: %r{Access Denied}, wait: 5) expect(page).to have_button('Test Connection', visible: :visible, wait: 5) expect(page).to have_button('Submit', visible: :hidden, wait: 5) @@ -97,7 +97,7 @@ RSpec.describe 'Manage > Settings > System > Network', type: :system do click_on 'Test Connection' expect(page).to have_css('h1.modal-title', text: 'Error', wait: 5) - expect(page).to have_css('div.modal-body', text: /Access Denied/, wait: 5) + expect(page).to have_css('div.modal-body', text: %r{Access Denied}, wait: 5) expect(page).to have_button('Test Connection', visible: :visible, wait: 5) expect(page).to have_button('Submit', visible: :hidden, wait: 5) diff --git a/spec/system/ticket/history_spec.rb b/spec/system/ticket/history_spec.rb index a0267555b..1c3914033 100644 --- a/spec/system/ticket/history_spec.rb +++ b/spec/system/ticket/history_spec.rb @@ -44,38 +44,38 @@ RSpec.describe 'Ticket history', type: :system, authenticated_as: true, time_zon end it "translates timestamp when attribute's tag is datetime" do - expect(page).to have_css('li', text: /22.01.2021 13:40/) + expect(page).to have_css('li', text: %r{22.01.2021 13:40}) end it 'does not include time with UTC format' do - expect(page).to have_no_text(/ UTC/) + expect(page).to have_no_text(%r{ UTC}) end it 'translates value when attribute is state' do - expect(page).to have_css('li', text: /Ticket Status von 'neu'/) + expect(page).to have_css('li', text: %r{Ticket Status von 'neu'}) end it 'translates value when attribute is priority' do - expect(page).to have_css('li', text: /Ticket Priorität von '1 niedrig'/) + expect(page).to have_css('li', text: %r{Ticket Priorität von '1 niedrig'}) end it 'translates value when attribute is internal' do - expect(page).to have_css('li', text: /Artikel intern von 'true'/) + expect(page).to have_css('li', text: %r{Artikel intern von 'true'}) end it 'translates last_contact_at display attribute' do - expect(page).to have_css('li', text: /Ticket Letzter Kontakt von '22.01.2021 13:40' → '07.04.2021 00:30'/) + expect(page).to have_css('li', text: %r{Ticket Letzter Kontakt von '22.01.2021 13:40' → '07.04.2021 00:30'}) end it 'translates last_contact_customer_at display attribute' do - expect(page).to have_css('li', text: /Ticket Letzter Kontakt \(Kunde\) von '22.01.2021 13:40' → '07.04.2021 00:30'/) + expect(page).to have_css('li', text: %r{Ticket Letzter Kontakt \(Kunde\) von '22.01.2021 13:40' → '07.04.2021 00:30'}) end it 'translates last_contact_agent_at display attribute' do - expect(page).to have_css('li', text: /Ticket Letzter Kontakt \(Agent\) von '22.01.2021 13:40' → '07.04.2021 00:30'/) + expect(page).to have_css('li', text: %r{Ticket Letzter Kontakt \(Agent\) von '22.01.2021 13:40' → '07.04.2021 00:30'}) end it 'translates pending_time display attribute' do - expect(page).to have_css('li', text: /Ticket Warten bis '07.04.2021 00:30'/) + expect(page).to have_css('li', text: %r{Ticket Warten bis '07.04.2021 00:30'}) end end diff --git a/spec/system/ticket/update/full_quote_header_spec.rb b/spec/system/ticket/update/full_quote_header_spec.rb index 8fe7389d6..6cb4b38b3 100644 --- a/spec/system/ticket/update/full_quote_header_spec.rb +++ b/spec/system/ticket/update/full_quote_header_spec.rb @@ -183,9 +183,9 @@ RSpec.describe 'Ticket > Update > Full Quote Header', current_user_id: -> { curr def confirm_style case style when :forward - citation.text.match?(/Subject(.+)\nDate(.+)/) + citation.text.match?(%r{Subject(.+)\nDate(.+)}) when :reply - citation.text.match?(/^On(.+)wrote:$/) + citation.text.match?(%r{^On(.+)wrote:$}) end end diff --git a/spec/system/user/history_spec.rb b/spec/system/user/history_spec.rb index 4aeb90074..91319b267 100644 --- a/spec/system/user/history_spec.rb +++ b/spec/system/user/history_spec.rb @@ -36,18 +36,18 @@ RSpec.describe 'Ticket history', type: :system, authenticated_as: true, time_zon end it "translates timestamp when attribute's tag is datetime" do - expect(page).to have_css('li', text: /'22.01.2021 00:00'/) + expect(page).to have_css('li', text: %r{'22.01.2021 00:00'}) end it 'does not include time with UTC format' do - expect(page).to have_no_text(/ UTC/) + expect(page).to have_no_text(%r{ UTC}) end it 'translates out_of_office_start_at value to time stamp' do - expect(page).to have_css('li', text: /Benutzer out_of_office_start_at '22.01.2021 00:00'/) + expect(page).to have_css('li', text: %r{Benutzer out_of_office_start_at '22.01.2021 00:00'}) end it 'translates out_of_office_end_at value to time stamp' do - expect(page).to have_css('li', text: /Benutzer out_of_office_end_at '06.04.2021 01:00'/) + expect(page).to have_css('li', text: %r{Benutzer out_of_office_end_at '06.04.2021 01:00'}) end end 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 92bb429e0..aa71c60bd 100644 --- a/test/browser/agent_ticket_email_reply_keep_body_test.rb +++ b/test/browser/agent_ticket_email_reply_keep_body_test.rb @@ -133,7 +133,7 @@ class AgentTicketEmailReplyKeepBodyTest < TestCase full_text = @browser.find_element(css: '.content.active .article-new .articleNewEdit-body').text - match = full_text.match(/\nOn (.*?) Nicole Braun wrote:/) + match = full_text.match(%r{\nOn (.*?) Nicole Braun wrote:}) assert match assert match[1] assert Time.zone.parse(match[1]) @@ -157,7 +157,7 @@ class AgentTicketEmailReplyKeepBodyTest < TestCase full_text = @browser.find_element(css: '.content.active .article-new .articleNewEdit-body').text - match = full_text.match(/\nOn (.*?) Nicole Braun wrote:/) + match = full_text.match(%r{\nOn (.*?) Nicole Braun wrote:}) assert_nil match # after test, turn full quote header back on again @@ -215,7 +215,7 @@ class AgentTicketEmailReplyKeepBodyTest < TestCase full_text = @browser.find_element(css: '.content.active .article-new .articleNewEdit-body').text - match = full_text.match(/\nAm (.*?), schrieb Nicole Braun:/) + match = full_text.match(%r{\nAm (.*?), schrieb Nicole Braun:}) assert match datestamp = match[1] diff --git a/test/browser/agent_ticket_tag_test.rb b/test/browser/agent_ticket_tag_test.rb index 88a5c8724..3f921a4e8 100644 --- a/test/browser/agent_ticket_tag_test.rb +++ b/test/browser/agent_ticket_tag_test.rb @@ -36,7 +36,7 @@ class AgentTicketTagTest < TestCase css: '.active .newTicket button.js-submit', ) sleep 5 - if !@browser.current_url.match?(/#{Regexp.quote('#ticket/zoom/')}/) + if !@browser.current_url.match?(%r{#{Regexp.quote('#ticket/zoom/')}}) raise 'Unable to create ticket!' end @@ -68,7 +68,7 @@ class AgentTicketTagTest < TestCase click(css: '#global-search') click(css: '.active .newTicket button.js-submit') sleep 5 - if !@browser.current_url.match?(/#{Regexp.quote('#ticket/zoom/')}/) + if !@browser.current_url.match?(%r{#{Regexp.quote('#ticket/zoom/')}}) raise 'Unable to create ticket!' end @@ -441,7 +441,7 @@ class AgentTicketTagTest < TestCase css: '.active .newTicket button.js-submit', ) sleep 5 - if !@browser.current_url.match?(/#{Regexp.quote('#ticket/zoom/')}/) + if !@browser.current_url.match?(%r{#{Regexp.quote('#ticket/zoom/')}}) raise 'Unable to create ticket!' end diff --git a/test/browser/keyboard_shortcuts_test.rb b/test/browser/keyboard_shortcuts_test.rb index 1a1088338..d2b1e609f 100644 --- a/test/browser/keyboard_shortcuts_test.rb +++ b/test/browser/keyboard_shortcuts_test.rb @@ -15,7 +15,7 @@ class KeyboardShortcutsTest < TestCase shortcut(key: 'h') # ff issue, sometimes shortcut is not fired in browser test env - if ENV['BROWSER'] && ENV['BROWSER'] =~ /firefox/i + if ENV['BROWSER'] && ENV['BROWSER'] =~ %r{firefox}i exists = false (1..4).each do |_count| sleep 1 diff --git a/test/browser_test_helper.rb b/test/browser_test_helper.rb index bb80f4006..8a848e91f 100644 --- a/test/browser_test_helper.rb +++ b/test/browser_test_helper.rb @@ -64,7 +64,7 @@ class TestCase < ActiveSupport::TestCase end def browser_support_cookies - if browser.match?(/(internet_explorer|ie)/i) + if browser.match?(%r{(internet_explorer|ie)}i) return false end @@ -168,7 +168,7 @@ class TestCase < ActiveSupport::TestCase browser_width = ENV['BROWSER_WIDTH'] || 1024 browser_height = ENV['BROWSER_HEIGHT'] || 800 local_browser.manage.window.resize_to(browser_width, browser_height) - if !ENV['REMOTE_URL']&.match?(/saucelabs|(grid|ci)\.(zammad\.org|znuny\.com)/i) + if !ENV['REMOTE_URL']&.match?(%r{saucelabs|(grid|ci)\.(zammad\.org|znuny\.com)}i) if @browsers.count == 1 local_browser.manage.window.move_to(0, 0) else @@ -420,7 +420,7 @@ class TestCase < ActiveSupport::TestCase instance.get(params[:url]) # check if reload was successfull - if !instance.find_elements(css: 'body')[0] || instance.find_elements(css: 'body')[0].text =~ /unavailable or too busy/i + if !instance.find_elements(css: 'body')[0] || instance.find_elements(css: 'body')[0].text =~ %r{unavailable or too busy}i instance.navigate.refresh end end @@ -441,7 +441,7 @@ class TestCase < ActiveSupport::TestCase instance = params[:browser] || @browser sleep 0.7 current_url = instance.current_url - if !current_url.match?(/#{Regexp.quote(params[:url])}/) + if !current_url.match?(%r{#{Regexp.quote(params[:url])}}) screenshot(browser: instance, comment: 'location_check_failed') raise "url #{current_url} is not matching #{params[:url]}" end @@ -464,7 +464,7 @@ class TestCase < ActiveSupport::TestCase instance.navigate.refresh # check if reload was successfull - if !instance.find_elements(css: 'body')[0] || instance.find_elements(css: 'body')[0].text =~ /unavailable or too busy/i + if !instance.find_elements(css: 'body')[0] || instance.find_elements(css: 'body')[0].text =~ %r{unavailable or too busy}i instance.navigate.refresh end screenshot(browser: instance, comment: 'reload_after') @@ -813,7 +813,7 @@ class TestCase < ActiveSupport::TestCase end # it's not working stable with ff via selenium, use js - if browser =~ /firefox/i && params[:css].include?('[data-name=') + if browser =~ %r{firefox}i && params[:css].include?('[data-name=') log('set_ff_trigger_workaround', params) instance.execute_script("$('#{params[:css]}').trigger('focusout')") end @@ -1051,7 +1051,7 @@ class TestCase < ActiveSupport::TestCase begin text = if params[:attribute] element.attribute(params[:attribute]) - elsif params[:css].match?(/(input|textarea)/i) + elsif params[:css].match?(%r{(input|textarea)}i) element.attribute('value') else element.text @@ -1067,17 +1067,17 @@ class TestCase < ActiveSupport::TestCase # do cleanups (needed for richtext tests) if params[:cleanup] - text.gsub!(/\s+$/m, '') - params[:value].gsub!(/\s+$/m, '') + text.gsub!(%r{\s+$}m, '') + params[:value].gsub!(%r{\s+$}m, '') end match = false if params[:no_quote] #puts "aaaa #{text}/#{params[:value]}" - if text =~ /#{params[:value]}/i + if text =~ %r{#{params[:value]}}i match = $1 || true end - elsif text.match?(/#{Regexp.quote(params[:value])}/i) + elsif text.match?(%r{#{Regexp.quote(params[:value])}}i) match = true end @@ -1204,14 +1204,14 @@ set type of task (closeTab, closeNextInOverview, stayOnTab) cookies = instance.manage.all_cookies cookies.each do |cookie| # :name=>"_zammad_session_c25832f4de2", :value=>"adc31cd21615cb0a7ab269184ec8b76f", :path=>"/", :domain=>"localhost", :expires=>nil, :secure=>false} - next if !cookie[:name].match?(/#{params[:name]}/i) + next if !cookie[:name].match?(%r{#{params[:name]}}i) - if params.key?(:value) && cookie[:value].to_s =~ /#{params[:value]}/i + if params.key?(:value) && cookie[:value].to_s =~ %r{#{params[:value]}}i assert(true, "matching value '#{params[:value]}' in cookie '#{cookie}'") else raise "not matching value '#{params[:value]}' in cookie '#{cookie}'" end - if params.key?(:expires) && cookie[:expires].to_s =~ /#{params[:expires]}/i + if params.key?(:expires) && cookie[:expires].to_s =~ %r{#{params[:expires]}}i assert(true, "matching expires '#{params[:expires].inspect}' in cookie '#{cookie}'") else raise "not matching expires '#{params[:expires]}' in cookie '#{cookie}'" @@ -1244,7 +1244,7 @@ set type of task (closeTab, closeNextInOverview, stayOnTab) instance = params[:browser] || @browser title = instance.title - if title.match?(/#{params[:value]}/i) + if title.match?(%r{#{params[:value]}}i) assert(true, "matching '#{params[:value]}' in title '#{title}'") else raise "not matching '#{params[:value]}' in title '#{title}'" @@ -1276,7 +1276,7 @@ set type of task (closeTab, closeNextInOverview, stayOnTab) # verify title if data[:title] title = instance.find_elements(css: '.tasks .is-active')[0].text.strip - if title.match?(/#{data[:title]}/i) + if title.match?(%r{#{data[:title]}}i) assert(true, "matching '#{data[:title]}' in title '#{title}'") else screenshot(browser: instance, comment: 'verify_task_failed') @@ -1466,12 +1466,12 @@ set type of task (closeTab, closeNextInOverview, stayOnTab) else text = if params[:attribute] element.attribute(params[:attribute]) - elsif selector.match?(/(input|textarea)/i) + elsif selector.match?(%r{(input|textarea)}i) element.attribute('value') else element.text end - if text.match?(/#{params[:value]}/i) + if text.match?(%r{#{params[:value]}}i) assert(true, "'#{params[:value]}' found in '#{text}'") sleep 0.5 return true @@ -1534,7 +1534,7 @@ wait untill text in selector disabppears if params[:value] begin text = instance.find_elements(css: params[:css])[0].text - if !text.match?(/#{params[:value]}/i) + if !text.match?(%r{#{params[:value]}}i) assert(true, "not matching '#{params[:value]}' in text '#{text}'") sleep 1 return true @@ -1914,7 +1914,7 @@ wait untill text in selector disabppears 11.times do element = instance.find_elements(css: 'body')[0] text = element.text - if text.match?(/#{Regexp.quote(data[:name])}/) + if text.match?(%r{#{Regexp.quote(data[:name])}}) assert(true, 'overview created') overview = { name: name, @@ -2028,7 +2028,7 @@ wait untill text in selector disabppears 11.times do element = instance.find_elements(css: 'body')[0] text = element.text - if text.match?(/#{Regexp.quote(data[:name])}/) + if text.match?(%r{#{Regexp.quote(data[:name])}}) assert(true, 'overview updated') overview = { name: name, @@ -2296,11 +2296,11 @@ wait untill text in selector disabppears sleep 1 9.times do - if instance.current_url.match?(/#{Regexp.quote('#ticket/zoom/')}/) + if instance.current_url.match?(%r{#{Regexp.quote('#ticket/zoom/')}}) assert(true, 'ticket created') sleep 2 id = instance.current_url - id.gsub!(//,) + id.gsub!(%r{},) id.gsub!(%r{^.+?/(\d+)$}, '\\1') element = instance.find_elements(css: '.content.active .ticketZoom-header .ticket-number')[0] @@ -2541,7 +2541,7 @@ wait untill text in selector disabppears begin text = instance.find_elements(css: '.content.active .js-reset')[0].text - if text.match?(/(Discard your unsaved changes.|Verwerfen der)/) + if text.match?(%r{(Discard your unsaved changes.|Verwerfen der)}) found = true end rescue @@ -2620,7 +2620,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.match?(/#{data[:title]}/i) + if title.match?(%r{#{data[:title]}}i) assert(true, "matching '#{data[:title]}' in title '#{title}'") else raise "not matching '#{data[:title]}' in title '#{title}'" @@ -2629,7 +2629,7 @@ wait untill text in selector disabppears if data[:body] body = instance.find_elements(css: '.content.active [data-name="body"]').first.text.strip - if body.match?(/#{data[:body]}/i) + if body.match?(%r{#{data[:body]}}i) assert(true, "matching '#{data[:body]}' in body '#{body}'") else raise "not matching '#{data[:body]}' in body '#{body}'" @@ -2639,7 +2639,7 @@ wait untill text in selector disabppears 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) + if value.match?(%r{#{local_value}}i) assert(true, "matching '#{value}' in #{local_key} '#{local_value}'") else raise "not matching '#{value}' in #{local_key} '#{local_value}'" @@ -2648,7 +2648,7 @@ wait untill text in selector disabppears 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) + if value.match?(%r{#{local_value}}i) assert(true, "matching '#{value}' in #{local_key} '#{local_value}'") else raise "not matching '#{value}' in #{local_key} '#{local_value}'" @@ -2766,7 +2766,7 @@ wait untill text in selector disabppears element.click sleep 1 number = instance.find_element(css: '.content.active .ticketZoom-header .ticket-number').text - if !number.match?(/#{params[:number]}/) + if !number.match?(%r{#{params[:number]}}) screenshot(browser: instance, comment: 'ticket_open_by_overview_open_failed_failed') raise "unable to open ticket #{params[:number]}!" end @@ -2804,7 +2804,7 @@ wait untill text in selector disabppears css: '.content.active .ticketZoom-header .ticket-number' ) number = instance.find_elements(css: '.content.active .ticketZoom-header .ticket-number')[0].text - if !number.match?(/#{params[:number]}/) + if !number.match?(%r{#{params[:number]}}) screenshot(browser: instance, comment: 'ticket_open_by_search_failed') raise "unable to search/find ticket #{params[:number]}!" end @@ -2838,7 +2838,7 @@ wait untill text in selector disabppears instance.execute_script("$(\".js-global-search-result a:contains('#{params[:title]}') .nav-tab-name\").first().click()") sleep 1 title = instance.find_elements(css: '.content.active .ticketZoom-header .js-objectTitle')[0].text - if !title.match?(/#{params[:title]}/) + if !title.match?(%r{#{params[:title]}}) screenshot(browser: instance, comment: 'ticket_open_by_title_failed') raise "unable to search/find ticket #{params[:title]}!" end @@ -2934,7 +2934,7 @@ wait untill text in selector disabppears css: '.content.active h1' ) name = instance.find_elements(css: '.content.active h1')[0].text - if !name.match?(/#{params[:value]}/) + if !name.match?(%r{#{params[:value]}}) screenshot(browser: instance, comment: 'organization_open_by_search_failed') raise "unable to search/find org #{params[:value]}!" end @@ -2970,7 +2970,7 @@ wait untill text in selector disabppears css: '.content.active h1' ) name = instance.find_elements(css: '.content.active h1')[0].text - if !name.match?(/#{params[:value]}/) + if !name.match?(%r{#{params[:value]}}) screenshot(browser: instance, comment: 'user_open_by_search_failed') raise "unable to search/find user #{params[:value]}!" end @@ -3397,7 +3397,7 @@ wait untill text in selector disabppears 7.times do element = instance.find_elements(css: 'body')[0] text = element.text - if text.match?(/#{Regexp.quote(data[:name])}/) + if text.match?(%r{#{Regexp.quote(data[:name])}}) assert(true, 'calendar created') sleep 1 return true @@ -3460,7 +3460,7 @@ wait untill text in selector disabppears 7.times do element = instance.find_elements(css: 'body')[0] text = element.text - if text.match?(/#{Regexp.quote(data[:name])}/) + if text.match?(%r{#{Regexp.quote(data[:name])}}) assert(true, 'sla created') sleep 1 return true @@ -3527,7 +3527,7 @@ wait untill text in selector disabppears 7.times do element = instance.find_elements(css: 'body')[0] text = element.text - if text.match?(/#{Regexp.quote(data[:name])}/) + if text.match?(%r{#{Regexp.quote(data[:name])}}) assert(true, 'text module created') sleep 1 return true @@ -3594,7 +3594,7 @@ wait untill text in selector disabppears 11.times do element = instance.find_elements(css: 'body')[0] text = element.text - if text.match?(/#{Regexp.quote(data[:name])}/) + if text.match?(%r{#{Regexp.quote(data[:name])}}) assert(true, 'signature created') sleep 1 return true @@ -3663,7 +3663,7 @@ wait untill text in selector disabppears element = instance.find_elements(css: 'body')[0] text = element.text - if text.match?(/#{Regexp.quote(data[:name])}/) + if text.match?(%r{#{Regexp.quote(data[:name])}}) assert(true, 'group created') modal_disappear(browser: instance) # wait until modal has gone @@ -3867,7 +3867,7 @@ wait untill text in selector disabppears element = instance.find_elements(css: 'body')[0] text = element.text - if text.match?(/#{Regexp.quote(data[:name])}/) + if text.match?(%r{#{Regexp.quote(data[:name])}}) assert(true, 'role created') modal_disappear(browser: instance) # wait until modal has gone @@ -3990,7 +3990,7 @@ wait untill text in selector disabppears element = instance.find_elements(css: 'body')[0] text = element.text - if text.match?(/#{Regexp.quote(data[:name])}/) + if text.match?(%r{#{Regexp.quote(data[:name])}}) assert(true, 'role created') modal_disappear(browser: instance) # wait until modal has gone @@ -4456,9 +4456,9 @@ wait untill text in selector disabppears def quote(string) string_quoted = string - string_quoted.gsub!(/&/, '&') - string_quoted.gsub!(//, '>') + string_quoted.gsub!(%r{&}, '&') + string_quoted.gsub!(%r{<}, '<') + string_quoted.gsub!(%r{>}, '>') string_quoted end @@ -4477,7 +4477,7 @@ wait untill text in selector disabppears if instance logs = instance.manage.logs.get(:browser) logs.each do |log| - next if log.level == 'WARNING' && log.message =~ /Declaration\sdropped./ # ignore ff css warnings + next if log.level == 'WARNING' && log.message =~ %r{Declaration\sdropped.} # ignore ff css warnings time = Time.zone.parse(Time.zone.at(log.timestamp / 1000).to_datetime.to_s) puts "#{time}/#{log.level}: #{log.message}" @@ -4818,7 +4818,7 @@ wait untill text in selector disabppears 11.times do element = instance.find_elements(css: 'body')[0] text = element.text - if text.match?(/#{Regexp.quote(data[:name])}/) + if text.match?(%r{#{Regexp.quote(data[:name])}}) assert(true, 'object manager attribute updated') sleep 1 return true diff --git a/test/integration/email_helper_test.rb b/test/integration/email_helper_test.rb index 9493c2ac6..dde583e14 100644 --- a/test/integration/email_helper_test.rb +++ b/test/integration/email_helper_test.rb @@ -194,7 +194,7 @@ class EmailHelperTest < ActiveSupport::TestCase } ) assert_equal('invalid', result[:result]) - assert_match(/Host not reachable|No route to host/, result[:message_human]) + assert_match(%r{Host not reachable|No route to host}, result[:message_human]) assert_equal('172.42.42.42', result[:settings][:options][:host]) # gmail @@ -209,7 +209,7 @@ class EmailHelperTest < ActiveSupport::TestCase } ) assert_equal('invalid', result[:result]) - assert_match(/Authentication failed, username incorrect|Authentication failed, invalid credentials/, result[:message_human]) + assert_match(%r{Authentication failed, username incorrect|Authentication failed, invalid credentials}, result[:message_human]) assert_equal('imap.gmail.com', result[:settings][:options][:host]) result = EmailHelper::Probe.inbound( @@ -226,9 +226,9 @@ class EmailHelperTest < ActiveSupport::TestCase # if we have to many failed logins, we need to handle another error message if result[:message_human].present? - assert_match(/Authentication failed, username incorrect|Authentication failed, invalid credentials/, result[:message_human]) + assert_match(%r{Authentication failed, username incorrect|Authentication failed, invalid credentials}, result[:message_human]) else - assert_match(/Web login required/, result[:message]) + assert_match(%r{Web login required}, result[:message]) end assert_equal('imap.gmail.com', result[:settings][:options][:host]) @@ -338,7 +338,7 @@ class EmailHelperTest < ActiveSupport::TestCase 'some@example.com', ) assert_equal('invalid', result[:result]) - assert_match(/Host not reachable|No route to host/, result[:message_human]) + assert_match(%r{Host not reachable|No route to host}, result[:message_human]) assert_equal('172.42.42.42', result[:settings][:options][:host]) # gmail @@ -378,7 +378,7 @@ class EmailHelperTest < ActiveSupport::TestCase 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]) + assert_match(%r{Please log in with your web browser and then try again}, result[:message]) end assert_equal('smtp.gmail.com', result[:settings][:options][:host]) diff --git a/test/integration/email_keep_on_server_test.rb b/test/integration/email_keep_on_server_test.rb index b37504dd5..dfa002e9c 100644 --- a/test/integration/email_keep_on_server_test.rb +++ b/test/integration/email_keep_on_server_test.rb @@ -75,7 +75,7 @@ To: shugo@example.com Message-ID: hello world -".gsub(/\n/, "\r\n"), [], Time.zone.now) +".gsub(%r{\n}, "\r\n"), [], Time.zone.now) # verify if message is still on server message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII') @@ -112,7 +112,7 @@ To: shugo@example.com Message-ID: hello world -".gsub(/\n/, "\r\n"), [], Time.zone.now) +".gsub(%r{\n}, "\r\n"), [], Time.zone.now) message_meta = imap.fetch(1, ['FLAGS'])[0].attr assert(message_meta['FLAGS'].include?(:Seen)) @@ -163,7 +163,7 @@ To: shugo@example.com Message-ID: hello world -".gsub(/\n/, "\r\n"), [], Time.zone.now) +".gsub(%r{\n}, "\r\n"), [], Time.zone.now) # verify if message is still on server message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII') @@ -188,7 +188,7 @@ To: shugo@example.com Message-ID: hello world -".gsub(/\n/, "\r\n"), [], Time.zone.now) +".gsub(%r{\n}, "\r\n"), [], Time.zone.now) # verify if message is still on server message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII') @@ -213,7 +213,7 @@ To: shugo@example.com Message-ID: hello world -".gsub(/\n/, "\r\n"), [], Time.zone.now) +".gsub(%r{\n}, "\r\n"), [], Time.zone.now) # verify if message is still on server message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII') diff --git a/test/integration/email_postmaster_to_sender.rb b/test/integration/email_postmaster_to_sender.rb index d95644ee6..c18a9e3a1 100644 --- a/test/integration/email_postmaster_to_sender.rb +++ b/test/integration/email_postmaster_to_sender.rb @@ -90,7 +90,7 @@ To: shugo@example.com Message-ID: <#{@test_id}@zammad.test.com> Oversized Email Message Body #{'#' * 120_000} -".gsub(/\n/, "\r\n") +".gsub(%r{\n}, "\r\n") large_message_md5 = Digest::MD5.hexdigest(large_message) large_message_size = format('%.2f', MB: large_message.size.to_f / 1024 / 1024) @@ -103,7 +103,7 @@ Oversized Email Message Body #{'#' * 120_000} # /tmp/oversized_mail/yyyy-mm-ddThh:mm:ss-:md5.eml path = Rails.root.join('tmp/oversized_mail') target_files = Dir.entries(path).select do |filename| - filename =~ /^#{large_message_md5}\.eml$/ + filename =~ %r{^#{large_message_md5}\.eml$} end assert(target_files.present?, 'Large message .eml log file must be present.') @@ -182,7 +182,7 @@ To: shugo@example.com Message-ID: <#{@test_id}@zammad.test.com> Oversized Email Message Body #{'#' * 120_000} -".gsub(/\n/, "\r\n") +".gsub(%r{\n}, "\r\n") imap.append(@folder, large_message, [], Time.zone.now) @@ -192,7 +192,7 @@ Oversized Email Message Body #{'#' * 120_000} # /tmp/oversized_mail/yyyy-mm-ddThh:mm:ss-:md5.eml path = Rails.root.join('tmp/oversized_mail') target_files = Dir.entries(path).select do |filename| - filename =~ /^.+?\.eml$/ + filename =~ %r{^.+?\.eml$} end assert_not(target_files.blank?, 'Large message .eml log file must be blank.') diff --git a/test/integration/otrs_import_test.rb b/test/integration/otrs_import_test.rb index 56c23acdf..3887c5f1b 100644 --- a/test/integration/otrs_import_test.rb +++ b/test/integration/otrs_import_test.rb @@ -22,7 +22,7 @@ class OtrsImportTest < ActiveSupport::TestCase if ENV['IMPORT_OTRS_ENDPOINT'] =~ %r{^(http|https)://((.+?)\..+?)/} http = $1 system_id = $3 - system_id.gsub!(/[A-z]/, '') # strip chars + system_id.gsub!(%r{[A-z]}, '') # strip chars end assert_equal( system_id, Setting.get('system_id'), 'system_id' ) assert_equal( http, Setting.get('http_type'), 'http_type' ) diff --git a/test/integration/slack_test.rb b/test/integration/slack_test.rb index 21188912a..43f03f4b8 100644 --- a/test/integration/slack_test.rb +++ b/test/integration/slack_test.rb @@ -302,7 +302,7 @@ class SlackTest < ActiveSupport::TestCase channel_history['messages'].each do |message| next if !message['text'] - if message['text'].match?(/#{search_for}/i) + if message['text'].match?(%r{#{search_for}}i) message_count += 1 p "SUCCESS: message with #{search_for} found #{message_count} time(s)!" end diff --git a/test/integration/user_agent_test.rb b/test/integration/user_agent_test.rb index 7f36c1a06..d5dd364d1 100644 --- a/test/integration/user_agent_test.rb +++ b/test/integration/user_agent_test.rb @@ -27,7 +27,7 @@ class UserAgentTest < ActiveSupport::TestCase assert(result.body.include?('"123"')) assert(result.body.include?('"content_type_requested":null')) if ENV['ZAMMAD_PROXY_TEST'] == 'true' && ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK'] - assert_match(/"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"/, result.body) + assert_match(%r{"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"}, result.body) end # get / 404 @@ -54,7 +54,7 @@ class UserAgentTest < ActiveSupport::TestCase assert(result.body.include?('"some value"')) assert(result.body.include?('"application/x-www-form-urlencoded"')) if ENV['ZAMMAD_PROXY_TEST'] == 'true' && ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK'] - assert_match(/"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"/, result.body) + assert_match(%r{"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"}, result.body) end # post / 404 @@ -84,7 +84,7 @@ class UserAgentTest < ActiveSupport::TestCase assert(result.body.include?('"some value"')) assert(result.body.include?('"application/x-www-form-urlencoded"')) if ENV['ZAMMAD_PROXY_TEST'] == 'true' && ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK'] - assert_match(/"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"/, result.body) + assert_match(%r{"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"}, result.body) end # put / 404 @@ -110,7 +110,7 @@ class UserAgentTest < ActiveSupport::TestCase assert(result.body.include?('"delete"')) assert(result.body.include?('"content_type_requested":null')) if ENV['ZAMMAD_PROXY_TEST'] == 'true' && ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK'] - assert_match(/"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"/, result.body) + assert_match(%r{"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"}, result.body) end # delete / 404 @@ -141,7 +141,7 @@ class UserAgentTest < ActiveSupport::TestCase assert(result.body.include?('"123"')) assert(result.body.include?('"content_type_requested":null')) if ENV['ZAMMAD_PROXY_TEST'] == 'true' && ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK'] - assert_match(/"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"/, result.body) + assert_match(%r{"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"}, result.body) end # get / 401 @@ -177,7 +177,7 @@ class UserAgentTest < ActiveSupport::TestCase assert(result.body.include?('"some value"')) assert(result.body.include?('"application/x-www-form-urlencoded"')) if ENV['ZAMMAD_PROXY_TEST'] == 'true' && ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK'] - assert_match(/"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"/, result.body) + assert_match(%r{"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"}, result.body) end # post / 401 @@ -215,7 +215,7 @@ class UserAgentTest < ActiveSupport::TestCase assert(result.body.include?('"some value"')) assert(result.body.include?('"application/x-www-form-urlencoded"')) if ENV['ZAMMAD_PROXY_TEST'] == 'true' && ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK'] - assert_match(/"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"/, result.body) + assert_match(%r{"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"}, result.body) end # put / 401 @@ -250,7 +250,7 @@ class UserAgentTest < ActiveSupport::TestCase assert(result.body.include?('"delete"')) assert(result.body.include?('"content_type_requested":null')) if ENV['ZAMMAD_PROXY_TEST'] == 'true' && ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK'] - assert_match(/"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"/, result.body) + assert_match(%r{"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"}, result.body) end # delete / 401 @@ -283,7 +283,7 @@ class UserAgentTest < ActiveSupport::TestCase assert(result.body.include?('"abc"')) assert(result.body.include?('"content_type_requested":null')) if ENV['ZAMMAD_PROXY_TEST'] == 'true' && ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK'] - assert_match(/"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"/, result.body) + assert_match(%r{"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"}, result.body) end # get / 301 @@ -302,7 +302,7 @@ class UserAgentTest < ActiveSupport::TestCase assert(result.body.include?('"abc"')) assert(result.body.include?('"content_type_requested":null')) if ENV['ZAMMAD_PROXY_TEST'] == 'true' && ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK'] - assert_match(/"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"/, result.body) + assert_match(%r{"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"}, result.body) end # get / 401 @@ -334,7 +334,7 @@ class UserAgentTest < ActiveSupport::TestCase assert(result.body.include?('"123"')) assert(result.body.include?('"content_type_requested":null')) if ENV['ZAMMAD_PROXY_TEST'] == 'true' && ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK'] - assert_match(/"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"/, result.body) + assert_match(%r{"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"}, result.body) end # ftp / 200 @@ -346,7 +346,7 @@ class UserAgentTest < ActiveSupport::TestCase assert_equal(true, result.success?) assert_equal('200', result.code) assert_equal(String, result.body.class) - assert(result.body =~ /instructions/i) + assert(result.body =~ %r{instructions}i) # ftp / 401 result = UserAgent.request( @@ -477,7 +477,7 @@ class UserAgentTest < ActiveSupport::TestCase assert(result.body.include?('"application/json"')) assert_equal('some value ', result.data['submitted']['key']) if ENV['ZAMMAD_PROXY_TEST'] == 'true' && ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK'] - assert_match(/"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"/, result.body) + assert_match(%r{"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"}, result.body) end # get / 404 @@ -514,7 +514,7 @@ class UserAgentTest < ActiveSupport::TestCase assert(result.body.include?('"application/json"')) assert_equal('some value ', result.data['submitted']['key']) if ENV['ZAMMAD_PROXY_TEST'] == 'true' && ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK'] - assert_match(/"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"/, result.body) + assert_match(%r{"remote_ip":"#{ENV['ZAMMAD_PROXY_REMOTE_IP_CHECK']}"}, result.body) end end diff --git a/test/support/searchindex_helper.rb b/test/support/searchindex_helper.rb index 57afe0750..0af3be66d 100644 --- a/test/support/searchindex_helper.rb +++ b/test/support/searchindex_helper.rb @@ -39,7 +39,7 @@ prepares elasticsearch if ENV['ES_INDEX_RAND'].present? rand_id = ENV.fetch('CI_JOB_ID', "r#{rand(999)}") - test_method_name = method_name.gsub(/[^\w]/, '_') + test_method_name = method_name.gsub(%r{[^\w]}, '_') ENV['ES_INDEX'] = "es_index_#{test_method_name.downcase}_#{rand_id}_#{rand(999_999_999)}" end if ENV['ES_INDEX'].blank? diff --git a/test/test_helper.rb b/test/test_helper.rb index 286c92d48..ce0f44991 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -66,8 +66,8 @@ class ActiveSupport::TestCase count = 0 lines.reverse_each do |line| break if line.include?('++++NEW++++TEST++++') - next if !line.match?(/Send notification \(#{type}\)/) - next if !line.match?(/to:\s#{recipient}/) + next if !line.match?(%r{Send notification \(#{type}\)}) + next if !line.match?(%r{to:\s#{recipient}}) count += 1 end diff --git a/test/unit/email_build_test.rb b/test/unit/email_build_test.rb index f527584d3..0d7426ad1 100644 --- a/test/unit/email_build_test.rb +++ b/test/unit/email_build_test.rb @@ -7,7 +7,7 @@ class EmailBuildTest < ActiveSupport::TestCase result = Channel::EmailBuild.html_complete_check(html) assert(result.start_with?(''), 'test 1') assert(result.include?('font-family'), 'test 1') assert(result.include?('test'), 'test 1') @@ -15,10 +15,10 @@ class EmailBuildTest < ActiveSupport::TestCase html = 'invalid test' result = Channel::EmailBuild.html_complete_check(html) - assert(result !~ /^'), 'test 2') - assert(result !~ /font-family/, 'test 2') + assert(result !~ %r{font-family}, 'test 2') assert(result.include?('test'), 'test 2') # Issue #1230, missing backslashes @@ -396,6 +396,6 @@ text File.write('append_test.eml', mail.to_s) # Email Content should appear before the Text Content within the raw email - assert_match(/Email Content[\s\S]*Text Content/, mail.to_s) + assert_match(%r{Email Content[\s\S]*Text Content}, mail.to_s) end end diff --git a/test/unit/email_process_auto_response_test.rb b/test/unit/email_process_auto_response_test.rb index edd0374e4..b9662f7f3 100644 --- a/test/unit/email_process_auto_response_test.rb +++ b/test/unit/email_process_auto_response_test.rb @@ -238,9 +238,9 @@ Some Text" assert_equal('Customer', article_customer.sender.name) assert_equal('email', article_customer.type.name) article_notification = article_p.ticket.articles[1] - assert_match(/New Ticket add. info/, article_notification.subject) - assert_no_match(/me@example.com/, article_notification.to) - assert_match(/#{agent1.email}/, article_notification.to) + assert_match(%r{New Ticket add. info}, article_notification.subject) + assert_no_match(%r{me@example.com}, article_notification.to) + assert_match(%r{#{agent1.email}}, article_notification.to) assert_equal('System', article_notification.sender.name) assert_equal('email', article_notification.type.name) @@ -264,9 +264,9 @@ Some Text" assert_equal('Customer', article_customer.sender.name) assert_equal('email', article_customer.type.name) article_notification = article_p.ticket.articles[1] - assert_match(/New Ticket add. info/, article_notification.subject) - assert_no_match(/me@example.com/, article_notification.to) - assert_match(/#{agent1.email}/, article_notification.to) + assert_match(%r{New Ticket add. info}, article_notification.subject) + assert_no_match(%r{me@example.com}, article_notification.to) + assert_match(%r{#{agent1.email}}, article_notification.to) assert_equal('System', article_notification.sender.name) assert_equal('email', article_notification.type.name) @@ -296,14 +296,14 @@ Some Text" assert_equal('Customer', article_customer.sender.name) assert_equal('email', article_customer.type.name) article_notification = article_p.ticket.articles[1] - assert_match(/New Ticket add. info/, article_notification.subject) - assert_no_match(/me@example.com/, article_notification.to) - assert_match(/#{agent1.email}/, article_notification.to) + assert_match(%r{New Ticket add. info}, article_notification.subject) + assert_no_match(%r{me@example.com}, article_notification.to) + assert_match(%r{#{agent1.email}}, article_notification.to) assert_equal('System', article_notification.sender.name) assert_equal('email', article_notification.type.name) article_auto_reply = article_p.ticket.articles[2] - assert_match(/Thanks for your inquiry/, article_auto_reply.subject) - assert_match(/me@example.com/, article_auto_reply.to) + assert_match(%r{Thanks for your inquiry}, article_auto_reply.subject) + assert_match(%r{me@example.com}, article_auto_reply.to) assert_equal('System', article_auto_reply.sender.name) assert_equal('email', article_auto_reply.type.name) @@ -326,14 +326,14 @@ Some Text" assert_equal('Customer', article_customer.sender.name) assert_equal('email', article_customer.type.name) article_notification = article_p.ticket.articles[1] - assert_match(/New Ticket add. info/, article_notification.subject) - assert_no_match(/me@example.com/, article_notification.to) - assert_match(/#{agent1.email}/, article_notification.to) + assert_match(%r{New Ticket add. info}, article_notification.subject) + assert_no_match(%r{me@example.com}, article_notification.to) + assert_match(%r{#{agent1.email}}, article_notification.to) assert_equal('System', article_notification.sender.name) assert_equal('email', article_notification.type.name) article_auto_reply = article_p.ticket.articles[2] - assert_match(/Thanks for your inquiry/, article_auto_reply.subject) - assert_match(/me@example.com/, article_auto_reply.to) + assert_match(%r{Thanks for your inquiry}, article_auto_reply.subject) + assert_match(%r{me@example.com}, article_auto_reply.to) assert_equal('System', article_auto_reply.sender.name) assert_equal('email', article_auto_reply.type.name) @@ -575,9 +575,9 @@ Some Text" assert_equal('Customer', article_customer.sender.name) assert_equal('email', article_customer.type.name) article_notification = article_p.ticket.articles[1] - assert_match(/New Ticket add. info/, article_notification.subject) - assert_no_match(/me@example.com/, article_notification.to) - assert_match(/#{agent1.email}/, article_notification.to) + assert_match(%r{New Ticket add. info}, article_notification.subject) + assert_no_match(%r{me@example.com}, article_notification.to) + assert_match(%r{#{agent1.email}}, article_notification.to) assert_equal('System', article_notification.sender.name) assert_equal('email', article_notification.type.name) @@ -601,9 +601,9 @@ Some Text" assert_equal('Customer', article_customer.sender.name) assert_equal('email', article_customer.type.name) article_notification = article_p.ticket.articles[1] - assert_match(/New Ticket add. info/, article_notification.subject) - assert_no_match(/me@example.com/, article_notification.to) - assert_match(/#{agent1.email}/, article_notification.to) + assert_match(%r{New Ticket add. info}, article_notification.subject) + assert_no_match(%r{me@example.com}, article_notification.to) + assert_match(%r{#{agent1.email}}, article_notification.to) assert_equal('System', article_notification.sender.name) assert_equal('email', article_notification.type.name) @@ -633,14 +633,14 @@ Some Text" assert_equal('Customer', article_customer.sender.name) assert_equal('email', article_customer.type.name) article_auto_reply = article_p.ticket.articles[1] - assert_match(/Thanks for your inquiry/, article_auto_reply.subject) - assert_match(/me@example.com/, article_auto_reply.to) + assert_match(%r{Thanks for your inquiry}, article_auto_reply.subject) + assert_match(%r{me@example.com}, article_auto_reply.to) assert_equal('System', article_auto_reply.sender.name) assert_equal('email', article_auto_reply.type.name) article_notification = article_p.ticket.articles[2] - assert_match(/New Ticket add. info/, article_notification.subject) - assert_no_match(/me@example.com/, article_notification.to) - assert_match(/#{agent1.email}/, article_notification.to) + assert_match(%r{New Ticket add. info}, article_notification.subject) + assert_no_match(%r{me@example.com}, article_notification.to) + assert_match(%r{#{agent1.email}}, article_notification.to) assert_equal('System', article_notification.sender.name) assert_equal('email', article_notification.type.name) @@ -663,14 +663,14 @@ Some Text" assert_equal('Customer', article_customer.sender.name) assert_equal('email', article_customer.type.name) article_auto_reply = article_p.ticket.articles[1] - assert_match(/Thanks for your inquiry/, article_auto_reply.subject) - assert_match(/me@example.com/, article_auto_reply.to) + assert_match(%r{Thanks for your inquiry}, article_auto_reply.subject) + assert_match(%r{me@example.com}, article_auto_reply.to) assert_equal('System', article_auto_reply.sender.name) assert_equal('email', article_auto_reply.type.name) article_notification = article_p.ticket.articles[2] - assert_match(/New Ticket add. info/, article_notification.subject) - assert_no_match(/me@example.com/, article_notification.to) - assert_match(/#{agent1.email}/, article_notification.to) + assert_match(%r{New Ticket add. info}, article_notification.subject) + assert_no_match(%r{me@example.com}, article_notification.to) + assert_match(%r{#{agent1.email}}, article_notification.to) assert_equal('System', article_notification.sender.name) assert_equal('email', article_notification.type.name) @@ -781,9 +781,9 @@ Some Text" assert_equal('Customer', article_customer.sender.name) assert_equal('email', article_customer.type.name) article_notification = article_p.ticket.articles[1] - assert_match(/New Ticket add. info/, article_notification.subject) - assert_no_match(/me@example.com/, article_notification.to) - assert_match(/#{agent1.email}/, article_notification.to) + assert_match(%r{New Ticket add. info}, article_notification.subject) + assert_no_match(%r{me@example.com}, article_notification.to) + assert_match(%r{#{agent1.email}}, article_notification.to) assert_equal('System', article_notification.sender.name) assert_equal('email', article_notification.type.name) @@ -807,9 +807,9 @@ Some Text" assert_equal('Customer', article_customer.sender.name) assert_equal('email', article_customer.type.name) article_notification = article_p.ticket.articles[1] - assert_match(/New Ticket add. info/, article_notification.subject) - assert_no_match(/me@example.com/, article_notification.to) - assert_match(/#{agent1.email}/, article_notification.to) + assert_match(%r{New Ticket add. info}, article_notification.subject) + assert_no_match(%r{me@example.com}, article_notification.to) + assert_match(%r{#{agent1.email}}, article_notification.to) assert_equal('System', article_notification.sender.name) assert_equal('email', article_notification.type.name) @@ -838,9 +838,9 @@ Some Text" assert_equal('Customer', article_customer.sender.name) assert_equal('email', article_customer.type.name) article_notification = article_p.ticket.articles[1] - assert_match(/New Ticket add. info/, article_notification.subject) - assert_no_match(/me@example.com/, article_notification.to) - assert_match(/#{agent1.email}/, article_notification.to) + assert_match(%r{New Ticket add. info}, article_notification.subject) + assert_no_match(%r{me@example.com}, article_notification.to) + assert_match(%r{#{agent1.email}}, article_notification.to) assert_equal('System', article_notification.sender.name) assert_equal('email', article_notification.type.name) @@ -863,14 +863,14 @@ Some Text" assert_equal('Customer', article_customer.sender.name) assert_equal('email', article_customer.type.name) article_notification = article_p.ticket.articles[1] - assert_match(/New Ticket add. info/, article_notification.subject) - assert_no_match(/me@example.com/, article_notification.to) - assert_match(/#{agent1.email}/, article_notification.to) + assert_match(%r{New Ticket add. info}, article_notification.subject) + assert_no_match(%r{me@example.com}, article_notification.to) + assert_match(%r{#{agent1.email}}, article_notification.to) assert_equal('System', article_notification.sender.name) assert_equal('email', article_notification.type.name) article_auto_reply = article_p.ticket.articles[2] - assert_match(/Thanks for your inquiry/, article_auto_reply.subject) - assert_match(/me@example.com/, article_auto_reply.to) + assert_match(%r{Thanks for your inquiry}, article_auto_reply.subject) + assert_match(%r{me@example.com}, article_auto_reply.to) assert_equal('System', article_auto_reply.sender.name) assert_equal('email', article_auto_reply.type.name) diff --git a/test/unit/ticket_notification_test.rb b/test/unit/ticket_notification_test.rb index 9b3c1b030..9de4e2557 100644 --- a/test/unit/ticket_notification_test.rb +++ b/test/unit/ticket_notification_test.rb @@ -1171,15 +1171,15 @@ class TicketNotificationTest < ActiveSupport::TestCase changes: human_changes, }, ) - assert_match(/Bobs's resumé/, result[:subject]) - assert_match(/Priority/, result[:body]) - assert_match(/1 low/, result[:body]) - assert_match(/2 normal/, result[:body]) - assert_match(/Pending till/, result[:body]) + assert_match(%r{Bobs's resumé}, result[:subject]) + assert_match(%r{Priority}, result[:body]) + assert_match(%r{1 low}, result[:body]) + assert_match(%r{2 normal}, result[:body]) + assert_match(%r{Pending till}, result[:body]) assert_match('01/11/2015 19:33 (America/St_Lucia)', result[:body]) - assert_match(/update/, result[:body]) - assert_no_match(/pending_till/, result[:body]) - assert_no_match(/i18n/, result[:body]) + assert_match(%r{update}, result[:body]) + assert_no_match(%r{pending_till}, result[:body]) + assert_no_match(%r{i18n}, result[:body]) human_changes = bg.human_changes(@agent1, ticket1) assert(human_changes['Priority'], 'Check if attributes translated based on ObjectManager::Attribute') @@ -1205,15 +1205,15 @@ class TicketNotificationTest < ActiveSupport::TestCase }, ) - assert_match(/Bobs's resumé/, result[:subject]) - assert_match(/Priorität/, result[:body]) - assert_match(/1 niedrig/, result[:body]) - assert_match(/2 normal/, result[:body]) - assert_match(/Warten/, result[:body]) + assert_match(%r{Bobs's resumé}, result[:subject]) + assert_match(%r{Priorität}, result[:body]) + assert_match(%r{1 niedrig}, result[:body]) + assert_match(%r{2 normal}, result[:body]) + assert_match(%r{Warten}, result[:body]) assert_match('12.01.2015 00:33 (Europe/Berlin)', result[:body]) - assert_match(/aktualis/, result[:body]) - assert_no_match(/pending_till/, result[:body]) - assert_no_match(/i18n/, result[:body]) + assert_match(%r{aktualis}, result[:body]) + assert_no_match(%r{pending_till}, result[:body]) + assert_no_match(%r{i18n}, result[:body]) bg = Transaction::Notification.new( ticket_id: ticket1.id, @@ -1251,16 +1251,16 @@ class TicketNotificationTest < ActiveSupport::TestCase } ) - assert_match(/Bobs's resumé/, result[:subject]) - assert_match(/Titel/, result[:body]) - assert_no_match(/Title/, result[:body]) - assert_match(/some notification template test old 1/, result[:body]) - assert_match(/some notification template test 1 #2/, result[:body]) - assert_match(/Priorität/, result[:body]) - assert_no_match(/Priority/, result[:body]) - assert_match(/3 hoch/, result[:body]) - assert_match(/2 normal/, result[:body]) - assert_match(/aktualisier/, result[:body]) + assert_match(%r{Bobs's resumé}, result[:subject]) + assert_match(%r{Titel}, result[:body]) + assert_no_match(%r{Title}, result[:body]) + assert_match(%r{some notification template test old 1}, result[:body]) + assert_match(%r{some notification template test 1 #2}, result[:body]) + assert_match(%r{Priorität}, result[:body]) + assert_no_match(%r{Priority}, result[:body]) + assert_match(%r{3 hoch}, result[:body]) + assert_match(%r{2 normal}, result[:body]) + assert_match(%r{aktualisier}, result[:body]) human_changes = bg.human_changes(@agent2, ticket1) @@ -1277,18 +1277,18 @@ class TicketNotificationTest < ActiveSupport::TestCase } ) - assert_match(/Bobs's resumé/, result[:subject]) - assert_match(/Title/, result[:body]) - assert_match(/some notification template test old 1/, result[:body]) - assert_match(/some notification template test 1 #2/, result[:body]) - assert_match(/Priority/, result[:body]) - assert_match(/3 high/, result[:body]) - assert_match(/2 normal/, result[:body]) - assert_no_match(/Pending till/, result[:body]) - assert_no_match(/2015-01-11 23:33:47 UTC/, result[:body]) - assert_match(/update/, result[:body]) - assert_no_match(/pending_till/, result[:body]) - assert_no_match(/i18n/, result[:body]) + assert_match(%r{Bobs's resumé}, result[:subject]) + assert_match(%r{Title}, result[:body]) + assert_match(%r{some notification template test old 1}, result[:body]) + assert_match(%r{some notification template test 1 #2}, result[:body]) + assert_match(%r{Priority}, result[:body]) + assert_match(%r{3 high}, result[:body]) + assert_match(%r{2 normal}, result[:body]) + assert_no_match(%r{Pending till}, result[:body]) + assert_no_match(%r{2015-01-11 23:33:47 UTC}, result[:body]) + assert_match(%r{update}, result[:body]) + assert_no_match(%r{pending_till}, result[:body]) + assert_no_match(%r{i18n}, result[:body]) # en notification ticket1.escalation_at = Time.zone.parse('2019-04-01T10:00:00Z') diff --git a/test/unit/ticket_trigger_recursive_disabled_test.rb b/test/unit/ticket_trigger_recursive_disabled_test.rb index ecca70964..945c56acc 100644 --- a/test/unit/ticket_trigger_recursive_disabled_test.rb +++ b/test/unit/ticket_trigger_recursive_disabled_test.rb @@ -4282,7 +4282,7 @@ class TicketTriggerRecursiveDisabledTest < ActiveSupport::TestCase assert_match('Zammad ', article1.from) assert_match('smith@example.com', article1.to) assert_match('Thanks for your inquiry (aaäöüßad asd)!', article1.subject) - assert_match(/.+cid:.+?@zammad.example.com.+/, article1.body) + assert_match(%r{.+cid:.+?@zammad.example.com.+}, article1.body) assert_equal(1, article1.attachments.count) assert_equal('789', article1.attachments[0].size) assert_equal('text/html', article1.content_type) diff --git a/test/unit/ticket_trigger_test.rb b/test/unit/ticket_trigger_test.rb index 434a314b9..d61c65f83 100644 --- a/test/unit/ticket_trigger_test.rb +++ b/test/unit/ticket_trigger_test.rb @@ -4308,7 +4308,7 @@ class TicketTriggerTest < ActiveSupport::TestCase assert_match('Zammad ', article1.from) assert_match('smith@example.com', article1.to) assert_match('Thanks for your inquiry (aaäöüßad asd)!', article1.subject) - assert_match(/.+cid:.+?@zammad.example.com.+/, article1.body) + assert_match(%r{.+cid:.+?@zammad.example.com.+}, article1.body) assert_equal(1, article1.attachments.count) assert_equal('789', article1.attachments[0].size) assert_equal('text/html', article1.content_type)