padrino-core 0.9.28 → 0.9.29

Sign up to get free protection for your applications and to get access to all the features.
@@ -37,9 +37,9 @@ module Padrino
37
37
  # Returns the resulting rack builder mapping each 'mounted' application
38
38
  #
39
39
  def application
40
- raise ApplicationLoadError, "At least one app must be mounted!" unless self.mounted_apps && self.mounted_apps.any?
40
+ raise ApplicationLoadError, "At least one app must be mounted!" unless Padrino.mounted_apps && Padrino.mounted_apps.any?
41
41
  router = Padrino::Router.new
42
- self.mounted_apps.each { |app| app.map_onto(router) }
42
+ Padrino.mounted_apps.each { |app| app.map_onto(router) }
43
43
 
44
44
  unless middleware.empty?
45
45
  builder = Rack::Builder.new
@@ -85,23 +85,12 @@ module Padrino
85
85
  nil
86
86
  end
87
87
 
88
- ##
89
- # Returns the used $LOAD_PATHS from padrino
90
- #
91
- def load_paths
92
- %w(
93
- lib
94
- models
95
- shared
96
- ).map { |dir| root(dir) }
97
- end
98
-
99
88
  ##
100
89
  # Return bundle status :+:locked+ if .bundle/environment.rb exist :+:unlocked if Gemfile exist
101
90
  # otherwise return nil
102
91
  #
103
92
  def bundle
104
- return :locked if File.exist?(root('.bundle/environment.rb'))
93
+ return :locked if File.exist?(root('Gemfile.lock'))
105
94
  return :unlocked if File.exist?(root("Gemfile"))
106
95
  end
107
96
 
@@ -8,17 +8,21 @@ module Padrino
8
8
  #
9
9
  class Application < Sinatra::Base
10
10
  register Padrino::Routing # Support for advanced routing, controllers, url_for
11
- register Padrino::Rendering # Support for enhanced rendering with template detection
11
+ unless defined?(SKIP_PADRINO_RENDERING) && SKIP_PADRINO_RENDERING
12
+ register Padrino::Rendering # Support for enhanced rendering with template detection
13
+ end
12
14
 
13
15
  class << self
14
16
 
15
- def inherited(subclass) #:nodoc:
17
+ def inherited(base) #:nodoc:
18
+ logger.devel "Setup #{base}"
16
19
  CALLERS_TO_IGNORE.concat(PADRINO_IGNORE_CALLERS)
17
- subclass.default_configuration!
18
- Padrino.set_load_paths File.join(subclass.root, "/models")
19
- Padrino.require_dependencies File.join(subclass.root, "/models.rb")
20
- Padrino.require_dependencies File.join(subclass.root, "/models/**/*.rb")
21
- super(subclass) # Loading the subclass inherited method
20
+ base.default_configuration!
21
+ Padrino.require_dependencies File.join(base.root, "/models.rb")
22
+ Padrino.require_dependencies File.join(base.root, "/models/**/*.rb")
23
+ Padrino.require_dependencies File.join(base.root, "/lib.rb")
24
+ Padrino.require_dependencies File.join(base.root, "/lib/**/*.rb")
25
+ super(base) # Loading the subclass inherited method
22
26
  end
23
27
 
24
28
  ##
@@ -47,13 +51,13 @@ module Padrino
47
51
  # MyApp.reload!
48
52
  #
49
53
  def reload!
54
+ logger.devel "Reloading #{self}"
55
+ @_dependencies = nil # Reset dependencies
50
56
  reset! # Reset sinatra app
51
57
  reset_routes! # Remove all existing user-defined application routes
52
- Padrino.require_dependencies(File.join(self.root, "/models.rb")) # Reload models class
53
- Padrino.require_dependencies(File.join(self.root, "/models/**/*.rb")) # Reload all models
54
- Padrino.require_dependencies(self.app_file) # Reload the app file
58
+ Padrino.require_dependencies(self.app_file, :force => true) # Reload the app file
59
+ require_dependencies # Reload dependencies
55
60
  register_initializers # Reload our middlewares
