### Home Classes Methods

### In Files

- lib/merb-core/bootloader.rb

### Parent

Merb::BootLoader

### Methods

- ::exit_gracefully
- ::load_classes
- ::load_file
- ::reap_workers
- ::reap_workers_signal
- ::reload
- ::remove_classes_in_file
- ::remove_constant
- ::run
- ::start_transaction

### Files

- CHANGELOG
- LICENSE
- README
- TODO

### Class/Module Index

Quicksearch

- Merb
- Merb::AbstractController
- Merb::AcceptType
- Merb::AuthenticationMixin
- Merb::AuthenticationMixin::BasicAuthentication
- Merb::BootLoader
- Merb::BootLoader::AfterAppLoads
- Merb::BootLoader::BackgroundServices
- Merb::BootLoader::BeforeAppLoads
- Merb::BootLoader::BuildFramework
- Merb::BootLoader::ChooseAdapter
- Merb::BootLoader::Cookies
- Merb::BootLoader::Defaults
- Merb::BootLoader::Dependencies
- Merb::BootLoader::DropPidFile
- Merb::BootLoader::LoadClasses
- Merb::BootLoader::Logger
- Merb::BootLoader::MimeTypes
- Merb::BootLoader::MixinSession
- Merb::BootLoader::RackUpApplication
- Merb::BootLoader::ReloadClasses
- Merb::BootLoader::ReloadClasses::TimedExecutor
- Merb::BootLoader::Router
- Merb::BootLoader::SetupSession
- Merb::BootLoader::SetupStubClasses
- Merb::BootLoader::Templates
- Merb::ConditionalGetMixin
- Merb::Config
- Merb::Config::ConfigBlock
- Merb::Const
- Merb::Controller
- Merb::ControllerExceptions
- Merb::ControllerExceptions::Accepted
- Merb::ControllerExceptions::ActionNotFound
- Merb::ControllerExceptions::BadGateway
- Merb::ControllerExceptions::BadRequest
- Merb::ControllerExceptions::Base
- Merb::ControllerExceptions::ClientError
- Merb::ControllerExceptions::Conflict
- Merb::ControllerExceptions::Continue
- Merb::ControllerExceptions::Created
- Merb::ControllerExceptions::ExpectationFailed
- Merb::ControllerExceptions::Forbidden
- Merb::ControllerExceptions::GatewayTimeout
- Merb::ControllerExceptions::Gone
- Merb::ControllerExceptions::HTTPVersionNotSupported
- Merb::ControllerExceptions::Informational
- Merb::ControllerExceptions::InternalServerError
- Merb::ControllerExceptions::LayoutNotFound
- Merb::ControllerExceptions::LengthRequired
- Merb::ControllerExceptions::MethodNotAllowed
- Merb::ControllerExceptions::MovedPermanently
- Merb::ControllerExceptions::MovedTemporarily
- Merb::ControllerExceptions::MultiPartParseError
- Merb::ControllerExceptions::MultipleChoices
- Merb::ControllerExceptions::NoContent
- Merb::ControllerExceptions::NonAuthoritativeInformation
- Merb::ControllerExceptions::NotAcceptable
- Merb::ControllerExceptions::NotFound
- Merb::ControllerExceptions::NotImplemented
- Merb::ControllerExceptions::NotModified
- Merb::ControllerExceptions::OK
- Merb::ControllerExceptions::PartialContent
- Merb::ControllerExceptions::PaymentRequired
- Merb::ControllerExceptions::PreconditionFailed
- Merb::ControllerExceptions::ProxyAuthenticationRequired
- Merb::ControllerExceptions::Redirection
- Merb::ControllerExceptions::RequestEntityTooLarge
- Merb::ControllerExceptions::RequestRangeNotSatisfiable
- Merb::ControllerExceptions::RequestTimeout
- Merb::ControllerExceptions::RequestURITooLarge
- Merb::ControllerExceptions::ResetContent
- Merb::ControllerExceptions::SeeOther
- Merb::ControllerExceptions::ServerError
- Merb::ControllerExceptions::ServiceUnavailable
- Merb::ControllerExceptions::Successful
- Merb::ControllerExceptions::SwitchingProtocols
- Merb::ControllerExceptions::TemplateNotFound
- Merb::ControllerExceptions::TemporaryRedirect
- Merb::ControllerExceptions::Unauthorized
- Merb::ControllerExceptions::UnsupportedMediaType
- Merb::ControllerExceptions::UseProxy
- Merb::ControllerMixin
- Merb::CookieSession
- Merb::CookieSession::CookieOverflow
- Merb::CookieSession::TamperedWithCookie
- Merb::Cookies
- Merb::CookiesMixin
- Merb::CookiesMixin::RequestMixin
- Merb::Counter
- Merb::Dispatcher
- Merb::Dispatcher::DefaultException
- Merb::Dispatcher::DefaultExceptionHelper
- Merb::GlobalHelpers
- Merb::InlineTemplates
- Merb::Logger
- Merb::MemcacheSession
- Merb::MemcacheStore
- Merb::MemorySession
- Merb::MemorySessionStore
- Merb::Parse
- Merb::Plugins
- Merb::Rack
- Merb::Rack::AbstractAdapter
- Merb::Rack::Adapter
- Merb::Rack::Application
- Merb::Rack::ConditionalGet
- Merb::Rack::Console
- Merb::Rack::ContentLength
- Merb::Rack::DeferrableMiddleware
- Merb::Rack::Ebb
- Merb::Rack::EventedMongrel
- Merb::Rack::FastCGI
- Merb::Rack::Handler
- Merb::Rack::Handler::Mongrel
- Merb::Rack::Head
- Merb::Rack::Helpers
- Merb::Rack::Irb
- Merb::Rack::Middleware
- Merb::Rack::Mongrel
- Merb::Rack::PathPrefix
- Merb::Rack::Profiler
- Merb::Rack::Runner
- Merb::Rack::Static
- Merb::Rack::StreamWrapper
- Merb::Rack::SwiftipliedMongrel
- Merb::Rack::Thin
- Merb::Rack::ThinTurbo
- Merb::Rack::Tracer
- Merb::Rack::WEBrick
- Merb::RenderMixin
- Merb::RenderMixin::ClassMethods
- Merb::Request
- Merb::ReservedError
- Merb::Responder
- Merb::ResponderMixin
- Merb::ResponderMixin::ClassMethods
- Merb::ResponderMixin::ContentTypeAlreadySet
- Merb::Router
- Merb::Router::Behavior
- Merb::Router::Behavior::Error
- Merb::Router::Behavior::Proxy
- Merb::Router::CachedProc
- Merb::Router::GenerationError
- Merb::Router::NotCompiledError
- Merb::Router::Resources
- Merb::Router::RouteNotFound
- Merb::Server
- Merb::Session
- Merb::SessionContainer
- Merb::SessionMixin
- Merb::SessionMixin::NoSessionContainer
- Merb::SessionMixin::RequestMixin
- Merb::SessionMixin::RequestMixin::ClassMethods
- Merb::SessionMixin::SessionOverflow
- Merb::SessionStoreContainer
- Merb::System
- Merb::System::PortablePoller
- Merb::Template
- Merb::Template::Erubis
- Merb::Template::Erubis::Mixin
- Merb::Test
- Merb::Test::ControllerHelper
- Merb::Test::Cookie
- Merb::Test::CookieJar
- Merb::Test::ExampleGroup
- Merb::Test::Helpers
- Merb::Test::MakeRequest
- Merb::Test::Matchers
- Merb::Test::MultipartRequestHelper
- Merb::Test::MultipartRequestHelper::FileParam
- Merb::Test::MultipartRequestHelper::Param
- Merb::Test::MultipartRequestHelper::Post
- Merb::Test::RequestHelper
- Merb::Test::RequestHelper::CookieJar
- Merb::Test::RequestHelper::FakeRequest
- Merb::Test::RouteHelper
- Merb::Test::Rspec
- Merb::Test::Rspec::ControllerMatchers
- Merb::Test::Rspec::ControllerMatchers::BeError
- Merb::Test::Rspec::ControllerMatchers::BeRedirect
- Merb::Test::Rspec::ControllerMatchers::Provide
- Merb::Test::Rspec::RouteMatchers
- Merb::Test::Rspec::RouteMatchers::ParameterMatcher
- Merb::Test::Rspec::RouteMatchers::RouteToMatcher
- Merb::Test::ViewHelper
- Merb::Test::WebratHelper
- Merb::Worker
- Erubis
- Erubis::Basic
- Erubis::Basic::Converter
- Erubis::BlockAwareEnhancer
- Erubis::BlockAwareEruby
- Erubis::MEruby
- Spec
- Spec::Matchers
- Spec::Matchers::MatcherDSL
- Spec::Runner
- Spec::Runner::Formatter
- Spec::Runner::Formatter::BaseTextFormatter
- Gem
- Gem::Dependency
- Hpricot
- Hpricot::Elem
- Mongrel
- Mongrel::HttpResponse
- Class
- Exception
- Hash
- Kernel
- MemCache
- Memcached
- Object
- String
- Time

