Class: Gin::App
- Inherits:
-
Object
- Object
- Gin::App
- Extended by:
- GinClass
- Includes:
- Constants
- Defined in:
- lib/gin/app.rb,
lib/gin/test.rb
Overview
:nodoc:
Defined Under Namespace
Classes: RouterError
Constant Summary collapse
- CALLERS_TO_IGNORE =
:nodoc:
[ # :nodoc: /lib\/gin(\/(.*?))?\.rb/, # all gin code /lib\/tilt.*\.rb/, # all tilt code /^\(.*\)$/, # generated code /rubygems\/custom_require\.rb/, # rubygems require hacks /active_support/, # active_support require hacks /bundler(\/runtime)?\.rb/, # bundler require hacks /<internal:/, # internal in ruby >= 1.9.2 /src\/kernel\/bootstrap\/[A-Z]/ # maglev kernel files ]
- MD5 =
:nodoc:
RUBY_PLATFORM =~ /darwin/ ? 'md5 -q' : 'md5sum'
- STATIC_PATH_CLEANER =
:nodoc:
%r{\.+/|/\.+}
Constants included from Constants
Constants::ASYNC_CALLBACK, Constants::CACHE_CTRL, Constants::CNT_DISPOSITION, Constants::CNT_LENGTH, Constants::CNT_TYPE, Constants::ENV_DEV, Constants::ENV_PROD, Constants::ENV_STAGE, Constants::ENV_TEST, Constants::EPOCH, Constants::ETAG, Constants::EXPIRES, Constants::FWD_FOR, Constants::FWD_HOST, Constants::GIN_ACTION, Constants::GIN_CTRL, Constants::GIN_ERRORS, Constants::GIN_PATH_PARAMS, Constants::GIN_RELOADED, Constants::GIN_ROUTE, Constants::GIN_STACK, Constants::GIN_STATIC, Constants::GIN_TEMPLATES, Constants::GIN_TIMESTAMP, Constants::HTTP_VERSION, Constants::IF_MATCH, Constants::IF_MOD_SINCE, Constants::IF_NONE_MATCH, Constants::IF_UNMOD_SINCE, Constants::LAST_MOD, Constants::LOCATION, Constants::PATH_INFO, Constants::PRAGMA, Constants::QUERY_STRING, Constants::REMOTE_ADDR, Constants::REMOTE_USER, Constants::REQ_METHOD, Constants::SESSION_SECRET
Instance Attribute Summary collapse
-
#options ⇒ Object
readonly
Options applied to the Gin::App instance.
-
#rack_app ⇒ Object
readonly
App to fallback on if Gin::App is used as middleware and no route is found.
-
#stack ⇒ Object
readonly
Internal Rack stack.
Class Method Summary collapse
-
.asset_host(host = nil, &block) ⇒ Object
Get or set the CDN asset host (and path).
-
.autoreload(val = nil) ⇒ Object
Enable or disable auto-app reloading.
-
.call(env) ⇒ Object
Create a new instance of the app and call it.
-
.config ⇒ Object
Access the config for your application, loaded from the config_dir.
-
.config_dir(dir = nil) ⇒ Object
Get or set the path to the config directory.
-
.config_reload(ttl = nil) ⇒ Object
Get or set the config max age for auto-reloading in seconds.
-
.default_template(klass, *extensions) ⇒ Object
Set the default templating engine to use for various file extensions, or by default: # Default for .markdown and .md files default_template Tilt::MarukuTemplate, ‘markdown’, ‘md’.
- .define_test_helper ⇒ Object
-
.environment(env = nil) ⇒ Object
Get or set the current environment name, by default ENV [‘RACK_ENV’], or “development”.
-
.error_delegate(ctrl = nil) ⇒ Object
Define a Gin::Controller as a catch-all error rendering controller.
-
.inherited(subclass) ⇒ Object
:nodoc:.
-
.layout(name = nil) ⇒ Object
Get or set the layout name.
-
.layouts_dir(dir = nil) ⇒ Object
Get or set the directory for view layouts.
-
.logger(new_logger = nil) ⇒ Object
Get or set the logger for your application.
-
.make_config(opts = {}) ⇒ Object
:nodoc:.
-
.md5s ⇒ Object
Cache of file md5s shared across all instances of an App class.
-
.middleware ⇒ Object
List of internal app middleware.
-
.mime_type(type, value = nil) ⇒ Object
Lookup or register a mime type in Rack’s mime registry.
-
.mime_types(type) ⇒ Object
Provides all mime types matching type, including deprecated types: mime_types :html # => [‘text/html’] mime_types :js # => [‘application/javascript’, ‘text/javascript’].
-
.mount(ctrl, base_path = nil, &block) ⇒ Object
Mount a Gin::Controller into the App and specify a base path.
-
.namespace ⇒ Object
:nodoc:.
-
.old_inherited ⇒ Object
:nodoc:.
-
.options ⇒ Object
Hash of the full Gin::App configuration.
-
.protection(opts = nil) ⇒ Object
Use rack-protection or not.
-
.public_dir(dir = nil) ⇒ Object
Get or set the path to the public directory.
-
.reload_mutex ⇒ Object
:nodoc:.
-
.require(file) ⇒ Object
Custom require used for auto-reloading.
-
.root_dir(dir = nil) ⇒ Object
Get or set the root directory of the application.
-
.router ⇒ Object
Router instance that handles mapping Rack-env -> Controller#action.
-
.session_secret(val = nil) ⇒ Object
Get or set the session secret String.
-
.sessions(opts = nil) ⇒ Object
Use rack sessions or not.
-
.setup ⇒ Object
:nodoc:.
-
.source_class ⇒ Object
:nodoc:.
-
.source_file ⇒ Object
Returns the source file of the current app.
-
.templates ⇒ Object
Cache of precompiled templates, shared across all instances of a given App class.
-
.use(middleware, *args, &block) ⇒ Object
Add middleware internally to the app.
-
.views_dir(dir = nil) ⇒ Object
Get or set the path to the views directory.
Instance Method Summary collapse
-
#asset(path) ⇒ Object
Check if an asset exists.
-
#asset_host ⇒ Object
Returns the default asset host.
-
#asset_host_for(asset_name) ⇒ Object
Returns the asset host for a given asset name.
-
#asset_version(path) ⇒ Object
Returns the first 8 bytes of the asset file’s md5.
-
#call(env) ⇒ Object
Default Rack call method.
-
#call!(env) ⇒ Object
Call App instance stack without static file lookup or reloading.
-
#call_static(env) ⇒ Object
Returns a static file Rack response Array from the filename set in env.
-
#config ⇒ Object
Access the config for your application, loaded from the config_dir.
-
#development? ⇒ Boolean
Check if running in development mode.
-
#dispatch(env, ctrl, action) ⇒ Object
Dispatch the Rack env to the given controller and action.
-
#handle_error(err, env) ⇒ Object
Handle error with error_delegate if available, otherwise re-raise.
-
#initialize(rack_app = nil, options = {}) ⇒ App
constructor
Create a new Rack-mountable Gin::App instance, with an optional rack_app and options.
-
#md5(path) ⇒ Object
Returns the first 8 characters of a file’s MD5 hash.
-
#production? ⇒ Boolean
Check if running in production mode.
-
#reload! ⇒ Object
Used for auto reloading the whole app in development mode.
-
#route!(env) ⇒ Object
Check if the request routes to a controller and action and set gin.controller, gin.action, gin.path_query_hash, and gin.http_route env variables.
-
#staging? ⇒ Boolean
Check if running in staging mode.
-
#static!(env) ⇒ Object
Check if the request is for a static file and set the gin.static env variable to the filepath.
-
#template_files(path) ⇒ Object
Returns an Array of file paths that match a valid path and maps to a known template engine.
-
#template_for(path, engine = nil) ⇒ Object
Returns the tilt template for the given template name.
-
#test? ⇒ Boolean
Check if running in test mode.
-
#try_autoreload(env) ⇒ Object
Check if autoreload is needed and reload.
Constructor Details
#initialize(rack_app = nil, options = {}) ⇒ App
Create a new Rack-mountable Gin::App instance, with an optional rack_app and options.
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 |
# File 'lib/gin/app.rb', line 513 def initialize rack_app=nil, ={} if Hash === rack_app = rack_app @rack_app = nil else @rack_app = rack_app end = { config_dir: self.class.config_dir, public_dir: self.class.public_dir, layouts_dir: self.class.layouts_dir, views_dir: self.class.views_dir, config: self.class.config }.merge(self.class.).merge() [:config] = self.class.make_config() if [:environment] != [:config].environment || [:config_dir] != [:config].dir || [:config_reload] != [:config].ttl validate_all_controllers! @app = self @stack = build_app Rack::Builder.new end |
Instance Attribute Details
#options ⇒ Object (readonly)
Options applied to the Gin::App instance. Typically a result of class-level configuration methods, such as Gin::App.environment.
504 505 506 |
# File 'lib/gin/app.rb', line 504 def end |
#rack_app ⇒ Object (readonly)
App to fallback on if Gin::App is used as middleware and no route is found.
500 501 502 |
# File 'lib/gin/app.rb', line 500 def rack_app @rack_app end |
#stack ⇒ Object (readonly)
Internal Rack stack.
507 508 509 |
# File 'lib/gin/app.rb', line 507 def stack @stack end |
Class Method Details
.asset_host(host = nil, &block) ⇒ Object
Get or set the CDN asset host (and path). If block is given, evaluates the block on every read.
195 196 197 198 199 |
# File 'lib/gin/app.rb', line 195 def self.asset_host host=nil, &block [:asset_host] = host if host [:asset_host] = block if block_given? [:asset_host] end |
.autoreload(val = nil) ⇒ Object
Enable or disable auto-app reloading. On by default in development mode.
In order for an app to be reloadable, the libs and controllers must be required from the Gin::App class context, or use MyApp.require(“lib”).
Gin::App class reloading is not supported for applications defined in the config.ru file. Dependencies will, however, still be reloaded.
Autoreload must be enabled before any calls to Gin::App.require for those files to be reloaded.
class MyApp < Gin::App
# Only reloaded in development mode
require 'nokogiri'
autoreload false
# Never reloaded
require 'static_thing'
autoreload true
# Reloaded every request
require 'my_app/home_controller'
end
131 132 133 134 135 136 137 138 139 140 141 |
# File 'lib/gin/app.rb', line 131 def self.autoreload val=nil @autoreload = val unless val.nil? reload = @autoreload.nil? ? self.environment == ENV_DEV : @autoreload if reload Object.send :require, 'gin/reloadable' unless defined?(Gin::Reloadable) include Gin::Reloadable unless self < Gin::Reloadable end reload end |
.call(env) ⇒ Object
Create a new instance of the app and call it.
69 70 71 72 |
# File 'lib/gin/app.rb', line 69 def self.call env @instance ||= self.new @instance.call env end |
.config ⇒ Object
Access the config for your application, loaded from the config_dir.
# config/memcache.yml
default: &default
host: example.com
connections: 1
development: *default
host: localhost
# access from App class
CACHE = Memcache.new( MyApp.config['memcache.host'] )
The config object is shared across all instances of the App and has thread-safety built-in.
225 226 227 |
# File 'lib/gin/app.rb', line 225 def self.config [:config] ||= make_config end |
.config_dir(dir = nil) ⇒ Object
Get or set the path to the config directory. Defaults to “<root_dir>/config”
Configs are expected to be YAML files following this pattern:
default: &default
key: value
development: *default
other_key: value
production: *default
...
Configs will be named according to the filename, and only the config for the current environment will be accessible.
247 248 249 250 251 252 253 254 |
# File 'lib/gin/app.rb', line 247 def self.config_dir dir=nil if String === dir [:config_dir] = dir [:config].dir = dir if [:config] end [:config_dir] || File.join(self.root_dir, "config") end |
.config_reload(ttl = nil) ⇒ Object
Get or set the config max age for auto-reloading in seconds. Turns config reloading off if set to false. Defaults to false. Config only gets reloaded on demand.
# Set to 10 minutes
config_reload 600
# Set to never reload
config_reload false
268 269 270 271 272 273 274 |
# File 'lib/gin/app.rb', line 268 def self.config_reload ttl=nil unless ttl.nil? [:config_reload] = ttl [:config].ttl = ttl if [:config] end [:config_reload] end |
.default_template(klass, *extensions) ⇒ Object
Set the default templating engine to use for various file extensions, or by default:
# Default for .markdown and .md files
default_template Tilt::MarukuTemplate, 'markdown', 'md'
# Default for files without preset default
default_template Tilt::BlueClothTemplate
286 287 288 289 290 |
# File 'lib/gin/app.rb', line 286 def self.default_template klass, *extensions extensions = [nil] if extensions.empty? extensions.each{|ext| ([:template_engines][ext] ||= []).unshift klass } end |
.define_test_helper ⇒ Object
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 |
# File 'lib/gin/test.rb', line 678 def self.define_test_helper return const_get(:TestHelper) if const_defined?(:TestHelper) class_eval " module TestHelper\n include Gin::Test::Helpers\n\n def self.included subclass\n Gin::Test::Helpers.setup_klass(subclass)\n subclass.app_klass \#{self}\n end\n end\n STR\n\n const_get :TestHelper\nend\n" |
.environment(env = nil) ⇒ Object
Get or set the current environment name, by default ENV [‘RACK_ENV’], or “development”.
297 298 299 300 301 302 303 |
# File 'lib/gin/app.rb', line 297 def self.environment env=nil if env [:environment] = env [:config].environment = env if [:config] end [:environment] end |
.error_delegate(ctrl = nil) ⇒ Object
Define a Gin::Controller as a catch-all error rendering controller. This can be a dedicated controller, or a parent controller such as AppController. Defaults to Gin::Controller.
The error delegate should handle the following errors for creating custom pages for Gin errors:
Gin::NotFound, Gin::BadRequest, ::Exception
315 316 317 318 |
# File 'lib/gin/app.rb', line 315 def self.error_delegate ctrl=nil [:error_delegate] = ctrl if ctrl [:error_delegate] end |
.inherited(subclass) ⇒ Object
:nodoc:
32 33 34 |
# File 'lib/gin/app.rb', line 32 def self.inherited subclass #:nodoc: subclass.setup end |
.layout(name = nil) ⇒ Object
Get or set the layout name. Layout file location is assumed to be in the views_dir. If the views dir has a controller wildcard ‘*’, the layout is assumed to be one level above the controller-specific directory.
Defaults to :layout.
328 329 330 331 |
# File 'lib/gin/app.rb', line 328 def self.layout name=nil [:layout] = name if name [:layout] end |
.layouts_dir(dir = nil) ⇒ Object
Get or set the directory for view layouts. Defaults to the “<root_dir>/layouts”.
338 339 340 341 |
# File 'lib/gin/app.rb', line 338 def self.layouts_dir dir=nil [:layouts_dir] = dir if dir [:layouts_dir] || File.join(root_dir, 'layouts') end |
.logger(new_logger = nil) ⇒ Object
Get or set the logger for your application. Loggers must respond to the << method.
348 349 350 351 352 353 354 |
# File 'lib/gin/app.rb', line 348 def self.logger new_logger=nil if new_logger [:logger] = new_logger [:config].logger = new_logger if [:config] end [:logger] end |
.make_config(opts = {}) ⇒ Object
:nodoc:
202 203 204 205 206 207 |
# File 'lib/gin/app.rb', line 202 def self.make_config opts={} # :nodoc: Gin::Config.new opts[:environment] || self.environment, dir: opts[:config_dir] || self.config_dir, logger: opts[:logger] || self.logger, ttl: opts[:config_reload] || self.config_reload end |
.md5s ⇒ Object
Cache of file md5s shared across all instances of an App class. Used for static asset versioning.
361 362 363 |
# File 'lib/gin/app.rb', line 361 def self.md5s @md5s end |
.middleware ⇒ Object
List of internal app middleware.
369 370 371 |
# File 'lib/gin/app.rb', line 369 def self.middleware [:middleware] end |
.mime_type(type, value = nil) ⇒ Object
Lookup or register a mime type in Rack’s mime registry.
377 378 379 380 381 382 |
# File 'lib/gin/app.rb', line 377 def self.mime_type type, value=nil return type if type.nil? || type.to_s.include?('/') type = ".#{type}" unless type.to_s[0] == ?. return Rack::Mime.mime_type(type, nil) unless value Rack::Mime::MIME_TYPES[type] = value end |
.mime_types(type) ⇒ Object
Provides all mime types matching type, including deprecated types:
mime_types :html # => ['text/html']
mime_types :js # => ['application/javascript', 'text/javascript']
390 391 392 393 |
# File 'lib/gin/app.rb', line 390 def self.mime_types type type = mime_type type type =~ /^application\/(xml|javascript)$/ ? [type, "text/#$1"] : [type] end |
.mount(ctrl, base_path = nil, &block) ⇒ Object
Mount a Gin::Controller into the App and specify a base path. If controller mounts at root, use “/” as the base path.
mount UserController, "/user" do
get :index, "/"
get :show, "/:id"
post :create, "/"
get :stats # mounts to "/stats" by default
any :logged_in # any HTTP verb will trigger this action
end
Controllers with non-mounted actions will throw a warning at boot time.
Restful routes are automatically mounted when no block is given:
mount UserController
# restfully mounted to /user
# non-canonical actions are mounted to /user/<action_name>
Mount blocks also support routing whatever actions are left to their restful defaults:
mount UserController do
get :foo, "/"
defaults
end
All Gin::Controller methods are considered actions and will be mounted in restful mode. For helper methods, include a module into your controller.
186 187 188 |
# File 'lib/gin/app.rb', line 186 def self.mount ctrl, base_path=nil, &block router.add ctrl, base_path, &block end |
.namespace ⇒ Object
:nodoc:
92 93 94 95 |
# File 'lib/gin/app.rb', line 92 def self.namespace #:nodoc: # Parent namespace of the App class. Used for reloading purposes. Gin.const_find(@source_class.split("::")[0..-2]) if @source_class end |
.old_inherited ⇒ Object
:nodoc:
669 670 671 |
# File 'lib/gin/test.rb', line 669 def self.inherited subclass #:nodoc: subclass.setup end |
.options ⇒ Object
Hash of the full Gin::App configuration. Result of using class-level setter methods such as Gin::App.environment.
79 80 81 |
# File 'lib/gin/app.rb', line 79 def self. end |
.protection(opts = nil) ⇒ Object
Use rack-protection or not. Supports assigning hash for options. Defaults to false.
400 401 402 403 |
# File 'lib/gin/app.rb', line 400 def self.protection opts=nil [:protection] = opts unless opts.nil? [:protection] end |
.public_dir(dir = nil) ⇒ Object
Get or set the path to the public directory. Defaults to “<root_dir>/public”
410 411 412 413 |
# File 'lib/gin/app.rb', line 410 def self.public_dir dir=nil [:public_dir] = dir if dir [:public_dir] || File.join(root_dir, "public") end |
.reload_mutex ⇒ Object
:nodoc:
416 417 418 |
# File 'lib/gin/app.rb', line 416 def self.reload_mutex # :nodoc: @reload_mutex end |
.require(file) ⇒ Object
Custom require used for auto-reloading.
147 148 149 150 151 152 153 |
# File 'lib/gin/app.rb', line 147 def self.require file if autoreload track_require file else super file end end |
.root_dir(dir = nil) ⇒ Object
Get or set the root directory of the application. Defaults to the app file’s directory.
425 426 427 428 |
# File 'lib/gin/app.rb', line 425 def self.root_dir dir=nil [:root_dir] = File.(dir) if dir [:root_dir] end |
.router ⇒ Object
Router instance that handles mapping Rack-env -> Controller#action.
434 435 436 |
# File 'lib/gin/app.rb', line 434 def self.router [:router] end |
.session_secret(val = nil) ⇒ Object
Get or set the session secret String. Defaults to a new random value on boot.
453 454 455 456 |
# File 'lib/gin/app.rb', line 453 def self.session_secret val=nil [:session_secret] = val if val [:session_secret] end |
.sessions(opts = nil) ⇒ Object
Use rack sessions or not. Supports assigning hash for options. Defaults to false.
443 444 445 446 |
# File 'lib/gin/app.rb', line 443 def self.sessions opts=nil [:sessions] = opts unless opts.nil? [:sessions] end |
.setup ⇒ Object
:nodoc:
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/gin/app.rb', line 37 def self.setup # :nodoc: caller_line = caller.find{|line| !CALLERS_TO_IGNORE.any?{|m| line =~ m} } filepath = File.(caller_line.split(/:\d+:in `/).first) dir = File.dirname(filepath) @source_file = filepath @source_class = self.to_s @templates = Gin::Cache.new @md5s = Gin::Cache.new @reload_mutex = Mutex.new @autoreload = nil @instance = nil = {} [:root_dir] = dir [:environment] = ENV['RACK_ENV'] || ENV_DEV [:error_delegate] = Gin::Controller [:middleware] = [] [:logger] = Logger.new($stdout) [:router] = Gin::Router.new [:session_secret] = SESSION_SECRET [:protection] = false [:sessions] = false [:config_reload] = false [:layout] = :layout [:template_engines] = Tilt.mappings.merge(nil => [Tilt::ERBTemplate]) end |
.source_class ⇒ Object
:nodoc:
98 99 100 101 |
# File 'lib/gin/app.rb', line 98 def self.source_class #:nodoc: # Lookup the class from its name. Used for reloading purposes. Gin.const_find(@source_class) if @source_class end |
.source_file ⇒ Object
Returns the source file of the current app.
87 88 89 |
# File 'lib/gin/app.rb', line 87 def self.source_file @source_file end |
.templates ⇒ Object
Cache of precompiled templates, shared across all instances of a given App class.
463 464 465 |
# File 'lib/gin/app.rb', line 463 def self.templates @templates end |
.use(middleware, *args, &block) ⇒ Object
Add middleware internally to the app. Middleware statuses and Exceptions will NOT be handled by the error_delegate.
473 474 475 476 477 |
# File 'lib/gin/app.rb', line 473 def self.use middleware, *args, &block ary = [middleware, *args] ary << block if block_given? self.middleware << ary end |
.views_dir(dir = nil) ⇒ Object
Get or set the path to the views directory. The wildcard ‘*’ will be replaced by the controller name.
Defaults to “<root_dir>/views”
486 487 488 489 |
# File 'lib/gin/app.rb', line 486 def self.views_dir dir=nil [:views_dir] = dir if dir [:views_dir] || File.join(root_dir, 'views') end |
Instance Method Details
#asset(path) ⇒ Object
Check if an asset exists. Returns the full path to the asset if found, otherwise nil. Does not support ./ or ../ for security reasons.
791 792 793 794 795 796 797 798 799 |
# File 'lib/gin/app.rb', line 791 def asset path path = path.gsub STATIC_PATH_CLEANER, "" filepath = File.(File.join(public_dir, path)) return filepath if File.file? filepath filepath = File.(File.join(Gin::PUBLIC_DIR, path)) return filepath if File.file? filepath end |
#asset_host ⇒ Object
Returns the default asset host.
606 607 608 |
# File 'lib/gin/app.rb', line 606 def asset_host asset_host_for(nil) end |
#asset_host_for(asset_name) ⇒ Object
Returns the asset host for a given asset name. This is useful when assigning a block for the asset_host. The asset_name argument is passed to the block.
597 598 599 600 |
# File 'lib/gin/app.rb', line 597 def asset_host_for asset_name [:asset_host].respond_to?(:call) ? [:asset_host].call(asset_name) : [:asset_host] end |
#asset_version(path) ⇒ Object
Returns the first 8 bytes of the asset file’s md5. File path is assumed relative to the public_dir.
615 616 617 618 |
# File 'lib/gin/app.rb', line 615 def asset_version path path = File.(File.join(public_dir, path)) md5(path) end |
#call(env) ⇒ Object
Default Rack call method.
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 |
# File 'lib/gin/app.rb', line 694 def call env try_autoreload(env) if @app.route!(env) @app.call!(env) elsif @app.static!(env) @app.call_static(env) elsif @rack_app @rack_app.call(env) else @app.call!(env) end end |
#call!(env) ⇒ Object
Call App instance stack without static file lookup or reloading.
725 726 727 728 729 730 731 732 733 734 735 |
# File 'lib/gin/app.rb', line 725 def call! env if env[GIN_STACK] dispatch env, env[GIN_CTRL], env[GIN_ACTION] else env[GIN_STACK] = true with_log_request(env) do @stack.call env end end end |
#call_static(env) ⇒ Object
Returns a static file Rack response Array from the filename set in env.
742 743 744 745 746 |
# File 'lib/gin/app.rb', line 742 def call_static env with_log_request(env) do error_delegate.exec(self, env){ send_file env[GIN_STATIC] } end end |
#config ⇒ Object
Access the config for your application, loaded from the config_dir.
# config/memcache.yml
default: &default
host: example.com
connections: 1
development: *default
host: localhost
# access from App instance
@app.config['memcache.host']
The config object is shared across all instances of the App and has thread-safety built-in.
556 557 558 |
# File 'lib/gin/app.rb', line 556 def config [:config] end |
#development? ⇒ Boolean
Check if running in development mode.
564 565 566 |
# File 'lib/gin/app.rb', line 564 def development? self.environment == ENV_DEV end |
#dispatch(env, ctrl, action) ⇒ Object
Dispatch the Rack env to the given controller and action.
805 806 807 808 809 810 811 812 813 814 815 |
# File 'lib/gin/app.rb', line 805 def dispatch env, ctrl, action raise Gin::NotFound, "No route exists for: #{env[REQ_METHOD]} #{env[PATH_INFO]}" unless ctrl && action env[GIN_CTRL] = ctrl.new(self, env) env[GIN_CTRL].call_action action rescue ::Exception => err handle_error(err, env) end |
#handle_error(err, env) ⇒ Object
Handle error with error_delegate if available, otherwise re-raise.
821 822 823 824 825 826 827 828 829 830 831 |
# File 'lib/gin/app.rb', line 821 def handle_error err, env delegate = error_delegate begin delegate.exec(self, env){ handle_error(err) } rescue ::Exception => err delegate = Gin::Controller and retry unless delegate == Gin::Controller raise end end |
#md5(path) ⇒ Object
Returns the first 8 characters of a file’s MD5 hash. Values are cached for future reference.
627 628 629 630 |
# File 'lib/gin/app.rb', line 627 def md5 path return unless File.file?(path) self.md5s[path] ||= `#{MD5} #{path}`[0...8] end |
#production? ⇒ Boolean
Check if running in production mode.
588 589 590 |
# File 'lib/gin/app.rb', line 588 def production? self.environment == ENV_PROD end |
#reload! ⇒ Object
Used for auto reloading the whole app in development mode. Will only reload if Gin::App.autoreload is set to true.
If you use this in production, you’re gonna have a bad time.
675 676 677 678 679 680 681 682 683 684 685 686 687 688 |
# File 'lib/gin/app.rb', line 675 def reload! reload_mutex.synchronize do self.class.erase_dependencies! if File.extname(self.class.source_file) != ".ru" self.class.erase! [self.class.source_file], [self.class.name.split("::").last], self.class.namespace require self.class.source_file end @app = self.class.source_class.new @rack_app, end end |
#route!(env) ⇒ Object
Check if the request routes to a controller and action and set gin.controller, gin.action, gin.path_query_hash, and gin.http_route env variables. Returns true if a route is found, otherwise false.
771 772 773 774 775 776 777 778 779 780 781 |
# File 'lib/gin/app.rb', line 771 def route! env http_route = "#{env[REQ_METHOD]} #{env[PATH_INFO]}" return true if env[GIN_ROUTE] == http_route env[GIN_CTRL], env[GIN_ACTION], env[GIN_PATH_PARAMS] = router.resources_for env[REQ_METHOD], env[PATH_INFO] env[GIN_ROUTE] = http_route !!(env[GIN_CTRL] && env[GIN_ACTION]) end |
#staging? ⇒ Boolean
Check if running in staging mode.
580 581 582 |
# File 'lib/gin/app.rb', line 580 def staging? self.environment == ENV_STAGE end |
#static!(env) ⇒ Object
Check if the request is for a static file and set the gin.static env variable to the filepath. Returns true if request is to a static asset, otherwise false.
754 755 756 757 758 759 760 761 762 |
# File 'lib/gin/app.rb', line 754 def static! env filepath = %w{GET HEAD}.include?(env[REQ_METHOD]) && asset(env[PATH_INFO]) filepath ? (env[GIN_STATIC] = filepath) : env.delete(GIN_STATIC) !!env[GIN_STATIC] end |
#template_files(path) ⇒ Object
Returns an Array of file paths that match a valid path and maps to a known template engine.
app.template_files 'views/foo'
#=> ['views/foo.erb', 'views/foo.md']
663 664 665 666 |
# File 'lib/gin/app.rb', line 663 def template_files path exts = template_engines.keys.map{|e| "." << e if e }.join(",") Dir["#{path}{#{exts}}"] end |
#template_for(path, engine = nil) ⇒ Object
Returns the tilt template for the given template name. Returns nil if no template file is found.
template_for 'user/show'
#=> <Tilt::ERBTemplate @file="views/user/show.erb" ...>
template_for 'user/show.haml'
#=> <Tilt::HamlTemplate @file="views/user/show.haml" ...>
template_for 'non-existant'
#=> nil
645 646 647 648 649 650 651 652 653 654 |
# File 'lib/gin/app.rb', line 645 def template_for path, engine=nil templates.cache([path, engine]) do if file = template_files(path).first ext = File.extname(file) ext = ext.empty? ? nil : ext[1..-1] engine ||= template_engines[ext].first engine.new(file) if engine end end end |
#test? ⇒ Boolean
Check if running in test mode.
572 573 574 |
# File 'lib/gin/app.rb', line 572 def test? self.environment == ENV_TEST end |
#try_autoreload(env) ⇒ Object
Check if autoreload is needed and reload.
715 716 717 718 719 |
# File 'lib/gin/app.rb', line 715 def try_autoreload env return if env[GIN_RELOADED] || !autoreload env[GIN_RELOADED] = true reload! end |