# Module: Capcode
[ "README", "AUTHORS", "COPYING", "lib/capcode.rb", nil].each do
Capcode.view_html
Capcode::Views.view_html
Capcode::Helpers.view_html
Capcode::HTTPError.view_html
Capcode::RenderError.view_html
Capcode::RouteError.view_html
Capcode::ParameterError.view_html
end

Module Capcode

(in files lib/capcode.rb )

Includes

Methods

Public Class method: Route(*u)

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

     # File lib/capcode.rb, line 202
202:     def Route *u
203:       Class.new {
204:         meta_def(:__urls__){
205:           # < Route '/hello/world/([^\/]*)/id(\d*)', '/hello/(.*)'
206:           # # => [ {'/hello/world' => '([^\/]*)/id(\d*)', '/hello' => '(.*)'}, 2, <Capcode::Klass> ]
207:           h = {}
208:           max = 0
209:           u.each do |_u|
210:             m = /\/([^\/]*\(.*)/.match( _u )
211:             if m.nil?
212:               raise Capcode::RouteError, "Route `#{_u}' already defined with regexp `#{h[_u]}' !", caller if h.keys.include?(_u)
213:               h[_u] = ''
214:             else
215:               _pre = m.pre_match
216:               _pre = "/" if _pre.size == 0
217:               raise Capcode::RouteError, "Route `#{_pre}' already defined with regexp `#{h[_pre]}' !", caller if h.keys.include?(_pre)
218:               h[_pre] = m.captures[0]
219:               max = Regexp.new(m.captures[0]).number_of_captures if max < Regexp.new(m.captures[0]).number_of_captures
220:             end
221:           end
222:           [h, max, self]
223:         }
224: 
225:         # Hash containing all the request parameters (GET or POST)
226:         def params
227:           @request.params
228:         end
229:         
230:         # Hash containing all the environment variables
231:         def env
232:           @env
233:         end
234:         
235:         # Hash session
236:         def session
237:           @env['rack.session']
238:         end
239:         
240:         # Return the Rack::Request object
241:         def request
242:           @request
243:         end
244:         
245:         # Return the Rack::Response object
246:         def response
247:           @response
248:         end
249:         
250:         def call( e ) #:nodoc:
251:           @env = e
252:           @response = Rack::Response.new
253:           @request = Rack::Request.new(@env)
254: 
255:           r = case @env["REQUEST_METHOD"]
256:             when "GET"
257:               finalPath = nil
258:               finalArgs = nil
259:               finalNArgs = nil
260:               
261:               aPath = @request.path.gsub( /^\//, "" ).split( "/" )
262:               self.class.__urls__[0].each do |p, r|
263:                 xPath = p.gsub( /^\//, "" ).split( "/" )
264:                 if (xPath - aPath).size == 0
265:                   diffArgs = aPath - xPath
266:                   diffNArgs = diffArgs.size
267:                   if finalNArgs.nil? or finalNArgs > diffNArgs
268:                     finalPath = p
269:                     finalNArgs = diffNArgs
270:                     finalArgs = diffArgs
271:                   end
272:                 end
273:                 
274:               end
275: 
276:               nargs = self.class.__urls__[1]
277:               regexp = Regexp.new( self.class.__urls__[0][finalPath] )
278:               
279:               args = regexp.match( Rack::Utils.unescape(@request.path).gsub( Regexp.new( "^#{finalPath}" ), "" ).gsub( /^\//, "" ) )
280:               if args.nil?
281:                 raise Capcode::ParameterError, "Path info `#{@request.path_info}' does not match route regexp `#{regexp.source}'"
282:               else
283:                 args = args.captures
284:               end
285:               
286:               while args.size < nargs
287:                 args << nil
288:               end
289:                                           
290:               get( *args )
291:             when "POST"
292:               post
293:           end
294:           if r.respond_to?(:to_ary)
295:             @response.status = r[0]
296:             r[1].each do |k,v|
297:               @response[k] = v
298:             end
299:             @response.body = r[2]
300:           else
301:             @response.write r
302:           end
303:           
304:           @response.finish
305:         end
306:                 
307:         include Capcode::Helpers
308:         include Capcode::Views
309:       }      
310:     end

Public Class method: env()

Hash containing all the environment variables

     # File lib/capcode.rb, line 231
231:         def env
232:           @env
233:         end

Public Class method: map( r ) {|| ...}

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

  Capcode.map( "/file" ) do
    Rack::File.new( "." )
  end
     # File lib/capcode.rb, line 317
317:     def map( r, &b )
318:       @@__ROUTES[r] = yield
319:     end

Public Class method: params()

Hash containing all the request parameters (GET or POST)

     # File lib/capcode.rb, line 226
226:         def params
227:           @request.params
228:         end

Public Class method: request()

Return the Rack::Request object

     # File lib/capcode.rb, line 241
241:         def request
242:           @request
243:         end

Public Class method: response()

Return the Rack::Response object

     # File lib/capcode.rb, line 246
246:         def response
247:           @response
248:         end

Public Class method: run( args = {} )

Start your application.

Options :

  • :port = Listen port
  • :host = Listen host
  • :server = Server type (webrick or mongrel)
  • :log = Output logfile (default: STDOUT)
  • :session = Session parameters. See Rack::Session for more informations
  • :pid = PID file (default: $0.pid)
  • :daemonize = Daemonize application (default: false)
  • :db_config = database configuration file (default: database.yml)
  • :root = root directory (default: "." — relative to the working directory)
  • :working_directory = Working directory (default: directory of the main.rb)
     # File lib/capcode.rb, line 334
334:     def run( args = {} )
335:       conf = {
336:         :port => args[:port]||3000, 
337:         :host => args[:host]||"localhost",
338:         :server => args[:server]||nil,
339:         :log => args[:log]||$stdout,
340:         :session => args[:session]||{},
341:         :pid => args[:pid]||"#{$0}.pid",
342:         :daemonize => args[:daemonize]||false,
343:         :db_config => args[:db_config]||"database.yml",
344:         :root => args[:root]||".",
345:         :working_directory => args[:working_directory]||File.expand_path(File.dirname($0))
346:       }
347:       
348:       # Run in the Working directory
349:       Dir.chdir( conf[:working_directory] ) do
350:         # Set root directory for helpers
351:         Capcode::Helpers.root = File.expand_path( conf[:root] )
352:         
353:         # Check that mongrel exists 
354:         if conf[:server].nil? || conf[:server] == "mongrel"
355:           begin
356:             require 'mongrel'
357:             conf[:server] = "mongrel"
358:           rescue LoadError 
359:             puts "!! could not load mongrel. Falling back to webrick."
360:             conf[:server] = "webrick"
361:           end
362:         end
363:             
364:         Capcode.constants.each do |k|
365:           begin
366:             if eval "Capcode::#{k}.public_methods(true).include?( '__urls__' )"
367:               u, m, c = eval "Capcode::#{k}.__urls__"
368:               u.keys.each do |_u|
369:                 raise Capcode::RouteError, "Route `#{_u}' already define !", caller if @@__ROUTES.keys.include?(_u)
370:                 @@__ROUTES[_u] = c.new
371:               end
372:             end
373:           rescue => e
374:             raise e.message
375:           end
376:         end
377:         
378:         app = Rack::URLMap.new(@@__ROUTES)
379:         app = Rack::Session::Cookie.new( app, conf[:session] )
380:         app = Capcode::HTTPError.new(app, conf[:root])
381:         app = Rack::ContentLength.new(app)
382:         app = Rack::Lint.new(app)
383:         app = Rack::ShowExceptions.new(app)
384: #        app = Rack::Reloader.new(app) ## -- NE RELOAD QUE capcode.rb -- So !!!
385:         app = Rack::CommonLogger.new( app, Logger.new(conf[:log]) )
386:         
387:         # From rackup !!!
388:         if conf[:daemonize]
389:           if RUBY_VERSION < "1.9"
390:             exit if fork
391:             Process.setsid
392:             exit if fork
393:             # Dir.chdir "/"
394:             File.umask 0000
395:             STDIN.reopen "/dev/null"
396:             STDOUT.reopen "/dev/null", "a"
397:             STDERR.reopen "/dev/null", "a"
398:           else
399:             Process.daemon
400:           end
401:         
402:           File.open(conf[:pid], 'w'){ |f| f.write("#{Process.pid}") }
403:           at_exit { File.delete(conf[:pid]) if File.exist?(conf[:pid]) }
404:         end
405:         
406:         # Start database
407:         if self.methods.include? "db_connect"
408:           db_connect( conf[:db_config], conf[:log] )
409:         end
410:         
411:         # Start server
412:         case conf[:server]
413:         when "mongrel"
414:           puts "** Starting Mongrel on #{conf[:host]}:#{conf[:port]}"
415:           Rack::Handler::Mongrel.run( app, {:Port => conf[:port], :Host => conf[:host]} ) { |server|
416:             trap "SIGINT", proc { server.stop }
417:           }
418:         when "webrick"
419:           puts "** Starting WEBrick on #{conf[:host]}:#{conf[:port]}"
420:           Rack::Handler::WEBrick.run( app, {:Port => conf[:port], :BindAddress => conf[:host]} ) { |server|
421:             trap "SIGINT", proc { server.shutdown }
422:           }
423:         end
424:       end
425:     end

Public Class method: session()

Hash session

     # File lib/capcode.rb, line 236
236:         def session
237:           @env['rack.session']
238:         end