Best Vcr_ruby code snippet using Header.unhandled
mail_processor.rb
Source:mail_processor.rb
...22 # # Match based on the To or CC header23 # r.rcpt "post@example.com" do24 # # Match based on the body, capturing the post id and tag25 # r.body(/^Post: (\d+)-(\w+)/) do |post_id, tag|26 # unhandled_mail("no matching post") unless post = Post[post_id.to_i]27 # unhandled_mail("tag doesn't match for post") unless post.tag == tag28 #29 # # Match based on APPROVE somewhere in the mail text,30 # # marking the mail as handled31 # r.handle_text /\bAPPROVE\b/i do32 # post.approve!(from)33 # end34 #35 # # Match based on DENY somewhere in the mail text,36 # # marking the mail as handled37 # r.handle_text /\bDENY\b/i do38 # post.deny!(from)39 # end40 # end41 # end42 # end43 # end44 #45 # = Processing Mail46 #47 # To submit a mail for processing via the mail_processor routing tree, call the +process_mail+48 # method with a +Mail+ instance:49 #50 # MailProcessor.process_mail(Mail.new do51 # # ...52 # end)53 #54 # You can use this to process mail messages from the filesystem:55 #56 # MailProcessor.process_mail(Mail.read('/path/to/message.eml'))57 #58 # If you have a service that delivers mail via an HTTP POST request (for realtime59 # processing), you can have your web routes convert the web request into a +Mail+ instance60 # and then call +process_mail+:61 #62 # r.post "email" do63 # # check request is submitted by trusted sender64 #65 # # If request body is the raw mail body66 # r.body.rewind67 # MailProcessor.process_mail(Mail.new(r.body.read))68 #69 # # If request body is in a parameter named content70 # MailProcessor.process_mail(Mail.new(r.params['content']))71 #72 # # If the HTTP request requires a specific response status code (such as 204)73 # response.status = 20474 #75 # nil76 # end77 #78 # Note that when receiving messages via HTTP, you need to make sure you check that the79 # request is trusted. How to do this depends on the delivery service, but could involve80 # using HTTP basic authentication, checking for valid API tokens, or checking that a message81 # includes a signature/hash that matches the expected value.82 #83 # If you have setup a default retriever_method for +Mail+, you can call +process_mailbox+,84 # which will process all mail in the given mailbox (using +Mail.find_and_delete+):85 #86 # MailProcessor.process_mailbox87 #88 # You can also use a +:retreiver+ option to provide a specific retriever:89 #90 # MailProcessor.process_mailbox(retreiver: Mail::POP3.new)91 #92 # = Routing Mail93 #94 # The mail_processor plugin handles routing similar to Roda's default routing for95 # web requests, but because mail processing may not return a result, the mail_processor96 # plugin uses a more explicit approach to consider whether the message has been handled.97 # If the +r.handle+ method is called during routing, the mail is considered handled,98 # otherwise the mail is considered not handled. The +unhandled_mail+ method can be99 # called at any point to stop routing and consider the mail as not handled (even if100 # inside an +r.handle+ block).101 #102 # Here are the mail routing methods and what they use for matching:103 #104 # from :: match on the mail From address105 # to :: match on the mail To address106 # cc :: match on the mail CC address107 # rcpt :: match on the mail recipients (To and CC addresses by default)108 # subject :: match on the mail subject109 # body :: match on the mail body110 # text :: match on text extracted from the message (same as mail body by default)111 # header :: match on a mail header112 #113 # All of these routing methods accept a single argument, except for +r.header+, which114 # can take two arguments.115 #116 # Each of these routing methods also has a +r.handle_*+ method117 # (e.g. +r.handle_from+), which will call +r.handle+ implicitly to mark the118 # mail as handled if the routing method matches and control is passed to the block.119 #120 # The address matchers (from, to, cc, rcpt) perform a case-insensitive match if121 # given a string or array of strings, and a regular regexp match if given a regexp.122 #123 # The content matchers (subject, body, text) perform a case-sensitive substring search124 # if given a string or array of strings, and a regular regexp match if given a regexp.125 #126 # The header matcher should be called with a key and an optional value. If the matcher is127 # called with a key and not a value, it matches if a header matching the key is present128 # in the message, yielding the header value. If the matcher is called with a key and a129 # value, it matches if a header matching the key is present and the header value matches130 # the value given, using the same criteria as the content matchers.131 #132 # In all cases for matchers, if a string is given and matches, the match block is called without133 # arguments. If an array of strings is given, and one of the strings matches,134 # the match block is called with the matching string argument. If a regexp is given,135 # the match block is called with the regexp captures. This is the same behavior for Roda's136 # general string, array, and regexp matchers.137 # 138 # = Recipient-Specific Routing139 #140 # To allow splitting up the mail processor routing tree based on recipients, you can use141 # the +rcpt+ class method, which takes any number of string or regexps arguments for recipient142 # addresses, and a block to handle the routing for those addresses instead of using the143 # default routing.144 #145 # MailProcessor.rcpt('a@example.com') do |r|146 # r.text /Post: (\d+)-(\h+)/ do |post_id, hmac|147 # next unless Post[post_id.to_i]148 # unhandled_mail("no matching Post") unless post = Post[post_id.to_i]149 # unhandled_mail("HMAC for doesn't match for post") unless hmac == post.hmac_for_address(from.first)150 #151 # r.handle_text 'APPROVE' do152 # post.approved_by(from)153 # end154 #155 # r.handle_text 'DENY' do156 # post.denied_by(from)157 # end158 # end159 # end160 #161 # The +rcpt+ class method does not mark the messages as handled, because in most cases you will162 # need to do additional matching to extract the information necessary to handle163 # the mail. You will need to call +r.handle+ or similar method inside the block164 # to mark the mail as handled.165 #166 # Matching on strings provided to the +rcpt+ class method is an O(1) operation as167 # the strings are stored lowercase in a hash. Matching on regexps provided to the168 # +rcpt+ class method is an O(n) operation on the number of regexps.169 #170 # If you would like to break up the routing tree using something other than the171 # recipient address, you can use the multi_route plugin.172 #173 # = Hooks174 #175 # The mail_processor plugin offers hooks for processing mail.176 #177 # For mail that is handled successfully, you can use the handled_mail hook:178 #179 # MailProcessor.handled_mail do180 # # nothing by default181 # end182 #183 # For mail that is not handled successfully, either because +r.handle+ was not called184 # during routing or because the +unhandled_mail+ method was called explicitly,185 # you can use the unhandled_mail hook.186 #187 # The default is to reraise the UnhandledMail exception that was raised during routing,188 # so that calling code will not be able to ignore errors when processing mail. However,189 # you may want to save such mails to a special location or forward them as attachments190 # for manual review, and the unhandled_mail hook allows you to do that:191 #192 # MailProcessor.unhandled_mail do193 # # raise by default194 #195 # # Forward the mail as an attachment to an admin196 # m = Mail.new197 # m.to 'admin@example.com'198 # m.subject '[APP] Unhandled Received Email'199 # m.add_file(filename: 'message.eml', :content=>mail.encoded)200 # m.deliver201 # end202 # 203 # Finally, for all processed mail, regardless of whether it was handled or not,204 # there is an after_mail hook, which can be used to archive all processed mail:205 #206 # MailProcessor.after_mail do207 # # nothing by default208 #209 # # Add it to a received_mail table using Sequel210 # DB[:received_mail].insert(:message=>mail.encoded)211 # end212 #213 # The after_mail hook is called after the handled_mail or unhandled_mail hook214 # is called, even if routing, the handled_mail hook, or the unhandled_mail hook215 # raises an exception. The handled_mail and unhandled_mail hooks are not called216 # if an exception is raised during routing (other than for UnhandledMail exceptions).217 #218 # = Extracting Text from Mail219 #220 # The most common use of the mail_processor plugin is to handle replies to mails sent221 # out by the application, so that recipients can reply to mail to make changes without222 # having to access the application directly. When handling replies, it is common to want223 # to extract only the text of the reply, and ignore the text of the message that was224 # replied to. Because there is no consistent way to format replies in mail, there have225 # evolved various approaches to do this, with some gems devoted to extracting the reply226 # text from a message.227 #228 # The mail_processor plugin does not choose any particular approach for extracting text from mail,229 # but it includes the ability to configure how to do that via the +mail_text+ class method.230 # This method affects the +r.text+ match method, as well as +mail_text+ instance method.231 # By default, the decoded body of the mail is used as the mail text.232 # 233 # MailProcessor.mail_text do234 # # mail.body.decoded by default235 #236 # # https://github.com/github/email_reply_parser237 # EmailReplyParser.parse_reply(mail.body.decoded)238 #239 # # https://github.com/fiedl/extended_email_reply_parser240 # mail.parse241 # end242 #243 # = Security244 #245 # Note that due to the way mail delivery works via SMTP, the actual sender and recipient of246 # the mail (the SMTP envelope MAIL FROM and RCPT TO addresses) may not match the sender and247 # receiver embedded in the message. Because mail_processor routing relies on parsing the mail, 248 # it does not have access to the actual sender and recipient used at the SMTP level, unless249 # a mail server adds that information as a header to the mail (and clears any existing header250 # to prevent spoofing). Keep that in mind when you are setting up your mail routes. If you251 # have setup your mail server to add the SMTP RCPT TO information to a header, you may want252 # to only consider that header when looking for the recipients of the message, instead of253 # looking at the To and CC headers. You can override the default behavior for determining254 # the recipients (this will affect the +rcpt+ class method, +r.rcpt+ match method, and255 # +mail_recipients+ instance method):256 #257 # MailProcessor.mail_recipients do258 # # Assuming the information is in the X-SMTP-To header259 # Array(header['X-SMTP-To'].decoded)260 # end261 #262 # Also note that unlike when handling web requests where you can rely on storing authentication263 # information in the session, when processing mail, you should manually authenticate each message,264 # as email is trivially forged. One way to do this is assigning and storing a unique identifier when265 # sending each message, and checking for a matching identifier when receiving a response. Another266 # option is including a computable authentication code (e.g. HMAC) in the message, and then267 # when receiving a response, recomputing the authentication code and seeing if it matches the268 # authentication code in the message. The unique identifier approach requires storing a large269 # number of identifiers, but allows you to remove the identifier after a reply is received270 # (to ensure only one response is handled). The authentication code approach does not271 # require additional storage, but does not allow you to ensure only a single response is handled.272 #273 # = Avoiding Mail Loops274 #275 # If processing the mail results in sending out additional mail, be careful not to send a276 # response to the sender of the email, otherwise if the sender of the email has an277 # auto-responder, you can end up with a mail loop, where every mail you send results in278 # a response, which you then process and send out a response to.279 module MailProcessor280 # Exception class raised when a mail processed is not handled during routing,281 # either implicitly because the +r.handle+ method was not called, or via an explicit282 # call to +unhandled_mail+.283 class UnhandledMail < StandardError; end284 module ClassMethods285 # Freeze the rcpt routes if they are present.286 def freeze287 if string_routes = opts[:mail_processor_string_routes].freeze288 string_routes.freeze289 opts[:mail_processor_regexp_routes].freeze290 end291 super292 end293 # Process the given Mail instance, calling the appropriate hooks depending on294 # whether the mail was handled during processing.295 def process_mail(mail)296 scope = new("PATH_INFO"=>'', 'SCRIPT_NAME'=>'', "REQUEST_METHOD"=>"PROCESSMAIL", 'rack.input'=>StringIO.new, 'roda.mail'=>mail)297 begin298 begin299 scope.process_mail300 rescue UnhandledMail301 scope.unhandled_mail_hook302 else303 scope.handled_mail_hook304 end305 ensure306 scope.after_mail_hook307 end308 end309 310 # Process all mail in the given mailbox. If the +:retriever+ option is311 # given, should be an object supporting the Mail retriever API, otherwise312 # uses the default Mail retriever_method. This deletes retrieved mail from the313 # mailbox after processing, so that when called multiple times it does314 # not reprocess the same mail. If mail should be archived and not deleted,315 # the +after_mail+ method should be used to perform the archiving of the mail.316 def process_mailbox(opts=OPTS)317 (opts[:retriever] || Mail).find_and_delete(opts.dup){|m| process_mail(m)}318 nil319 end320 # Setup a routing tree for the given recipient addresses, which can be strings or regexps.321 # Any messages matching the given recipient address will use these routing trees instead322 # of the normal routing tree.323 def rcpt(*addresses, &block)324 opts[:mail_processor_string_routes] ||= {}325 opts[:mail_processor_regexp_routes] ||= {}326 string_meth = nil327 regexp_meth = nil328 addresses.each do |address|329 case address330 when String331 unless string_meth332 string_meth = define_roda_method("mail_processor_string_route_#{address}", 1, &convert_route_block(block))333 end334 opts[:mail_processor_string_routes][address] = string_meth 335 when Regexp336 unless regexp_meth337 regexp_meth = define_roda_method("mail_processor_regexp_route_#{address}", :any, &convert_route_block(block))338 end339 opts[:mail_processor_regexp_routes][address] = regexp_meth340 else341 raise RodaError, "invalid address format passed to rcpt, should be Array or String"342 end343 end344 nil345 end346 %w'after_mail handled_mail unhandled_mail'.each do |meth|347 class_eval(<<-END, __FILE__, __LINE__+1)348 def #{meth}(&block)349 define_method(:#{meth}_hook, &block)350 nil351 end352 END353 end354 %w'mail_recipients mail_text'.each do |meth|355 class_eval(<<-END, __FILE__, __LINE__+1)356 def #{meth}(&block)357 define_method(:#{meth}, &block)358 nil359 end360 END361 end362 end363 module InstanceMethods364 [:to, :from, :cc, :body, :subject, :header].each do |field|365 class_eval(<<-END, __FILE__, __LINE__+1)366 def #{field}367 mail.#{field}368 end369 END370 end371 # Perform the processing of mail for this request, first considering372 # routes defined via the the class-level +rcpt+ method, and then the373 # normal routing tree passed in as the block.374 def process_mail(&block)375 if string_routes = opts[:mail_processor_string_routes]376 addresses = mail_recipients377 addresses.each do |address|378 if meth = string_routes[address.to_s.downcase]379 _roda_handle_route{send(meth, @_request)}380 return381 end382 end383 opts[:mail_processor_regexp_routes].each do |regexp, meth|384 addresses.each do |address|385 if md = regexp.match(address)386 _roda_handle_route{send(meth, @_request, *md.captures)}387 return 388 end389 end390 end391 end392 _roda_handle_main_route393 nil394 end395 # Hook called after processing any mail, whether the mail was396 # handled or not. Does nothing by default.397 def after_mail_hook398 nil399 end400 # Hook called after processing a mail, when the mail was handled.401 # Does nothing by default.402 def handled_mail_hook403 nil404 end405 # Hook called after processing a mail, when the mail was not handled.406 # Reraises the UnhandledMail exception raised during mail processing407 # by default.408 def unhandled_mail_hook409 raise410 end411 # The mail instance being processed.412 def mail413 env['roda.mail']414 end415 # The text of the mail instance being processed, uses the416 # decoded body of the mail by default.417 def mail_text418 mail.body.decoded419 end420 # The recipients of the mail instance being processed, uses the To and CC421 # headers by default.422 def mail_recipients423 Array(to) + Array(cc)424 end425 # Raise an UnhandledMail exception with the given reason, used to mark the426 # mail as not handled. A reason why the mail was not handled must be427 # provided, which will be used as the exception message.428 def unhandled_mail(reason)429 raise UnhandledMail, reason430 end431 end432 module RequestMethods433 [:to, :from, :cc, :body, :subject, :rcpt, :text].each do |field|434 class_eval(<<-END, __FILE__, __LINE__+1)435 def handle_#{field}(val)436 #{field}(val) do |*args|437 handle do438 yield(*args)439 end440 end441 end442 def #{field}(address, &block)443 on(:#{field}=>address, &block)444 end445 private446 def match_#{field}(address)447 _match_address(:#{field}, address, Array(mail.#{field}))448 end449 END450 end451 undef_method :match_rcpt452 undef_method :match_text453 # Same as +header+, but also mark the message as being handled.454 def handle_header(key, value=nil)455 header(key, value) do |*args|456 handle do457 yield(*args)458 end459 end460 end461 # Match based on a mail header value.462 def header(key, value=nil, &block)463 on(:header=>[key, value], &block)464 end465 # Mark the mail as having been handled, so routing will not call466 # unhandled_mail implicitly.467 def handle(&block)468 env['roda.mail_handled'] = true469 always(&block)470 end471 private472 if RUBY_VERSION >= '2.4.0'473 # Whether the addresses are the same (case insensitive match).474 def address_match?(a1, a2)475 a1.casecmp?(a2)476 end477 else478 # :nocov:479 def address_match?(a1, a2)480 a1.downcase == a2.downcase481 end482 # :nocov:483 end484 # Match if any of the given addresses match the given val, which485 # can be a string (case insensitive match of the string), array of486 # strings (case insensitive match of any string), or regexp487 # (normal regexp match).488 def _match_address(field, val, addresses)489 case val490 when String491 addresses.any?{|a| address_match?(a, val)}492 when Array493 overlap = []494 addresses.each do |a|495 val.each do |v|496 if address_match?(a, v)497 overlap << a 498 end499 end500 end501 unless overlap.empty?502 @captures.concat(overlap)503 end504 when Regexp505 matched = false506 addresses.each do |v|507 if md = val.match(v)508 matched = true509 @captures.concat(md.captures)510 end511 end512 matched513 else514 unsupported_matcher(:field=>val)515 end516 end517 # Match if the content matches the given val, which518 # can be a string (case sensitive substring match), array of519 # strings (case sensitive substring match of any string), or regexp520 # (normal regexp match).521 def _match_content(field, val, content)522 case val523 when String524 content.include?(val)525 when Array526 val.each do |v|527 if content.include?(v)528 return @captures << v529 end530 end531 false532 when Regexp533 if md = content.match(val)534 @captures.concat(md.captures)535 end536 else537 unsupported_matcher(field=>val)538 end539 end540 # Match the value against the full mail body.541 def match_body(val)542 _match_content(:body, val, mail.body.decoded)543 end544 # Match the value against the mail subject.545 def match_subject(val)546 _match_content(:subject, val, mail.subject)547 end548 # Match the given address against all recipients in the mail.549 def match_rcpt(address)550 _match_address(:rcpt, address, scope.mail_recipients)551 end552 # Match the value against the extracted mail text.553 def match_text(val)554 _match_content(:text, val, scope.mail_text)555 end556 # Match against a header specified by key with the given557 # value (which may be nil).558 def match_header((key, value))559 return unless content = mail.header[key]560 if value.nil?561 @captures << content.decoded562 else563 _match_content(:header, value, content.decoded)564 end565 end566 # The mail instance being processed.567 def mail568 env['roda.mail']569 end570 # If the routing did not explicitly mark the mail as handled571 # mark it as unhandled.572 def block_result_body(_)573 unless env['roda.mail_handled']574 scope.unhandled_mail('mail was not handled during mail_processor routing')575 end576 end577 end578 end579 register_plugin(:mail_processor, MailProcessor)580 end581end...
abuse_feedback.rb
Source:abuse_feedback.rb
...91 return false92 end93 end94 95 def self.find_unhandled(options = {})96 find(:all, options.merge(:conditions => "handled_at IS NULL"))97 end98 def self.count_unhandled99 count(:all, :conditions => "handled_at IS NULL")100 end101 102 # AbuseFeedback.handle_unhandled calls AbuseFeedback#handle! on all unhandled complaints103 def self.handle_unhandled104 orig_cnt = count_unhandled105 logger.info "AbuseFeedback.handle_unhandled called with #{orig_cnt} complaints to work on"106 cnt = 0107 while feedbacks = find_unhandled(:limit => 100) do 108 break if feedbacks.blank?109 feedbacks.each do |feedback| 110 feedback.handle!111 cnt += 1112 end113 end114 logger.info "AbuseFeedback.handle_unhandled finished after handling #{cnt} complaints."115 end116 def handled?117 handled_at != nil 118 end119 def handle!120 #121 # This is where you do something. 122 #123 fast_update_attribute :handled_at, Time.now.utc 124 logger.info "AbuseFeedback#handle! [#{id}] handling completed."125 end126 def self.uidl_exists?(u)127 self.count(:conditions => ["uidl = ?", u]) > 0128 end...
export_json.rb
Source:export_json.rb
...30 end31 opts.on('-i', '--include-opcodes x,y,z', Array, 'Only include listed opcodes; excludes all opcodes except listed; comma separated, eg. SMSG_ATTACK_START,SMSG_ATTACK_STOP') do |i|32 options[:include_opcodes] = i33 end34 opts.on('-s', '--skip-unhandled', 'Skip unhandled packets (may still include packets that are missing specific build support)') do |s|35 options[:skip_unhandled] = true36 end37 opts.on_tail('-h', '--help', 'Display argument information') do38 puts opts39 exit40 end41 end42 parser.parse!43 input_path = ARGV.pop44 if input_path.nil? || input_path.empty?45 puts46 puts 'ERROR: Must specify input file path'47 puts48 puts parser49 exit50 end51 options[:input_path] = input_path52 if options[:output_path].nil? || options[:output_path].empty?53 options[:output_path] = input_path + '.json'54 end55 options56 end57 def packets_to_json(options)58 puts59 puts "Output Path: #{options[:output_path]}"60 puts61 puts 'Exporting packets to JSON...'62 input_path = options[:input_path]63 output_path = options[:output_path]64 include_opcodes = options[:include_opcodes]65 exclude_opcodes = options[:exclude_opcodes]66 skip_unhandled = options[:skip_unhandled] == true67 output_file = File.open(output_path, 'w')68 capture = WOW::Capture::Parser.new(input_path)69 if options[:pretty]70 opening = "{\n \"packets\": ["71 else72 opening = "{\"packets\":["73 end74 output_file.write(opening)75 first_packet = true76 capture.on(:packet) do |packet|77 print "\r-> Progress: #{(capture.progress * 100).round}% ##{packet.header.index} (#{capture.pos} / #{capture.file_size})"78 if !(include_opcodes.nil? || include_opcodes.empty?)79 next if packet.header.opcode.nil?80 next if !include_opcodes.include?(packet.header.opcode.label)81 elsif !(exclude_opcodes.nil? || exclude_opcodes.empty?)82 next if packet.header.opcode.nil?83 next if exclude_opcodes.include?(packet.header.opcode.label)84 end85 next if skip_unhandled && !packet.handled?86 output_file.write(',') if !first_packet87 if options[:pretty]88 raw_output = JSON.pretty_generate(packet.to_h, indent: (' ' * 4))89 output = raw_output.split("\n").map { |line| " #{line}" }.join("\n")90 output_file.write("\n#{output}")91 else92 output_file.write(packet.to_json)93 end94 first_packet = false if first_packet95 end96 puts '-> Replaying capture'97 if skip_unhandled98 puts '-> Skipping unhandled packets'99 end100 capture.replay!101 if options[:pretty]102 closing = "\n ]\n}"103 else104 closing = "]}"105 end106 output_file.write(closing)107 output_file.close108 capture.close109 puts110 puts '-> Finished!'111 end112end...
unhandled
Using AI Code Generation
1 def method_missing(method, *args)2doc = Hpricot(open("http://www.google.com/"))3doc.search("h3.r a").each do |link|
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!