No matching classes.

# Merb::BootLoader::LoadClasses

Load all classes inside the load paths.

This is used in conjunction with Merb::BootLoader::ReloadClasses to track files that need to be reloaded, and which constants need to be removed in order to reload a file.

This also adds the model, controller, and lib directories to the load path, so they can be required in order to avoid load-order issues.

### Constants

FILES_LOADED
LOADED_CLASSES
MTIMES

### Public Class Methods

exit_gracefully() click to toggle source

Wait for any children to exit, remove the "main" PID, and exit.

#### Returns

(Does not return.)

:api: private

    # File lib/merb-core/bootloader.rb, line 685
    def exit_gracefully
      # wait all workers to exit
      Process.waitall
      # remove master process pid
      Merb::Server.remove_pid("main")
      # terminate, workers remove their own pids
      # in on exit hook

      Merb::BootLoader.before_master_shutdown_callbacks.each do |cb|
        begin
          cb.call
        rescue Exception => e
          Merb.logger.fatal "before_master_shutdown callback crashed: #{e.message}"
        end
      end
      exit
    end

load_classes(*paths) click to toggle source

Load classes from given paths - using path/glob pattern.

#### Parameters

*paths<Array> | Array of paths to load classes from - may contain glob pattern

#### Returns

nil

:api: private

    # File lib/merb-core/bootloader.rb, line 926
    def load_classes(*paths)
      orphaned_classes = []
      paths.flatten.each do |path|
        Dir[path].sort.each do |file|
          begin
            load_file file
          rescue NameError => ne
            Merb.logger.verbose! "Stashed file with missing requirements for later reloading: #{file}"
            ne.backtrace.each_with_index { |line, idx| Merb.logger.verbose! "[#{idx}]: #{line}" }
            orphaned_classes.unshift(file)
          end
        end
      end
      load_classes_with_requirements(orphaned_classes)
    end