56
- require_load_paths # Reload dependencies
57
61
  default_filters! # Reload filters
58
62
  default_errors! # Reload our errors
59
63
  I18n.reload! if defined?(I18n) # Reload also our translations
@@ -89,7 +93,7 @@ module Padrino
89
93
  def setup_application!
90
94
  return if @_configured
91
95
  self.register_initializers
92
- self.require_load_paths
96
+ self.require_dependencies
93
97
  self.disable :logging # We need do that as default because Sinatra use commonlogger.
94
98
  self.default_filters!
95
99
  self.default_routes!
@@ -107,20 +111,30 @@ module Padrino
107
111
  #
108
112
  def run!(options={})
109
113
  return unless Padrino.load!
110
- set options
111
- handler = detect_rack_handler
112
- handler_name = handler.name.gsub(/.*::/, '')
113
- puts "=> #{self.name}/#{Padrino.version} has taken the stage #{Padrino.env} on #{port}" unless handler_name =~/cgi/i
114
- handler.run self, :Host => bind, :Port => port do |server|
115
- trap(:INT) do
116
- ## Use thins' hard #stop! if available, otherwise just #stop
117
- server.respond_to?(:stop!) ? server.stop! : server.stop
118
- puts "<= #{self.name} has ended his set (crowd applauds)" unless handler_name =~/cgi/i
119
- end
120
- set :running, true
121
- end
122
- rescue Errno::EADDRINUSE => e
123
- puts "<= Someone is already performing on port #{port}!"
114
+ Padrino.mount(self.to_s).to("/")
115
+ Padrino.run!
116
+ end
117
+
118
+ ##
119
+ # Returns the used $LOAD_PATHS from this application
120
+ #
121
+ def load_paths
122
+ @_load_paths ||= %w(models lib mailers controllers helpers).map { |path| File.join(self.root, path) }
123
+ end
124
+
125
+ ##
126
+ # Returns default list of path globs to load as dependencies
127
+ # Appends custom dependency patterns to the be loaded for your Application
128
+ #
129
+ # ==== Examples
130
+ # MyApp.dependencies << "#{Padrino.root}/uploaders/**/*.rb"
131
+ # MyApp.dependencies << Padrino.root('other_app', 'controllers.rb')
132
+ #
133
+ def dependencies
134
+ @_dependencies ||= [
135
+ "urls.rb", "config/urls.rb", "mailers/*.rb", "mailers.rb",
136
+ "controllers/**/*.rb", "controllers.rb", "helpers/**/*.rb", "helpers.rb"
137
+ ].map { |file| Dir[File.join(self.root, file)] }.flatten
124
138
  end
125
139
 
126
140
  protected
@@ -195,23 +209,16 @@ module Padrino
195
209
  use Padrino::ShowExceptions if show_exceptions?
196
210
  use Padrino::Logger::Rack, uri_root if Padrino.logger && logging?
197
211
  use Padrino::Reloader::Rack if reload?
198
- use Rack::Flash if flash?
199
- end
200
-
201
- ##
202
- # Returns the load_paths for the application (relative to the application root)
203
- #
204
- def load_paths
205
- @load_paths ||= ["urls.rb", "config/urls.rb", "mailers/*.rb", "mailers.rb",
206
- "controllers/**/*.rb", "controllers.rb", "helpers/**/*.rb", "helpers.rb"]
212
+ use Rack::Flash, :sweep => true if flash?
207
213
  end
208
214
 
209
215
  ##
210
216
  # Requires all files within the application load paths
211
217
  #
212
- def require_load_paths
213
- load_paths.each { |path| Padrino.require_dependencies(File.join(self.root, path)) }
218
+ def require_dependencies
219
+ Padrino.set_load_paths(*load_paths)
220
+ Padrino.require_dependencies(dependencies, :force => true)
214
221
  end
215
222
  end # self
216
223
  end # Application
