Class: Egalite::Handler

Inherits:
Object show all
Defined in:
lib/egalite.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Handler

Returns a new instance of Handler.



406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
# File 'lib/egalite.rb', line 406

def initialize(opts = {})
  @routes = opts[:routes] || Route.default_routes
  
  db = opts[:db]
  @db = db
  @opts = opts
  @env = Environment.new(db, opts)
  opts[:static_root] ||= "static/"

  @template_path = opts[:template_path] || 'pages/'
  @template_path << '/' if @template_path[-1..-1] != '/'
  @template_engine = opts[:template_engine] || HTMLTemplate
  
  @profile_logger = opts[:profile_logger]
  @notfound_template = opts[:notfound_template]
  if opts[:error_template_file]
    @error_template = File.open(opts[:error_template_file]).read
  else
    @error_template = opts[:error_template]
  end
  @admin_emails = opts[:admin_emails]
  @email_from = opts[:email_from]
  @exception_log_table = opts[:exception_log_table]
  if @exception_log_table
    Egalite::ErrorLogger.table = db[@exception_log_table]
    Egalite::ErrorLogger.admin_emails = @admin_emails
    Egalite::ErrorLogger.email_from = @email_from
  end
end

Instance Attribute Details

#routesObject

Returns the value of attribute routes.



404
405
406
# File 'lib/egalite.rb', line 404

def routes
  @routes
end

Instance Method Details

#call(rack_env) ⇒ Object



702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
# File 'lib/egalite.rb', line 702

def call(rack_env)
  # set up logging
  
  res = nil

  req = Rack::Request.new(rack_env)
  
  begin
    ereq = Request.new(
      :rack_request => req,
      :rack_env => rack_env,
      :handler => self
    )

    # parameter handling
    params = stringify_hash(req.params)

    puts "before-cookie: #{req.cookies.inspect}" if @opts[:cookie_debug]
    
    ereq.params = params
    ereq.cookies = req.cookies

    authorization_keys = ['HTTP_AUTHORIZATION', 'X-HTTP_AUTHORIZATION', 'X_HTTP_AUTHORIZATION']
    key = authorization_keys.detect { |key| rack_env.has_key?(key) }
    ereq.authorization = rack_env[key] if key
    
    if @opts[:session_handler]
      ereq.session = @opts[:session_handler].new(@env,ereq.cookies, @opts[:session_opts] || {})
      ereq.session.load
    end
    
    res = dispatch(req.path_info, params, req.request_method, ereq, true)
    res = res.to_a

    puts "after-cookie: #{res[1]['Set-Cookie'].inspect}" if @opts[:cookie_debug]
    
    if res[0] == 200
      if res[1]['Content-Type'] !~ /charset/i and res[1]['Content-Type'] =~ /text\/html/i
        res[1]["Content-Type"] = @opts[:charset] || 'text/html; charset=utf-8'
      end
    end
    
   rescue Exception => e
    raise e if $raise_exception
    
    begin
      # write error log
      logid = nil
      if @exception_log_table and not e.is_a?(UserError)
        logid = ErrorLogger.write_exception(e,{:ipaddress => req.ip, :url => req.url})
      end
      
      # show exception
      
      if @error_template
        values = {}
        values[:logid] = logid if logid
        values[:exception] = e.to_s
        values[:backtrace] = e.backtrace
        values[:message] = e.message if e.is_a?(UserError) or e.is_a?(SystemError)
        values[:usererror] = true if e.is_a?(UserError)
        html = @template_engine.new.handleTemplate(@error_template.dup,values)
        res = [500, {"Content-type"=>"text/html; charset=utf-8"}, [html]]
      else
        res = display_internal_server_error(e)
      end
    rescue Exception => e2
      res = display_internal_server_error(e2)
    end
  end
  
  res = res.to_a
  p res if @opts[:response_debug]
  res
end

#dispatch(path, params, method, req, first_call = false) ⇒ Object



645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
# File 'lib/egalite.rb', line 645