load_file(file, reload = false) click to toggle source

Loads a file, tracking its modified time and, if necessary, the classes it declared.

#### Parameters

file<String> | The file to load.

#### Returns

nil

:api: private

    # File lib/merb-core/bootloader.rb, line 872
    def load_file(file, reload = false)
      Merb.logger.verbose! "#{reload ? "re" : ""}loading #{file}"

      # If we're going to be reloading via constant remove,
      # keep track of what constants were loaded and what files
      # have been added, so that the constants can be removed
      # and the files can be removed from $LOADED_FEAUTRES
      if !Merb::Config[:fork_for_class_load]
        if FILES_LOADED[file]
          FILES_LOADED[file].each {|lf| $LOADED_FEATURES.delete(lf)}
        end

        klasses = ObjectSpace.classes.dup
        files_loaded = $LOADED_FEATURES.dup
      end

      # If we're in the midst of a reload, remove the file
      # itself from $LOADED_FEATURES so it will get reloaded
      if reload
        $LOADED_FEATURES.delete(file) if reload
      end

      # Ignore the file for syntax errors. The next time
      # the file is changed, it'll be reloaded again
      begin
        require file
      rescue SyntaxError => e
        Merb.logger.error "Cannot load #{file} because of syntax error: #{e.message}"
      ensure
        if Merb::Config[:reload_classes]
          MTIMES[file] = File.mtime(file)
        end
      end

      # If we're reloading via constant remove, store off the details
      # after the file has been loaded
      unless Merb::Config[:fork_for_class_load]
        LOADED_CLASSES[file] = ObjectSpace.classes - klasses
        FILES_LOADED[file] = $LOADED_FEATURES - files_loaded
      end

      nil
    end

reap_workers(status = 0, sig = reap_workers_signal) click to toggle source