217
- end # Padrino
224
+ end # Padrino
@@ -17,12 +17,12 @@ module Padrino
17
17
  #
18
18
  IGNORE_FILE_PATTERN = [
19
19
  /~$/ # This is for Gedit
20
- ]
20
+ ] unless defined?(IGNORE_FILE_PATTERN)
21
21
 
22
22
  ##
23
23
  # Default rendering options used in the #render-method
24
24
  #
25
- DEFAULT_RENDERING_OPTIONS = { :strict_format => false, :raise_exceptions => true }
25
+ DEFAULT_RENDERING_OPTIONS = { :strict_format => false, :raise_exceptions => true } unless defined?(DEFAULT_RENDERING_OPTIONS)
26
26
 
27
27
  ##
28
28
  # Main class that register this extension
@@ -73,7 +73,7 @@ module Padrino
73
73
  end
74
74
 
75
75
  ##
76
- # Retunrs the cached layout path.
76
+ # Returns the cached layout path.
77
77
  #
78
78
  def fetch_layout_path(given_layout=nil)
79
79
  layout_name = given_layout || @layout || :application
@@ -110,18 +110,25 @@ module Padrino
110
110
  # If engine is a hash then render data converted to json
111
111
  return engine.to_json if engine.is_a?(Hash)
112
112
 
113
- # If engine is nil, ignore engine parameter
114
- engine, data = data, options if engine.nil? && data
113
+ # If engine is nil, ignore engine parameter and shift up all arguments
114
+ # render nil, "index", { :layout => true }, { :localvar => "foo" }
115
+ engine, data, options = data, options, locals if engine.nil? && data
115
116
 
116
- # Data can actually be a hash of options in certain render cases
117
- options.merge!(data) && data = nil if data.is_a?(Hash)
117
+ # Data is a hash of options when no engine isn't explicit
118
+ # render "index", { :layout => true }, { :localvar => "foo" }
119
+ # Data is options, and options is locals in this case
120
+ data, options, locals = nil, data, options if data.is_a?(Hash)
118
121
 
119
- # If an engine is a string then this is a likely a path to be resolved
122
+ # If data is unassigned then this is a likely a template to be resolved
123
+ # This means that no engine was explicitly defined
120
124
  data, engine = *resolve_template(engine, options) if data.nil?
121
125
 
122
126
  # Setup root
123
127
  root = settings.respond_to?(:root) ? settings.root : ""
124
128
 
129
+ # Use @layout if it exists
130
+ options[:layout] = @layout if options[:layout].nil?
131
+
125
132
  # Resolve layouts similar to in Rails
126
133
  if (options[:layout].nil? || options[:layout] == true) && !settings.templates.has_key?(:layout)
127
134
  layout_path, layout_engine = *resolved_layout
@@ -130,7 +137,7 @@ module Padrino
130
137
  options[:layout_engine] = layout_engine || engine if options[:layout]
131
138
  logger.debug "Resolving layout #{root}/views#{options[:layout]}" if defined?(logger) && options[:layout].present?
132
139
  elsif options[:layout].present?
133
- options[:layout] = settings.fetch_layout_path(options[:layout])
140
+ options[:layout] = settings.fetch_layout_path(options[:layout] || @layout)
134
141
  logger.debug "Resolving layout #{root}/views#{options[:layout]}" if defined?(logger)
135
142
  end
136
143
 
@@ -1,3 +1,5 @@
1
+ $:.unshift '/Users/joshbuddy/Development/http_router/lib'
2
+
1
3
  require 'http_router' unless defined?(HttpRouter)
2
4
  require 'padrino-core/support_lite' unless defined?(SupportLite)
3
5
 
@@ -18,21 +20,6 @@ class HttpRouter #:nodoc:
18
20
  def add_before_filter(filter)
19
21
  @before_filters ||= []
20
22
  @before_filters << filter