def dispatch(path, params, method, req, first_call = false)
  # routing
  (controller_name, action_name, path_params, prmhash) = nil
  (controller, action) = nil
  
  route = @routes.find { |route|
    puts "Routing: matching: #{route.inspect}" if RouteDebug
    route_result = route.match(path)
    (controller_name, action_name, path_params, prmhash) = route_result
    next if route_result == nil
    puts "Routing: pre-matched: #{route_result.inspect}" if RouteDebug
    (controller, action) = get_controller(controller_name, action_name, method)
    true if controller
  }
  return display_notfound unless controller

  puts "Routing: matched: #{controller.class} #{action}" if RouteDebug
  params = prmhash.merge(params)
  
  req.route = route
  req.controller = controller_name
  req.controller_class = controller
  req.action = action_name
  req.action_method = action
  req.inner_path = path
  req.path_params = path_params
  req.path_info = path_params.join('/')

  res = run_controller(controller, action, req)
  
  if first_call
    controller.after_filter(res.to_a)
    
    # access log
    t = Time.now - req.time
    log = [req.time.iso8601, req.ipaddr, t, req.url, req.referrer]
    log += controller.log_values.to_a
    line = log.map {|s| s.to_s.gsub(/\t/,'')}.join("\t").gsub(/\n/,'')
    AccessLogger.write(line)
  end
  res
end

#inner_dispatch(req, values) ⇒ Object



544
545
546
547
548
549
550
551
552
553
# File 'lib/egalite.rb', line 544

def inner_dispatch(req, values)
  # recursive controller call to handle include tag or delegate.
  stringified = StringifyHash.create(values)
  (path, params) = req.route.get_path_and_params_from_params(stringified)
  newreq = req.clone
  newreq.params = params
  method = 'GET'
  method = values[:http_method] if values[:http_method]
  dispatch(path, params, method, newreq)
end

#run_controller(controller, action, req) ⇒ Object

Raises:

  • (SecurityError)


554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
# File 'lib/egalite.rb', line 554

def run_controller(controller, action, req)
  # invoke controller
  controller.env = @env
  controller.req = req
  controller.params = req.params
  
  before_filter_result = controller.before_filter
  if before_filter_result != true
    return before_filter_result if before_filter_result.is_a?(Array)
    return [200,{'Content-Type' => "text/html"},[before_filter_result]] if before_filter_result.is_a?(String)
    return forbidden unless before_filter_result.respond_to?(:command)
    response = case before_filter_result.command
     when :delegate
      inner_dispatch(req, before_filter_result.param)
     when :redirect
      redirect(before_filter_result.param)
     when :notfound
      display_notfound
     else
      forbidden
    end
    set_cookies_to_response(response,req)
    return response
  end
  
  nargs = controller.method(action).arity
  args = req.path_params[0,nargs.abs] || []
  if nargs > 0
    args.size.upto(nargs-1) { args << nil }
  end
  raise SecurityError unless controller.respond_to?(action, false)

  s = Time.now
  values = controller.send(action,*args)
  t = Time.now - s
  @profile_logger.puts "#{Time.now}: ctrl #{t}sec #{controller.class.name}.#{action} (#{req.path_info})" if @profile_logger
  
  values = controller.after_filter_return_value(values)
  
  # result handling
  result = if values.respond_to?(:command)
    case values.command
     when :delegate
      inner_dispatch(req, values.param)
     when :redirect
      redirect(values.param)
     when :notfound
      display_notfound
    end
  elsif values.is_a?(Array)
    values
  elsif values.is_a?(String)
    html = controller.after_filter_html(values)
    [200,{'Content-Type' => "text/html"},[html]]
  elsif values.is_a?(Rack::Response)
    values.to_a
  elsif values == nil
    raise "egalite error: controller returned nil as a response."
  else
    htmlfile = controller.template_file
    unless htmlfile
      htmlfile = [req.controller,req.action].compact.join('_')
      htmlfile = 'index' if htmlfile.blank?
      htmlfile += '.html'
    end
    html = load_template(@template_path + htmlfile)
    return [404, {"Content-Type" => "text/plain"}, ["Template not found: #{htmlfile}\n"]] unless html
    
    # apply on_html_load filter
    html = controller.filter_on_html_load(html, htmlfile)
    
    # apply html template
    template = @template_engine.new
    template.controller = controller

    s = Time.now
    template.handleTemplate(html,values) { |values|
      inner_dispatch(req,values)[2].join("")
    }
    t = Time.now - s
    
    html = controller.after_filter_html(html)
    
    @profile_logger.puts "#{Time.now}: view #{t}sec #{controller.class.name}.#{action} (#{req.path_info})" if @profile_logger

    [200,{"Content-Type"=>"text/html"},[html]]
  end
  set_cookies_to_response(result,req)
  return result
end