Reap any workers of the spawner process and exit with an appropriate status code.

Note that exiting the spawner process with a status code of 128 when a master process exists will cause the spawner process to be recreated, and the app code reloaded.

#### Parameters

status<Integer> | The status code to exit with. Defaults to 0.
sig<String> | The signal to send to workers

#### Returns

(Does not return.)

:api: private

    # File lib/merb-core/bootloader.rb, line 826
    def reap_workers(status = 0, sig = reap_workers_signal)

      Merb.logger.info "Executed all before worker shutdown callbacks..."
      Merb::BootLoader.before_worker_shutdown_callbacks.each do |cb|
        begin
          cb.call
        rescue Exception => e
          Merb.logger.fatal "before worker shutdown callback crashed: #{e.message}"
        end

      end

      Merb.exiting = true unless status == 128

      begin
        if @writer
          @writer.puts(status.to_s)
          @writer.close
        end
      rescue SystemCallError
      end

      threads = []

      ($WORKERS || []).each do |p|
        threads << Thread.new do
          begin
            Process.kill(sig, p)
            Process.wait2(p)
          rescue SystemCallError
          end
        end
      end
      threads.each {|t| t.join }
      exit(status)
    end

reap_workers_signal() click to toggle source

    # File lib/merb-core/bootloader.rb, line 807
    def reap_workers_signal
      Merb::Config[:reap_workers_quickly] ? "KILL" : "ABRT"
    end

reload(file) click to toggle source

Reloads the classes in the specified file. If fork-based loading is used, this causes the current processes to be killed and and all classes to be reloaded. If class-based loading is not in use, the classes declared in that file are removed and the file is reloaded.

#### Parameters

file<String> | The file to reload.

#### Returns

When fork-based loading is used:

    (Does not return.)

When fork-based loading is not in use:

    nil

:api: private

    # File lib/merb-core/bootloader.rb, line 957
    def reload(file)
      if Merb::Config[:fork_for_class_load]
        reap_workers(128)
      else
        remove_classes_in_file(file) { |f| load_file(f, true) }
      end
    end

remove_classes_in_file(file, &block) click to toggle source

Removes all classes declared in the specified file. Any hashes which use classes as keys will be protected provided they have been added to Merb.klass_hashes. These hashes have their keys substituted with placeholders before the file's classes are unloaded. If a block is provided, it is called before the substituted keys are reconstituted.

#### Parameters

file<String> | The file to remove classes for.
&block | A block to call with the file that has been removed before klass_hashes are updated

to use the current values of the constants they used as keys.

#### Returns

nil

:api: private

    # File lib/merb-core/bootloader.rb, line 979
    def remove_classes_in_file(file, &block)
      Merb.klass_hashes.each { |x| x.protect_keys! }
      if klasses = LOADED_CLASSES.delete(file)
        klasses.each { |klass| remove_constant(klass) unless klass.to_s =~ /Router/ }
      end
      yield file if block_given?
      Merb.klass_hashes.each {|x| x.unprotect_keys!}
      nil
    end

remove_constant(const) click to toggle source

Removes the specified class.

Additionally, removes the specified class from the subclass list of every superclass that tracks it's subclasses in an array returned by _subclasses_list. Classes that wish to use this functionality are required to alias the reader for their list of subclasses to _subclasses_list. Plugins for ORMs and other libraries should keep this in mind.

#### Parameters

const<Class> | The class to remove.

#### Returns

nil

:api: private

    # File lib/merb-core/bootloader.rb, line 1003
    def remove_constant(const)
      # This is to support superclasses (like AbstractController) that track
      # their subclasses in a class variable.
      superklass = const
      until (superklass = superklass.superclass).nil?
        if superklass.respond_to?(:_subclasses_list)
          superklass.send(:_subclasses_list).delete(klass)
          superklass.send(:_subclasses_list).delete(klass.to_s)
        end
      end

      parts = const.to_s.split("::")
      base = parts.size == 1 ? Object : Object.full_const_get(parts[0..-2].join("::"))
      object = parts[-1].to_s
      begin
        base.send(:remove_const, object)
        Merb.logger.debug("Removed constant #{object} from #{base}")
      rescue NameError
        Merb.logger.debug("Failed to remove constant #{object} from #{base}")
      end
      nil
    end