21
- arbitrary { |req, params|
22
- if req.testing_405?
23
- true
24
- else
25
- old_params = router.runner.params
26
- result = catch(:pass) {
27
- router.runner.params ||= {}
28
- router.runner.params.merge!(params)
29
- router.runner.instance_eval(&filter)
30
- true
31
- } == true
32
- router.runner.params = old_params
33
- result
34
- end
35
- }
36
23
  end
37
24
 
38
25
  def add_after_filter(filter)
@@ -64,7 +51,7 @@ module Padrino
64
51
  # to the url throughout the application.
65
52
  #
66
53
  module Routing
67
- CONTENT_TYPE_ALIASES = { :htm => :html }
54
+ CONTENT_TYPE_ALIASES = { :htm => :html } unless defined?(CONTENT_TYPE_ALIASES)
68
55
 
69
56
  class UnrecognizedException < RuntimeError #:nodoc:
70
57
  end
@@ -357,6 +344,7 @@ module Padrino
357
344
  # Sinatra defaults
358
345
  define_method "#{verb} #{path}", &block
359
346
  unbound_method = instance_method("#{verb} #{path}")
347
+
360
348
  block =
361
349
  if block.arity != 0
362
350
  block_arity = block.arity
@@ -367,6 +355,7 @@ module Padrino
367
355
  else
368
356
  proc { unbound_method.bind(self).call }
369
357
  end
358
+
370
359
  invoke_hook(:route_added, verb, path, block)
371
360
 
372
361
  # HTTPRouter route construction
@@ -414,44 +403,6 @@ module Padrino
414
403
  route.after_filters = @filters[:after] || []
415
404
  end
416
405
 
417
- route.arbitrary_with_continue do |req, params|
418
- if req.testing_405?
419
- req.continue[true]
420
- else
421
- base = self
422
- processed = false
423
- router.runner.instance_eval do
424
- request.route_obj = route
425
- @_response_buffer = nil
426
- if path.is_a?(Regexp)
427
- params_list = req.extra_env['router.regex_match'].to_a
428
- params_list.shift
429
- @block_params = params_list
430
- @params.update({:captures => params_list}.merge(@params || {}))
431
- else
432
- @block_params = req.params
433
- @params.update(params.merge(@params || {}))
434
- end
435
- pass_block = catch(:pass) do
436
- # If present set current controller layout
437
- parent_layout = base.instance_variable_get(:@layout)
438
- base.instance_variable_set(:@layout, route.use_layout) if route.use_layout
439
- # Provide access to the current controller to the request
440
- # Now we can eval route, but because we have "throw halt" we need to be
441
- # (en)sure to reset old layout and run controller after filters.
442
- begin
443
- @route = route
444
- @_response_buffer = catch(:halt) { route_eval(&block) }
445
- processed = true
446
- ensure
447
- base.instance_variable_set(:@layout, parent_layout) if route.use_layout
448
- (@_pending_after_filters ||= []).concat(route.after_filters) if route.after_filters
449
- end
450
- end
451
- end
452
- req.continue[processed]
453
- end
454
- end
455
406
  route.to(block)
456
407
  route
457
408
  end
@@ -603,7 +554,7 @@ module Padrino
603
554
 
604
555
  # per rfc2616-sec14:
605
556
  # Assume */* if no ACCEPT header is given.
606
- accepts.delete "*/*"
557
+ catch_all = (accepts.delete "*/*" || accepts.empty?)
607
558
  if accepts.empty?
608
559
  matching_types = mime_types.slice(0,1)
609
560
  else
@@ -615,6 +566,9 @@ module Padrino
615
566
  elsif !url_format && matching_types.first
616
567
  type = ::Rack::Mime::MIME_TYPES.find { |k, v| v == matching_types.first }[0].sub(/\./,'').to_sym
617
568
  accept_format = CONTENT_TYPE_ALIASES[type] || type
569
+ elsif catch_all
570
+ type = types.first
571
+ accept_format = CONTENT_TYPE_ALIASES[type] || type
618
572
  end
619
573
 
620
574
  matched_format = types.include?(:any) ||
@@ -719,9 +673,39 @@ module Padrino
719
673
  #
