Module Capcode
In: lib/capcode.rb
lib/capcode/base/db.rb
lib/capcode/configuration.rb
lib/capcode/filters.rb
lib/capcode/render/text.rb
lib/capcode/helpers/auth.rb

Methods

Route   application   before_filter   env   http_authentication   map   params   request   response   run   session   set   use  

Included Modules

Rack Capcode::Helpers Capcode::Views

Classes and Modules

Module Capcode::Helpers
Module Capcode::Resource
Module Capcode::Views
Class Capcode::Base
Class Capcode::Configuration
Class Capcode::HTTPError

Constants

Route = Capcode::Route(nil)

Attributes

__auth__  [RW] 

Public Class methods

Add routes to a controller class

  module Capcode
    class Hello < Route '/hello/(.*)', '/hello/([^#]*)#(.*)'
      def get( arg1, arg2 )
        ...
      end
    end
  end

In the get method, you will receive the maximum of parameters declared by the routes. In this example, you will receive 2 parameters. So if you go to /hello/world#friend then arg1 will be set to world and arg2 will be set to friend. Now if you go to /hello/you, then arg1 will be set to you and arg2 will be set to nil

If the regexp in the route does not match, all arguments will be nil

[Source]

     # File lib/capcode.rb, line 363
363:     def Route *routes_paths
364:       create_path = routes_paths[0].nil?
365:       Class.new {
366:         meta_def(:__urls__) {
367:           routes_paths = ['/'+self.to_s.gsub( /^Capcode::/, "" ).underscore] if create_path == true
368:           # < Route '/hello/world/([^\/]*)/id(\d*)', '/hello/(.*)', :agent => /Songbird (\d\.\d)[\d\/]*?/
369:           # # => [ {'/hello/world' => '([^\/]*)/id(\d*)', '/hello' => '(.*)'}, 
370:           #        2, 
371:           #        <Capcode::Klass>, 
372:           #        {:agent => /Songbird (\d\.\d)[\d\/]*?/} ]
373:           hash_of_routes = {}
374:           max_captures_for_routes = 0
375:           routes_paths.each do |current_route_path|
376:             if current_route_path.class == String
377:               m = /\/([^\/]*\(.*)/.match( current_route_path )
378:               if m.nil?
379:                 raise Capcode::RouteError, "Route `#{current_route_path}' already defined with regexp `#{hash_of_routes[current_route_path]}' !", caller if hash_of_routes.keys.include?(current_route_path)
380:                 hash_of_routes[current_route_path] = ''
381:               else
382:                 _pre = m.pre_match
383:                 _pre = "/" if _pre.size == 0
384:                 raise Capcode::RouteError, "Route `#{_pre}' already defined with regexp `#{hash_of_routes[_pre]}' !", caller if hash_of_routes.keys.include?(_pre)
385:                 hash_of_routes[_pre] = m.captures[0]
386:                 max_captures_for_routes = Regexp.new(m.captures[0]).number_of_captures if max_captures_for_routes < Regexp.new(m.captures[0]).number_of_captures
387:               end
388:             else
389:               raise Capcode::ParameterError, "Bad route declaration !", caller
390:             end
391:           end
392:           [hash_of_routes, max_captures_for_routes, self]
393:         }
394:                 
395:         # Hash containing all the request parameters (GET or POST)
396:         def params
397:           @request.params
398:         end
399:         
400:         # Hash containing all the environment variables
401:         def env
402:           @env
403:         end
404:         
405:         # Session hash
406:         def session
407:           @env['rack.session']
408:         end
409:         
410:         # Return the Rack::Request object
411:         def request
412:           @request
413:         end
414:         
415:         # Return the Rack::Response object
416:         def response
417:           @response
418:         end
419:         
420:         def call( e ) #:nodoc:
421:           @env = e
422:           @response = Rack::Response.new
423:           @request = Rack::Request.new(@env)
424: 
425:           # Check authz
426:           authz_options = nil
427:           if Capcode.__auth__ and Capcode.__auth__.size > 0
428:             authz_options = Capcode.__auth__[@request.path]||nil
429:             if authz_options.nil?
430:               route = nil
431:               
432:               Capcode.__auth__.each do |r, o|
433:                 regexp = "^#{r.gsub(/\/$/, "")}([/]{1}.*)?$"
434:                 if Regexp.new(regexp).match( @request.path )
435:                   if route.nil? or r.size > route.size
436:                     route = r
437:                     authz_options = o
438:                   end
439:                 end  
440:               end
441:             end
442:           end
443: 
444:           r = catch(:halt) { 
445:             unless authz_options.nil?
446:               http_authentication( :type => authz_options[:type], :realm => authz_options[:realm], :opaque => authz_options[:realm] ) { 
447:                 authz_options[:autz]
448:               }
449:             end
450: 
451:             finalPath = nil
452:             finalArgs = nil
453:             finalNArgs = nil
454:             
455:             aPath = @request.path.gsub( /^\//, "" ).split( "/" )
456:             self.class.__urls__[0].each do |p, r|
457:               xPath = p.gsub( /^\//, "" ).split( "/" )
458:               if (xPath - aPath).size == 0
459:                 diffArgs = aPath - xPath
460:                 diffNArgs = diffArgs.size - 1
461:                 if finalNArgs.nil? or finalNArgs > diffNArgs
462:                   finalPath = p
463:                   finalNArgs = diffNArgs
464:                   finalArgs = diffArgs
465:                 end
466:               end
467:             end
468:             
469:             if finalNArgs > self.class.__urls__[1]
470:               return [404, {'Content-Type' => 'text/plain'}, "Not Found: #{@request.path}"]
471:             end
472:         
473:             nargs = self.class.__urls__[1]
474:             regexp = Regexp.new( self.class.__urls__[0][finalPath] )
475:             args = regexp.match( Rack::Utils.unescape(@request.path).gsub( Regexp.new( "^#{finalPath}" ), "" ).gsub( /^\//, "" ) )
476:             if args.nil?
477:               raise Capcode::ParameterError, "Path info `#{@request.path_info}' does not match route regexp `#{regexp.source}'"
478:             else
479:               args = args.captures.map { |x| (x.size == 0)?nil:x }
480:             end
481:             
482:             while args.size < nargs
483:               args << nil
484:             end
485: 
486:             filter_output = Capcode::Filter.execute( self )
487: 
488:             if( filter_output.nil? )
489:               case @env["REQUEST_METHOD"]
490:                 when "GET"                      
491:                   get( *args )
492:                 when "POST"
493:                   _method = params.delete( "_method" ) { |_| "post" }
494:                   send( _method.downcase.to_sym, *args )
495:                 else
496:                   _method = @env["REQUEST_METHOD"]
497:                   send( _method.downcase.to_sym, *args )
498:               end
499:             else
500:               filter_output
501:             end
502:           }
503:           
504:           if r.respond_to?(:to_ary)
505:             @response.status = r.shift #r[0]
506:             #r[1].each do |k,v|
507:             r.shift.each do |k,v|
508:               @response[k] = v
509:             end
510:             @response.write r.shift #r[2]
511:           else
512:             @response.write r
513:           end
514:           
515:           @response.finish
516:         end
517:                 
518:         include Capcode::Helpers
519:         include Capcode::Views        
520:       }      
521:     end

Return the Rack App.

Options : see Capcode::Configuration.set

Options set here replace the ones set globally

[Source]

     # File lib/capcode.rb, line 590
590:     def application( args = {} )
591:       Capcode::Configuration.configuration(args)
592:       
593:       Capcode.constants.clone.delete_if {|k| 
594:         not( Capcode.const_get(k).to_s =~ /Capcode/ ) or [
595:           "Filter", 
596:           "Helpers", 
597:           "RouteError", 
598:           "Views", 
599:           "ParameterError", 
600:           "HTTPError", 
601:           "Configuration", 
602:           "MissingLibrary", 
603:           "Route", 
604:           "RenderError"
605:         ].include?(k)
606:       }.each do |k|
607:         begin
608:           if eval "Capcode::#{k}.public_methods(true).include?( '__urls__' )"
609:             hash_of_routes, max_captures_for_routes, klass = eval "Capcode::#{k}.__urls__"            
610:             hash_of_routes.keys.each do |current_route_path|
611:               #raise Capcode::RouteError, "Route `#{current_route_path}' already define !", caller if @@__ROUTES.keys.include?(current_route_path)
612:               raise Capcode::RouteError, "Route `#{current_route_path}' already define !", caller if Capcode.routes.keys.include?(current_route_path)
613: #              Capcode.routes[current_route_path] = klass.new
614:               Capcode.routes[current_route_path] = klass
615:             end
616:           end
617:         rescue => e
618:           raise e.message
619:         end
620:       end
621:       
622:       # Set Static directory
623:       Capcode.static = (Capcode::Configuration.get(:static)[0].chr == "/")?Capcode::Configuration.get(:static):"/"+Capcode::Configuration.get(:static) unless Capcode::Configuration.get(:static).nil?
624:       
625:       # Initialize Rack App
626:       puts "** Map routes." if Capcode::Configuration.get(:verbose)
627: #      app = Rack::URLMap.new(Capcode.routes)
628:       app = Capcode::Ext::Rack::URLMap.new(Capcode.routes)
629:       puts "** Initialize static directory (#{Capcode.static}) in #{File.expand_path(Capcode::Configuration.get(:root))}" if Capcode::Configuration.get(:verbose)
630:       app = Rack::Static.new( 
631:         app, 
632:         #:urls => [@@__STATIC_DIR], 
633:         :urls => [Capcode.static], 
634:         :root => File.expand_path(Capcode::Configuration.get(:root)) 
635:       ) unless Capcode::Configuration.get(:static).nil?
636:       puts "** Initialize session" if Capcode::Configuration.get(:verbose)
637:       app = Rack::Session::Cookie.new( app, Capcode::Configuration.get(:session) )
638:       app = Capcode::HTTPError.new(app)
639:       app = Rack::ContentLength.new(app)
640:       app = Rack::Lint.new(app)
641:       app = Rack::ShowExceptions.new(app)
642:       #app = Rack::Reloader.new(app) ## -- NE RELOAD QUE capcode.rb -- So !!!
643:       
644:       middlewares.each do |mw|
645:         middleware, args, block = mw
646:         puts "** Load middleware #{middleware}" if Capcode::Configuration.get(:verbose)
647:         if block
648:           app = middleware.new( app, *args, &block )
649:         else
650:           app = middleware.new( app, *args )
651:         end
652:       end
653:       
654:       # Start database
655:       if self.methods.include? "db_connect"
656:         db_connect( Capcode::Configuration.get(:db_config), Capcode::Configuration.get(:log) )
657:       end
658:       
659:       if block_given?
660:         puts "** Execute block" if Capcode::Configuration.get(:verbose)
661:         yield( self )
662:       end
663:       
664:       return app
665:     end

Add a before filter :

  module Capcode
    before_filter :my_global_action
    before_filter :need_login, :except => [:Login]
    before_filter :check_mail, :only => [:MailBox]
    # ...
  end

If the action return nil, the normal get or post will be executed, else no.

[Source]

    # File lib/capcode/filters.rb, line 14
14:     def before_filter( action, opts = {} )
15:       Capcode::Filter.filters[action] = { }
16:       
17:       opts.each do |k, v|
18:         Capcode::Filter.filters[action][k] = v
19:       end
20:     end

Hash containing all the environment variables

[Source]

     # File lib/capcode.rb, line 401
401:         def env
402:           @env
403:         end

Allow you to add and HTTP Authentication (Basic or Digest) to controllers for or specific route

Options :

  • :type : Authentication type (:basic or :digest) - default : :basic
  • :realm : realm ;) - default : "Capcode.app"
  • :opaque : Your secret passphrase. You MUST set it if you use Digest Auth - default : "opaque"
  • :routes : Routes - default : "/"

The block must return a Hash of username => password like that :

  {
    "user1" => "pass1",
    "user2" => "pass2",
    # ...
  }

[Source]

     # File lib/capcode.rb, line 564
564:     def http_authentication( opts = {}, &b )
565:       options = {
566:         :type => :basic,
567:         :realm => "Capcode.app",
568:         :opaque => "opaque",
569:         :routes => "/"
570:       }.merge( opts )
571:       
572:       options[:autz] = b.call()
573:       
574:       @__auth__ ||= {}
575:       
576:       if options[:routes].class == Array
577:         options[:routes].each do |r|
578:           @__auth__[r] = options
579:         end
580:       else
581:         @__auth__[options[:routes]] = options
582:       end      
583:     end

This method help you to map and URL to a Rack or What you want Helper

  Capcode.map( "/file" ) do
    Rack::File.new( "." )
  end

[Source]

     # File lib/capcode.rb, line 529
529:     def map( route, &b )
530:       Capcode.routes[route] = yield
531:     end

Hash containing all the request parameters (GET or POST)

[Source]

     # File lib/capcode.rb, line 396
396:         def params
397:           @request.params
398:         end

Return the Rack::Request object

[Source]

     # File lib/capcode.rb, line 411
411:         def request
412:           @request
413:         end

Return the Rack::Response object

[Source]

     # File lib/capcode.rb, line 416
416:         def response
417:           @response
418:         end

Start your application.

Options : see Capcode::Configuration.set

Options set here replace the ones set globally

[Source]

     # File lib/capcode.rb, line 672
672:     def run( args = {} )
673:       Capcode::Configuration.configuration(args)
674:       
675:       # Parse options
676:       opts = OptionParser.new do |opts|
677:         opts.banner = "Usage: #{File.basename($0)} [options]"
678:         opts.separator ""
679:         opts.separator "Specific options:"
680: 
681:         opts.on( "-C", "--console", "Run in console mode with IRB (default: false)" ) { 
682:           Capcode::Configuration.set :console, true
683:         }
684:         opts.on( "-h", "--host HOSTNAME", "Host for web server to bind to (default: #{Capcode::Configuration.get(:host)})" ) { |h|
685:           Capcode::Configuration.set :host, h
686:         }
687:         opts.on( "-p", "--port NUM", "Port for web server (default: #{Capcode::Configuration.get(:port)})" ) { |p|
688:           Capcode::Configuration.set :port, p
689:         }
690:         opts.on( "-d", "--daemonize [true|false]", "Daemonize (default: #{Capcode::Configuration.get(:daemonize)})" ) { |d|
691:           Capcode::Configuration.set :daemonize, d
692:         }
693:         opts.on( "-r", "--root PATH", "Working directory (default: #{Capcode::Configuration.get(:root)})" ) { |w|
694:           Capcode::Configuration.set :root, w
695:         }
696:         opts.on( "-s", "--static PATH", "Static directory -- relative to the root directory (default: #{Capcode::Configuration.get(:static)})" ) { |r|
697:           Capcode::Configuration.set :static, r
698:         }
699: 
700:         opts.separator ""
701:         opts.separator "Common options:"
702: 
703:         opts.on("-?", "--help", "Show this message") do
704:           puts opts
705:           exit
706:         end  
707:         opts.on("-v", "--version", "Show versions") do
708:           puts "Capcode version #{Capcode::CAPCOD_VERION} (ruby v#{RUBY_VERSION})"
709:           exit
710:         end  
711:         opts.on_tail( "-V", "--verbose", "Run in verbose mode" ) do
712:           Capcode::Configuration.set :verbose, true
713:         end
714:       end
715:       
716:       begin
717:         opts.parse! ARGV
718:       rescue OptionParser::ParseError => ex
719:         puts "!! #{ex.message}"
720:         puts "** use `#{File.basename($0)} --help` for more details..."
721:         exit 1
722:       end
723:       
724:       # Run in the Working directory
725:       puts "** Go on root directory (#{File.expand_path(Capcode::Configuration.get(:root))})" if Capcode::Configuration.get(:verbose)
726:       Dir.chdir( Capcode::Configuration.get(:root) ) do
727:         
728:         # Check that mongrel exists 
729:         if Capcode::Configuration.get(:server).nil? || Capcode::Configuration.get(:server) == "mongrel"
730:           begin
731:             require 'mongrel'
732:             Capcode::Configuration.set :server, :mongrel
733:           rescue LoadError 
734:             puts "!! could not load mongrel. Falling back to webrick."
735:             Capcode::Configuration.set :server, :webrick
736:           end
737:         end
738:         
739:         # From rackup !!!
740:         if Capcode::Configuration.get(:daemonize)
741:           if /java/.match(RUBY_PLATFORM).nil?
742:             if RUBY_VERSION < "1.9"
743:               exit if fork
744:               Process.setsid
745:               exit if fork
746:               # Dir.chdir "/"
747:               File.umask 0000
748:               STDIN.reopen "/dev/null"
749:               STDOUT.reopen "/dev/null", "a"
750:               STDERR.reopen "/dev/null", "a"
751:             else
752:               Process.daemon
753:             end
754:           else
755:             puts "!! daemonize option unavailable on #{RUBY_PLATFORM} platform."
756:           end
757:         
758:           File.open(Capcode::Configuration.get(:pid), 'w'){ |f| f.write("#{Process.pid}") }
759:           at_exit { File.delete(Capcode::Configuration.get(:pid)) if File.exist?(Capcode::Configuration.get(:pid)) }
760:         end
761:         
762:         app = nil
763:         if block_given?
764:           app = application(Capcode::Configuration.get) { yield( self ) }
765:         else
766:           app = application(Capcode::Configuration.get)
767:         end
768:         app = Rack::CommonLogger.new( app, Logger.new(Capcode::Configuration.get(:log)) )
769:         
770:         if Capcode::Configuration.get(:console)
771:           puts "Run console..."
772:           IRB.start
773:           exit
774:         end
775:         
776:         # Start server
777:         case Capcode::Configuration.get(:server).to_s
778:         when "mongrel"
779:           puts "** Starting Mongrel on #{Capcode::Configuration.get(:host)}:#{Capcode::Configuration.get(:port)}"
780:           Rack::Handler::Mongrel.run( app, {:Port => Capcode::Configuration.get(:port), :Host => Capcode::Configuration.get(:host)} ) { |server|
781:             trap "SIGINT", proc { server.stop }
782:           }
783:         when "webrick"
784:           puts "** Starting WEBrick on #{Capcode::Configuration.get(:host)}:#{Capcode::Configuration.get(:port)}"
785:           Rack::Handler::WEBrick.run( app, {:Port => Capcode::Configuration.get(:port), :BindAddress => Capcode::Configuration.get(:host)} ) { |server|
786:             trap "SIGINT", proc { server.shutdown }
787:           }
788:         when "thin"
789:           puts "** Starting Thin on #{Capcode::Configuration.get(:host)}:#{Capcode::Configuration.get(:port)}"
790:           Rack::Handler::Thin.run( app, {:Port => Capcode::Configuration.get(:port), :Host => Capcode::Configuration.get(:host)} ) { |server|
791:             trap "SIGINT", proc { server.stop }
792:           }
793:         end
794:       end
795:     end

Session hash

[Source]

     # File lib/capcode.rb, line 406
406:         def session
407:           @env['rack.session']
408:         end

[Source]

   # File lib/capcode/configuration.rb, line 3
3:     def set(key, value, opts = {}); Configuration.set(key, value, opts); end

This method allow you to use a Rack middleware

Example :

  module Capcode
    ...
    use Rack::Codehighlighter, :coderay, :element => "pre",
      :pattern => /\A:::(\w+)\s*\n/, :logging => false
    ...
  end

[Source]

     # File lib/capcode.rb, line 543
543:     def use(middleware, *args, &block)
544:       middlewares << [middleware, args, block]
545:     end

[Validate]