run() click to toggle source

Load all classes from Merb's native load paths.

If fork-based loading is used, every time classes are loaded this will return in a new spawner process and boot loading will continue from this point in the boot loading process.

If fork-based loading is not in use, this only returns once and does not fork a new process.

#### Returns

Returns at least once:

    nil

:api: plugin

    # File lib/merb-core/bootloader.rb, line 645
    def run
      # process name you see in ps output
      $0 = "merb#{" : " + Merb::Config[:name] if Merb::Config[:name]} : master"

      # Log the process configuration user defined signal 1 (SIGUSR1) is received.
      Merb.trap("USR1") do
        require "yaml"
        Merb.logger.fatal! "Configuration:\n#{Merb::Config.to_hash.merge(:pid => $$).to_yaml}\n\n"
      end

      if Merb::Config[:fork_for_class_load] && !Merb.testing?
        start_transaction
      else
        Merb.trap('INT') do
          Merb.logger.warn! "Reaping Workers"
          reap_workers
        end
      end

      # Load application file if it exists - for flat applications
      load_file Merb.dir_for(:application) if File.file?(Merb.dir_for(:application))

      # Load classes and their requirements
      Merb.load_paths.each do |component, path|
        next if path.last.blank? || component == :application || component == :router
        load_classes(path.first / path.last)
      end

      Merb::Controller.send :include, Merb::GlobalHelpers

      nil
    end

start_transaction() click to toggle source

Set up the BEGIN point for fork-based loading and sets up any signals in the parent and child. This is done by forking the app. The child process continues on to run the app. The parent process waits for the child process to finish and either forks again

#### Returns

Parent Process:

    (Does not return.)

Child Process returns at least once:

    nil

:api: private

    # File lib/merb-core/bootloader.rb, line 716
    def start_transaction
      Merb.logger.warn! "Parent pid: #{Process.pid}"
      reader, writer = nil, nil

      # Enable REE garbage collection
      if GC.respond_to?(:copy_on_write_friendly=)
        GC.copy_on_write_friendly = true
      end

      loop do
        # create two connected endpoints
        # we use them for master/workers communication
        reader, @writer = IO.pipe
        pid = Kernel.fork

        # pid means we're in the parent; only stay in the loop if that is case
        break unless pid
        # writer must be closed so reader can generate EOF condition
        @writer.close

        # master process stores pid to merb.main.pid
        Merb::Server.store_pid("main") if Merb::Config[:daemonize] || Merb::Config[:cluster]

        if Merb::Config[:console_trap]
          Merb.trap("INT") {}
        else
          # send ABRT to worker on INT
          Merb.trap("INT") do
            Merb.logger.warn! "Reaping Workers"
            begin
              Process.kill(reap_workers_signal, pid)
            rescue SystemCallError
            end
            exit_gracefully
          end
        end

        Merb.trap("HUP") do
          Merb.logger.warn! "Doing a fast deploy\n"
          Process.kill("HUP", pid)
        end

        reader_ary = [reader]
        loop do
          # wait for worker to exit and capture exit status
          #
          #
          # WNOHANG specifies that wait2 exists without waiting
          # if no worker processes are ready to be noticed.
          if exit_status = Process.wait2(pid, Process::WNOHANG)
            # wait2 returns a 2-tuple of process id and exit
            # status.
            #
            # We do not care about specific pid here.
            exit_status[1] && exit_status[1].exitstatus == 128 ? break : exit
          end
          # wait for data to become available, timeout in 0.5 of a second
          if select(reader_ary, nil, nil, 0.5)
            begin
              # no open writers
              next if reader.eof?
              msg = reader.readline
              reader.close
              if msg.to_i == 128
                Process.waitpid(pid, Process::WNOHANG)
                break
              else
                exit_gracefully
              end
            rescue SystemCallError
              exit_gracefully
            end
          end
        end
      end

      reader.close

      # add traps to the worker
      if Merb::Config[:console_trap]
        Merb::Server.add_irb_trap
        at_exit { reap_workers }
      else
        Merb.trap('INT') do
          Merb::BootLoader.before_worker_shutdown_callbacks.each { |cb| cb.call }
        end
        Merb.trap('ABRT') { reap_workers }
        Merb.trap('HUP') { reap_workers(128, "ABRT") }
      end
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.