720
674
  def route!(base=self.class, pass_block=nil)
721
675
  base.router.runner = self
722
- if base.router and match = base.router.recognize(@request.env)
676
+ if base.router and match = base.router.recognize(@request.env) { |match|
677
+ request.route_obj = match.path.route
678
+ @_response_buffer = nil
679
+ if match.path.route.is_a?(HttpRouter::RegexRoute)
680
+ params_list = match.request.extra_env['router.regex_match'].to_a
681
+ params_list.shift
682
+ @block_params = params_list
683
+ @params.update({:captures => params_list}.merge(@params || {}))
684
+ else
685
+ @block_params = match.param_values
686
+ @params.update(match.params.merge(@params || {}))
687
+ end
688
+ parent_layout = @layout
689
+ @params ||= {}
690
+ @layout = match.path.route.use_layout if match.path.route.use_layout
691
+ # Provide access to the current controller to the request
692
+ # Now we can eval route, but because we have "throw halt" we need to be
693
+ # (en)sure to reset old layout and run controller after filters.
694
+ begin
695
+ old_params = @params
696
+ match.path.route.before_filters.each { |filter| instance_eval(&filter) } if match.path.route.before_filters
697
+ # If present set current controller layout
698
+ @route = match.path.route
699
+ @block_params = @block_params.slice(0, match.path.route.dest.arity) if match.path.route.dest.arity > 0
700
+ match.acceptance_response = catch(:halt) { route_eval(&match.path.route.dest) } || ''
701
+ ensure
702
+ @layout = parent_layout
703
+ (@_pending_after_filters ||= []).concat(match.path.route.after_filters) if match.path.route.after_filters
704
+ @params = old_params
705
+ end
706
+ }
723
707
  if match.respond_to?(:path)
724
- throw :halt, @_response_buffer
708
+ throw :halt, @_response_buffer = match.acceptance_response
725
709
  elsif match.respond_to?(:each)
726
710
  route_eval do
727
711
  match[1].each {|k,v| response[k] = v}
@@ -4,41 +4,18 @@ module Padrino
4
4
  class << self
5
5
  # Start for the given options a rackup handler
6
6
  def start(options)
7
- if options.daemonize?
8
- stop # Need to stop a process if it exists
9
- fork do
10
- Process.setsid
11
- exit if fork
12
- File.umask 0000
13
- puts "=> Padrino server has been daemonized with pid #{Process.pid}"
14
- STDIN.reopen "/dev/null"
15
- STDOUT.reopen "/dev/null", "a"
16
- STDERR.reopen STDOUT
17
-
18
- FileUtils.mkdir_p("tmp/pids") unless File.exist?("tmp/pids")
19
- pid = "tmp/pids/server.pid"
20
-
21
- if pid
22
- File.open(pid, 'w'){ |f| f.write("#{Process.pid}") }
23
- end
24
-
25
- Padrino.run!(options.symbolize_keys)
26
- exit
27
- end
28
- else
29
- Padrino.run!(options.symbolize_keys)
30
- end
7
+ Padrino.run!(options.symbolize_keys)
31
8
  end
32
9
 
33
10
  # Method that stop (if exist) a running Padrino.application
34
- def stop
35
- if File.exist?("tmp/pids/server.pid")
36
- pid = File.read("tmp/pids/server.pid").to_i
37
- print "=> Sending SIGTERM to process with pid #{pid} wait "
38
- Process.kill(15, pid) rescue nil
39
- 1.step(5) { |i| sleep i; print "."; $stdout.flush }
40
- File.delete("tmp/pids/server.pid")
41
- puts " done."
11
+ def stop(options)
12
+ options.symbolize_keys!
13
+ if File.exist?(options[:pid])
14
+ pid = File.read(options[:pid]).to_i
15
+ print "=> Sending INT to process with pid #{pid} wait "
16
+ Process.kill(2, pid) rescue nil
17
+ else
18
+ puts "=> #{options[:pid]} not found!"
42
19
  end
43
20
  end
44
21
  end # self
