File indexing completed on 2024-05-12 04:02:11

0001 # This file is a testcase for the highlighting of Ruby code
0002 # It's not executable code, but a collection of code snippets
0003 #
0004 
0005 require 'Config'
0006 require 'DO/Clients'
0007 require 'DO/DBClients'
0008 
0009   def CGI::escapeElement(string, *elements)
0010     elements = elements[0] if elements[0].kind_of?(Array)
0011     unless elements.empty?
0012       string.gsub(/<\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?>/ni) do
0013         CGI::escapeHTML($&)
0014       end
0015     else
0016       string
0017     end
0018   end
0019 
0020 case inputLine
0021   when "debug"
0022     dumpDebugInfo
0023     dumpSymbols
0024   when /p\s+(\w+)/
0025     dumpVariable($1)
0026   when "quit", "exit"
0027     exit
0028   else
0029     print "Illegal command: #{inputLine}"
0030 end
0031 
0032 
0033 kind = case year #hi there
0034          when 1850..1889 then "Blues"
0035          when 1890..1909 then "Ragtime"
0036          when 1910..1929 then "New Orleans Jazz"
0037          when 1930..1939 then "Swing"
0038          when 1940..1950 then "Bebop"
0039          else                 "Jazz"
0040        end
0041 
0042   # URL-encode a string.
0043   #   url_encoded_string = CGI::escape("'Stop!' said Fred")
0044   #      # => "%27Stop%21%27+said+Fred"
0045   def CGI::escape(string)
0046     string.gsub(/([^ a-zA-Z0-9_.-]+)/n) do
0047       '%' + $1.unpack('H2' * $1.size).join('%').upcase
0048     end.tr(' ', '+')
0049   end
0050 
0051 
0052 # Class ClientManager
0053 #
0054 # definition : Import, store and export the various data used by the application.
0055 # This class is the sole interface between the application and the underlying database.
0056 
0057 mon, day, year = $1, $2, $3 if /(\d\d)-(\d\d)-(\d\d)/
0058 puts "a = #{a}" if fDebug
0059 print total unless total == 0
0060 
0061 while gets
0062   next if /^#/            # Skip comments
0063   parseLine unless /^$/   # Don't parse empty lines
0064 end
0065 
0066 if artist == "John Coltrane" #hi there
0067   artist = "'Trane" #hi there
0068 end unless nicknames == "no" #hi there
0069 
0070 handle = if aSong.artist == "Gillespie" then #hi there
0071            "Dizzy"
0072          elsif aSong.artist == "Parker" then
0073            "Bird"
0074          else #hi there
0075            "unknown"
0076          end
0077 
0078 if aSong.artist == "Gillespie" then  handle = "Dizzy"
0079 elsif aSong.artist == "Parker" then  handle = "Bird"
0080 else  handle = "unknown"
0081 end #hi there
0082 
0083 if aSong.artist == "Gillespie" then
0084   handle = "Dizzy"
0085 elsif aSong.artist == "Parker" then
0086   handle = "Bird"
0087 else
0088   handle = "unknown"
0089 end
0090 
0091 if aSong.artist == "Gillespie"
0092   handle = "Dizzy"
0093 elsif aSong.artist == "Parker"
0094   handle = "Bird"
0095 else
0096   handle = "unknown"
0097 end
0098 
0099  case line
0100   when /title=(.*)/
0101     puts "Title is #$1"
0102   when /track=(.*)/
0103     puts "Track is #$1"
0104   when /artist=(.*)/
0105     puts "Artist is #$1"
0106 end
0107 
0108 case shape
0109   when Square, Rectangle
0110     # ...
0111   when Circle
0112     # ...
0113   when Triangle
0114     # ...
0115   else
0116     # ...
0117 end 
0118 
0119 
0120 until playList.duration > 60 #hi there
0121   playList.add(songList.pop)
0122 end
0123 
0124 3.times do
0125   print "Ho! "
0126 end
0127 
0128 loop {
0129   # block ...
0130 }
0131 
0132 songList.each do |aSong|
0133   aSong.play
0134 end
0135 
0136 for aSong in songList
0137   aSong.play
0138 end
0139 
0140 for i in ['fee', 'fi', 'fo', 'fum']
0141   print i, " "
0142 end
0143 for i in 1..3
0144   print i, " "
0145 end
0146 for i in File.open("ordinal").find_all { |l| l =~ /d$/}
0147   print i.chomp, " "
0148 end
0149 
0150 class Periods
0151   def each
0152     yield "Classical"
0153     yield "Jazz"
0154     yield "Rock"
0155   end
0156 end
0157 
0158 
0159 periods = Periods.new
0160 for genre in periods
0161   print genre, " "
0162 end
0163 
0164 while gets
0165   next if /^\s*#/   # skip comments
0166   break if /^END/   # stop at end
0167                     # substitute stuff in backticks and try again
0168   redo if gsub!(/`(.*?)`/) { eval($1) }
0169   # process line ...
0170 end
0171 
0172 i=0
0173 loop do
0174   i += 1
0175   next if i < 3
0176   print i
0177   break if i > 4
0178 end
0179 
0180 for i in 1..100
0181   print "Now at #{i}. Restart? "
0182   retry if gets =~ /^y/i
0183 end
0184 
0185 def doUntil(cond)
0186   yield
0187   retry unless cond
0188 end
0189 
0190 i = 0
0191 doUntil(i > 3) {
0192   print i, " "
0193   i += 1
0194 }
0195 
0196 def system_call
0197         # ... code which throws SystemCallError
0198 rescue SystemCallError
0199         $stderr.print "IO failed: " + $!
0200         opFile.close
0201         File.delete(opName)
0202         raise
0203 end
0204 
0205 class ClientManager
0206         
0207         # constructor
0208         def initialize(dbase)
0209                 @dbClient = DBClient.new(dbase)
0210                 @clients = Clients.new
0211         end
0212         
0213         def prout(a, b, xy="jj") 24 end 
0214         ###############################################################
0215         #
0216         # CLIENTS SECTION
0217         #
0218         ###############################################################
0219         
0220         # update the clients object by retrieving the related data from the database
0221         # returns the number of clients
0222         def refreshClients
0223                 @clients.clean
0224                 unless @sqlQuery.nil? then
0225                         @sqlQuery.selectClient.each do |row|
0226                                 @clients.addClient(row[0],row[1],row[2],row[3],row[4],row[5], row[6], row[7], row[8])
0227                         end
0228                 else
0229                         puts "SqlQuery wasn't created : cannot read data from database"
0230                 end
0231                 return @clients.length
0232         end
0233         
0234         # insert a client in the database and refreshes the local clients object
0235         # we assume that none of the arguments is null
0236         # we assume that the client, identified by raison_sociale doesn't already exists
0237         def addClient(raison_sociale, division, departement, adresse, cp, ville, nom_contact, tel_contact)
0238                 id = "0"
0239                 unless @sqlQuery.nil? then
0240                         id = @sqlQuery.insertClient(raison_sociale, division, departement, adresse, cp, ville, nom_contact,tel_contact)
0241                 else
0242                         puts "SqlQuery wasn't created : database update cannot be performed"
0243                 end
0244                 @clients.addClient(id, raison_sociale, division, departement, adresse, cp, ville, nom_contact, tel_contact) # synchronize local object with DB
0245         end
0246         
0247         # deletes a client from the database and updates the local Clients object accordingly
0248         def delClient(nomclient_brut)
0249                 raison_sociale, div, dep = Clients.getIdentifiers(nomclient_brut)
0250                 listeContratsExp, listeContratsSup, listeContratsProd, listePropositionsExp, listePropositionsSup = []
0251 
0252                 listeContratsExp = @contratsExpertise.getContratsFromClient(nomclient_brut)
0253                 listeContratsSup = @contratsSupport.getContratsFromClient(nomclient_brut)
0254                 listeContratsProd = @contratsProduits.getContratsFromClient(nomclient_brut)
0255                 listePropositionsExp = @propositionsExpertise.getPropositionsFromClient(nomclient_brut)
0256                 listePropositionsSup = @propositionsSupport.getPropositionsFromClient(nomclient_brut)
0257                 
0258                 unless @sqlQuery.nil? then
0259                         @sqlQuery.deleteClient(raison_sociale, div, dep)
0260                         
0261                         @sqlQuery.deleteContracts(Config::EXPERTISE,listeContratsExp) 
0262                         @sqlQuery.deleteContracts(Config::SUPPORT,listeContratsSup)
0263                         @sqlQuery.deleteContracts(Config::PRODUIT,listeContratsProd)
0264                         @sqlQuery.deletePropositions(Config::EXPERTISE,listePropositionsExp)
0265                         @sqlQuery.deletePropositions(Config::SUPPORT,listePropositionsSup)
0266                 else
0267                         puts "SqlQuery wasn't created : database update cannot be performed"
0268                 end
0269                 @clients.delClient(raison_sociale,div,dep)
0270         
0271                 @contratsExpertise.deleteContracts(listeContratsExp)
0272                 @contratsSupport.deleteContracts(listeContratsSup)
0273                 @contratsProduits.deleteContracts(listeContratsProd)
0274                 @propositionsExpertise.deletePropositions(listePropositionsExp)
0275                 @propositionsSupport.deletePropositions(listePropositionsSup)
0276         end
0277 end
0278 
0279   # Mixin module for HTML version 3 generation methods.
0280   module Html3 # :nodoc:
0281 
0282     # The DOCTYPE declaration for this version of HTML
0283     def doctype
0284       %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">|
0285     end
0286 
0287     # Initialise the HTML generation methods for this version.
0288     def element_init
0289       extend TagMaker
0290       methods = ""
0291       # - -
0292       for element in %w[ A TT I B U STRIKE BIG SMALL SUB SUP EM STRONG
0293           DFN CODE SAMP KBD VAR CITE FONT ADDRESS DIV center MAP
0294           APPLET PRE XMP LISTING DL OL UL DIR MENU SELECT table TITLE
0295           STYLE SCRIPT H1 H2 H3 H4 H5 H6 TEXTAREA FORM BLOCKQUOTE
0296           CAPTION ]
0297         methods += <<-BEGIN + nn_element_def(element) + <<-END
0298           def #{element.downcase}(attributes = {})
0299         BEGIN
0300           end
0301         END
0302       end
0303 
0304       # - O EMPTY
0305       for element in %w[ IMG BASE BASEFONT BR AREA LINK PARAM HR INPUT
0306           ISINDEX META ]
0307         methods += <<-BEGIN + nOE_element_def(element) + <<-END
0308           def #{element.downcase}(attributes = {})
0309         BEGIN
0310           end
0311         END
0312       end
0313 
0314       # O O or - O
0315       for element in %w[ HTML HEAD BODY P PLAINTEXT DT DD LI OPTION tr
0316           th td ]
0317         methods += <<-BEGIN + nO_element_def(element) + <<-END
0318           def #{element.downcase}(attributes = {})
0319         BEGIN
0320           end
0321         END
0322       end
0323       eval(methods)
0324     end
0325 
0326   end
0327 
0328 # following snippet from Webrick's log.rb
0329 # notice the erronous handling of the query method is_a?
0330 def format(arg)
0331      str = if arg.is_a?(Exception)
0332         "#{arg.class}: #{arg.message}\n\t" <<
0333         arg.backtrace.join("\n\t") << "\n"
0334       elsif arg.respond_to?(:to_str)
0335         arg.to_str
0336       else
0337         arg.inspect
0338       end
0339 end
0340 
0341 # following snippet from Webrick's httputils.rb
0342 # Splitting regexps on several lines might be bad form,
0343 # but not illegal in Ruby. 
0344 # This should probably be supported in the highlighting
0345 def split_header_value(str)
0346       str.scan(/((?:"(?:\\.|[^"])+?"|[^",]+)+)
0347                 (?:,\s*|\Z)/xn).collect{|v| v[0] }
0348 end
0349 
0350 # snippet from Net::Telnet
0351 string.gsub(/#{IAC}(
0352                    [#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]|
0353                    [#{DO}#{DONT}#{WILL}#{WONT}]
0354                      [#{OPT_BINARY}-#{OPT_NEW_ENVIRON}#{OPT_EXOPL}]|
0355                    #{SB}[^#{IAC}]*#{IAC}#{SE}
0356                  )/xno)
0357 
0358 # following snippet from Webrick's httpresponse.rb
0359 # the HEREDOC is not recognized as such
0360 @body << <<-_end_of_html_
0361 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
0362 <HTML>
0363   <HEAD><TITLE>#{HTMLUtils::escape(@reason_phrase)}</TITLE></HEAD>
0364   <BODY>
0365     <H1>#{HTMLUtils::escape(@reason_phrase)}</H1>
0366     #{HTMLUtils::escape(ex.message)}
0367     <HR>
0368 _end_of_html_
0369 
0370 
0371 # snippet from Webrick's httpproxy.rb
0372 # here we should make sure that the symbol definition ':' doesn't override
0373 # the module operator '::'
0374 Net::HTTP::version_1_2 if RUBY_VERSION < "1.7"
0375 
0376 # snippet from Webrick's cookie.rb
0377 # the beginning of the regexp is erronously highlighted like an operator
0378 key, val = x.split(/=/,2)
0379 
0380 # the following are division operators
0381 # it's a bit tricky to keep the operator apart from the regexp
0382 result = 8 / 4
0383 result /= divisor
0384 
0385 # 2008-06-01 regexp and division operator syntax has been fixed:
0386 result = 8/4    # division
0387 result = 8/foo  # division
0388 result = /8/    # regexp
0389 result = 8//4/  # division and regexp
0390 
0391 10/10           # division
0392 10/ 10          # division
0393 10 /10          # division
0394 10 / 10         # division
0395 
0396 foo/10          # division
0397 foo/ 10         # division
0398 foo /10/        # regexp
0399 foo / 10        # division
0400 
0401 foo/10/10       # both division
0402 total/count/2   # both division
0403 total/(count/2) # both division
0404 
0405 @foo/10         # division
0406 @foo /10        # division
0407 
0408 "hello"/10      # division
0409 "hello" / 10    # division
0410 
0411 /regexp//10     # division
0412 /regexp/ / 10   # division
0413 
0414 Math::PI/10     # division
0415 Math::foo /rx/  # regexp
0416 
0417 # 2008-06-05 similar fix for modulo operator:
0418 
0419 10%4            # modulo
0420 10 %4           # modulo
0421 10% 4           # modulo
0422 10 % 4          # modulo
0423 
0424 foo%4           # modulo
0425 # foo %4          # illegal %string
0426 foo% 4          # modulo
0427 foo % 4         # modulo
0428 
0429 foo % (4)       # modulo
0430 
0431 foo %(4)        # %string
0432 foo %q(4)       # %string
0433 foo %Q(4)       # %string
0434 foo %%4%        # %string
0435 
0436 foo = %|blah|   # GDL input
0437 foo % %|blah|   # modulo and GDL
0438 
0439 # mix in any way you want
0440 result = 10//regexp//20/foo//regexp//20
0441 
0442 # test cases for general delimited input
0443 # quoted strings
0444 %Q|this is a string|
0445 %Q{this is a string}
0446 %Q(this is a string)
0447 %Q<this is a string>
0448 %Q[this is a string]
0449 
0450 %|also a string|
0451 %{also a string}
0452 %(also a string)
0453 %<also a string>
0454 %[also a string]
0455 
0456 # apostrophed strings
0457 %q|apostrophed|
0458 %q{apostrophed}
0459 %q(apostrophed)
0460 %q<apostrophed>
0461 %q[apostrophed]
0462 
0463 # regular expressions
0464 %r{expression}
0465 %r(expression)
0466 %r<expression>
0467 %r[expression]
0468 %r|expression|
0469 
0470 # shell commands
0471 %x{ls -l}
0472 %x(ls -l)
0473 %x<ls -l>
0474 %x[ls -l]
0475 
0476 # sometimes it's useful to have the command on multiple lines
0477 %x{ls -l |
0478 grep test }
0479 
0480 # alternative syntax
0481 `ls -l`
0482 `echo ' '`
0483 
0484 # token array
0485 %w{one two three}
0486 %w(one two three)
0487 %w<one two three>
0488 %w[one two three]
0489 
0490 # snippet from Net::IMAP
0491 # I object to putting String, Integer and Array into kernel methods.
0492 # While these classes are builtin in Ruby, this is an implementation detail
0493 # that should not be exposed to the user.
0494 # If we want to handle all std-lib classes, fine. But then they should be in their
0495 # own std-lib keyword category.
0496 
0497 def send_data(data)
0498       case data
0499       when nil
0500         put_string("NIL")
0501       when String
0502         send_string_data(data)
0503       when Integer
0504         send_number_data(data)
0505       when Array
0506         send_list_data(data)
0507       when Time
0508         send_time_data(data)
0509       when Symbol
0510         send_symbol_data(data)
0511       else
0512         data.send_data(self)
0513       end
0514 end
0515 
0516 # snippet from Net::POP
0517 # class names can have numbers in them as long as they don't begin with numbers
0518 # Ruby doesn't internally really make much of a difference between a class name and a constant
0519 
0520 # class aliases
0521   POP = POP3
0522   POPSession  = POP3
0523   POP3Session = POP3
0524 
0525 # "member access"
0526 POP::Session.COUNT.attribute.calc_with(2){ |arg| puts arg }
0527 
0528 # snippet from Net::SMTP
0529 # This breaks the code folding. I think we would need to
0530 # handle the '\' that continues the statement to the next line
0531 # in some way to make these kind of things not break something.
0532 raise ArgumentError, 'both user and secret are required'\
0533                       unless user and secret
0534  
0535 # string escapes must detect escaping the escape char
0536 str = "\\"
0537 str = "\\\\"
0538 # this is not part of the string
0539 %x{echo \\\}\\} # prints \}\
0540 # this is not part of the command
0541 
0542 # these are all symbols
0543 :abc
0544 :abc!
0545 :abc?
0546 :abc=
0547 :[]
0548 :[]=
0549 :@abc
0550 :@@abc
0551 :$abc
0552 
0553 # squiggly HEREDOC
0554     <<~HEREDOC
0555       Hello!!
0556     HEREDOC
0557 
0558 # HEREDOC with backticks
0559 <<`HEREDOC`
0560     echo "hello"
0561 HEREDOC
0562 
0563 # do not highlight HEREDOC markers after the "class" keyword
0564 # (singleton class definition) (bug: #358273)
0565 class <<Foo = Object.new
0566   attr_accessor :foo
0567 end
0568 singleton_class = ( class <<foo; self; end )
0569 
0570 # highlight regular expressions after ": " (bug: #361875)
0571 get 'files/:slug/:filename', to: 'files#download', slug: /^[a-z]+$/, filename: %r|^[/\s]+$|
0572 @@hello!: /regexp/
0573 []=: %r!regexp!
0574 
0575 # refinements and its usage
0576 module Constantize
0577   refine String do
0578     def constantize
0579       ::Kernel.const_get(self)
0580     end
0581   end
0582 end
0583 
0584 class MyClass
0585   using Constantize
0586 
0587   SOME_CONST = "Kate is cool!"
0588 
0589   def self.method_using_refinement
0590     "MyClass::SOME_CONST".constantize
0591   end
0592 end
0593 
0594 puts MyClass.method_using_refinement