@@ -5,32 +5,31 @@ module Padrino
5
5
 
6
6
  class Base < Thor
7
7
  include Thor::Actions
8
- include Thor::RakeCompat
9
8
 
10
9
  class_option :chdir, :type => :string, :aliases => "-c", :desc => "Change to dir before starting"
11
10
  class_option :environment, :type => :string, :aliases => "-e", :required => true, :default => :development, :desc => "Padrino Environment"
12
11
  class_option :help, :type => :boolean, :desc => "Show help usage"
13
12
 
14
13
  desc "start", "Starts the Padrino application"
15
- method_option :adapter, :type => :string, :aliases => "-a", :desc => "Rack Handler (default: autodetect)"
16
- method_option :host, :type => :string, :aliases => "-h", :required => true, :default => "localhost", :desc => "Bind to HOST address"
14
+ method_option :server, :type => :string, :aliases => "-a", :desc => "Rack Handler (default: autodetect)"
15
+ method_option :host, :type => :string, :aliases => "-h", :required => true, :default => "0.0.0.0", :desc => "Bind to HOST address"
17
16
  method_option :port, :type => :numeric, :aliases => "-p", :required => true, :default => 3000, :desc => "Use PORT"
18
17
  method_option :daemonize, :type => :boolean, :aliases => "-d", :desc => "Run daemonized in the background"
18
+ method_option :pid, :type => :string, :aliases => "-p", :desc => "File to store pid"
19
+ method_option :debug, :type => :boolean, :desc => "Set debugging flags"
19
20
  def start
20
21
  prepare :start
21
- require File.expand_path(File.dirname(__FILE__) + "/adapter")
22
+ require File.expand_path("../adapter", __FILE__)
22
23
  require File.expand_path('config/boot.rb')
23
24
  Padrino::Cli::Adapter.start(options)
24
25
  end
25
26
 
26
- desc "s", "Starts the Padrino application"
27
- alias :s :start
28
-
29
27
  desc "stop", "Stops the Padrino application"
28
+ method_option :pid, :type => :string, :aliases => "-p", :desc => "File to store pid", :default => 'tmp/pids/server.pid'
30
29
  def stop
31
30
  prepare :stop
32
- require File.expand_path(File.dirname(__FILE__) + "/adapter")
33
- Padrino::Cli::Adapter.stop
31
+ require File.expand_path("../adapter", __FILE__)
32
+ Padrino::Cli::Adapter.stop(options)
34
33
  end
35
34
 
36
35
  desc "rake", "Execute rake tasks"
@@ -48,21 +47,21 @@ module Padrino
48
47
  ARGV.concat(args)
49
48
  puts "=> Executing Rake #{ARGV.join(' ')} ..."
50
49
  ENV['PADRINO_LOG_LEVEL'] ||= "test"
51
- require File.expand_path(File.dirname(__FILE__) + '/rake')
50
+ load File.expand_path('../rake.rb', __FILE__)
52
51
  silence(:stdout) { require File.expand_path('config/boot.rb') }
53
- PadrinoTasks.init
52
+ PadrinoTasks.init(true)
54
53
  end
55
54
 
56
55
  desc "console", "Boots up the Padrino application irb console"
57
56
  def console
58
57
  prepare :console
59
- require File.expand_path(File.dirname(__FILE__) + "/../version")
58
+ require File.expand_path("../../version", __FILE__)
60
59
  ARGV.clear
61
60
  puts "=> Loading #{options.environment} console (Padrino v.#{Padrino.version})"
62
61
  require 'irb'
63
62
  require "irb/completion"
64
63
  require File.expand_path('config/boot.rb')
65
- require File.expand_path(File.dirname(__FILE__) + '/console')
64
+ require File.expand_path('../console', __FILE__)
66
65
  IRB.start
67
66
  end
68
67
 
@@ -139,4 +138,4 @@ module Padrino
139
138
  alias :silence :capture
140
139
  end # Base
141
140
  end # Cli
142
- end # Padrino
141
+ end # Padrino