Module: Merb

Module | Merb
In: | lib/merb-core/autoload.rb lib/merb-core/bootloader.rb lib/merb-core/config.rb lib/merb-core/constants.rb lib/merb-core/controller/abstract_controller.rb lib/merb-core/controller/exceptions.rb lib/merb-core/controller/mime.rb lib/merb-core/controller/mixins/controller.rb lib/merb-core/controller/mixins/responder.rb lib/merb-core/dispatch/cookies.rb lib/merb-core/dispatch/default_exception/default_exception.rb lib/merb-core/dispatch/dispatcher.rb lib/merb-core/dispatch/request.rb lib/merb-core/dispatch/request_parsers.rb lib/merb-core/dispatch/router/behavior.rb lib/merb-core/dispatch/router/cached_proc.rb lib/merb-core/dispatch/router/resources.rb lib/merb-core/dispatch/router/route.rb lib/merb-core/dispatch/router.rb lib/merb-core/dispatch/session/container.rb lib/merb-core/dispatch/session/cookie.rb lib/merb-core/dispatch/session/memcached.rb lib/merb-core/dispatch/session/memory.rb lib/merb-core/dispatch/session/store_container.rb lib/merb-core/dispatch/session.rb lib/merb-core/dispatch/worker.rb lib/merb-core/logger.rb lib/merb-core/plugins.rb lib/merb-core/rack/adapter/abstract.rb lib/merb-core/rack/adapter/ebb.rb lib/merb-core/rack/adapter/evented_mongrel.rb lib/merb-core/rack/adapter/fcgi.rb lib/merb-core/rack/adapter/irb.rb lib/merb-core/rack/adapter/mongrel.rb lib/merb-core/rack/adapter/runner.rb lib/merb-core/rack/adapter/swiftiplied_mongrel.rb lib/merb-core/rack/adapter/thin.rb lib/merb-core/rack/adapter/thin_turbo.rb lib/merb-core/rack/adapter/webrick.rb lib/merb-core/rack/adapter.rb lib/merb-core/rack/application.rb lib/merb-core/rack/handler/mongrel.rb lib/merb-core/rack/helpers.rb lib/merb-core/rack/middleware/conditional_get.rb lib/merb-core/rack/middleware/content_length.rb lib/merb-core/rack/middleware/path_prefix.rb lib/merb-core/rack/middleware/profiler.rb lib/merb-core/rack/middleware/static.rb lib/merb-core/rack/middleware/tracer.rb lib/merb-core/rack/middleware.rb lib/merb-core/rack/stream_wrapper.rb lib/merb-core/rack.rb lib/merb-core/server.rb lib/merb-core/tasks/merb_rake_helper.rb lib/merb-core/test/helpers/controller_helper.rb lib/merb-core/test/helpers/cookie_jar.rb lib/merb-core/test/helpers/mock_request_helper.rb lib/merb-core/test/helpers/request_helper.rb lib/merb-core/test/helpers/route_helper.rb lib/merb-core/test/run_specs.rb lib/merb-core/test/test_ext/rspec.rb lib/merb-core/test.rb lib/merb-core/version.rb lib/merb-core.rb

require "time" # httpdate

#### Public Merb Logger API

To replace an existing logger with a new one:

     Merb::Logger.set_log(log{String, IO},level{Symbol, String})

Available logging levels are

      Merb::Logger::{ Fatal, Error, Warn, Info, Debug }

Logging via:

      Merb.logger.fatal(message<String>,&block)
      Merb.logger.error(message<String>,&block)
      Merb.logger.warn(message<String>,&block)
      Merb.logger.info(message<String>,&block)
      Merb.logger.debug(message<String>,&block)

Logging with autoflush:

      Merb.logger.fatal!(message<String>,&block)
      Merb.logger.error!(message<String>,&block)
      Merb.logger.warn!(message<String>,&block)
      Merb.logger.info!(message<String>,&block)
      Merb.logger.debug!(message<String>,&block)

Flush the buffer to

      Merb.logger.flush

Remove the current log object

      Merb.logger.close

#### Private Merb Logger API

To initialize the logger you create a new object, proxies to set_log.

      Merb::Logger.new(log{String, IO},level{Symbol, String})

### Methods

add_generators add_mime_type add_rakefiles at_exit at_exit_procs available_accepts available_mime_types bundled? config deferred_actions dir_for disable disabled? disabled_components disabled_components= env? exception exiting= fatal! forking_environment? framework_root generators glob_for load_config load_dependencies log_path log_stream logger merge_env mime_transform_method on_jruby? on_windows? orm orm_generator_scope print_colorized_backtrace push_path rakefiles reload remove_mime_type remove_paths reset_logger! restart_environment root root= root_path run_later start start_environment template_engine test_framework test_framework_generator_scope testing? trap

### Classes and Modules

Module Merb::AuthenticationMixin
Module Merb::ConditionalGetMixin
Module Merb::Const
Module Merb::ControllerExceptions
Module Merb::ControllerMixin
Module Merb::CookiesMixin
Module Merb::GlobalHelpers
Module Merb::InlineTemplates
Module Merb::MemcacheStore
Module Merb::Parse
Module Merb::Plugins
Module Merb::Rack
Module Merb::RakeHelper
Module Merb::RenderMixin
Module Merb::ResponderMixin
Module Merb::Session
Module Merb::SessionMixin
Module Merb::Template
Module Merb::Test
Class Merb::AbstractController
Class Merb::AcceptType
Class Merb::BootLoader
Class Merb::Config
Class Merb::Controller
Class Merb::CookieSession
Class Merb::Cookies
Class Merb::Counter
Class Merb::Dispatcher
Class Merb::Logger
Class Merb::MemcacheSession
Class Merb::MemorySession
Class Merb::MemorySessionStore
Class Merb::Request
Class Merb::ReservedError
Class Merb::Responder
Class Merb::Router
Class Merb::Server
Class Merb::SessionContainer
Class Merb::SessionStoreContainer
Class Merb::Worker

### Constants

VERSION | = | '1.0.8.1' unless defined?(Merb::VERSION)
DM_VERSION | = | '0.9.9' unless defined?(Merb::DM_VERSION)

### External Aliases

environment | -> | env
| :api: public
started | -> | started?
| :api: public

### Attributes

adapter | [RW] | :api: public
environment | [RW] | :api: public
environment_info | [RW] | :api: private
exiting | [R] |
klass_hashes | [RW] | Set up default variables under Merb
load_paths | [RW] | :api: private
orm | [RW] | Set up default variables under Merb
started | [RW] | :api: private
template_engine | [RW] | Set up default variables under Merb
test_framework | [RW] | Set up default variables under Merb

### Public Class methods

add_generators(*generators)

#### Parameters

*generators: | Generator paths to add to the list of generators.

#### Notes

Recommended way to add Generator load paths for plugin authors.

:api: public

add_mime_type(key, transform_method, mimes, new_response_headers = {}, default_quality = 1, &block)

Any specific outgoing headers should be included here. These are not the content-type header but anything in addition to it. `transform_method` should be set to a symbol of the method used to transform a resource into this mime type. For example for the :xml mime type an object might be transformed by calling :to_xml, or for the :js mime type, :to_json. If there is no transform method, use nil.

#### Autogenerated Methods

Adding a mime-type adds a render_type method that sets the content type and calls render.

By default this does: def render_all, def render_yaml, def render_text, def render_html, def render_xml, def render_js, and def render_yaml

#### Parameters

key<Symbol>: | The name of the mime-type. This is used by the provides API
transform_method<~to_s>: | The associated method to call on objects to convert them to the appropriate mime-type. For instance, :json would use :to_json as its transform_method.
mimes<Array[String]>: | A list of possible values sent in the Accept header, such as text/html, that should be associated with this content-type.
new_response_headers<Hash>: | The response headers to set for the the mime type. For example: ‘Content-Type’ => ‘application/json; charset=utf-8’; As a shortcut for the common charset option, use :charset => ‘utf-8’, which will be correctly appended to the mimetype itself.
&block: | a block which recieves the current controller when the format

      is set (in the controller's #content_type method)

#### Returns

nil

:api: public

add_rakefiles(*rakefiles)

#### Parameters

*rakefiles: | Rakefile paths to add to the list of Rakefiles.

#### Notes

Recommended way to add Rakefiles load path for plugins authors.

:api: public

at_exit(&blk)

Register a proc to run when Merb is exiting gracefully. It will not be run when Merb exits quickly.

#### Returns

Array: | The current list of procs to run when Merb exits gracefully

:api: plugin

at_exit_procs()

The list of procs that have been registered with Merb to run when Merb exits gracefully.

#### Returns

Array: | The current list of procs

:api: private

available_accepts()

#### Returns

Hash{String => Symbol}: | A hash mapping Content-Type values to the mime type key of the appropriate entry in available_mime_types

:api: public

available_mime_types()

Returns a hash of the available mime types.

#### Returns

Hash{Symbol => Hash{Symbol => Object}}: | The available mime types.

#### Notes

Each entry corresponds to a call to add_mime_type, having the mime type key (:html, :xml, :json, etc.) as the key and a hash containing the following entries:

      :accepts           # the mime types that will be recognized by this entry
      :transform_method  # the method called on an object to convert it to content of this type (such as to_json)
      :content_type      # the value set to the "Content-Type" HTTP header when this mime is sent in a response
      :response_headers  # sent in a response using this content type
      :default_quality   # the scale factor used in describing content type preference
      :response_block    # the block to be called with the controller when a request responds to this mime type

:api: public

bundled?()

#### Returns

Boolean: | True if Merb is running as an application with bundled gems.

#### Notes

Bundling required gems makes your application independent from the environment it runs in. It is a good practice to freeze application framework and gems and is very useful when application is run in some sort of sandbox, for instance, shared hosting with preconfigured gems.

:api: public

config(&block)

If block was given configures using the block.

#### Parameters

&block: | Configuration parameter block, see example below.

#### Returns

Hash: | The current configuration.

#### Notes

See Merb::GlobalHelpers.load_config for configuration options list.

#### Examples

      Merb.config do
        beer               "good"
        hashish            :foo => "bar"
        environment        "development"
        log_level          "debug"
        use_mutex          false
        exception_details  true
        reload_classes     true
        reload_time        0.5
      end

:api: public

deferred_actions()

#### Returns

RegExp: | Regular expression against which deferred actions are matched by Rack application handler.

#### Notes

Concatenates :deferred_actions configuration option values.

:api: public

dir_for(type)

#### Parameters

type<Symbol>: | The type of path to retrieve directory for, e.g. :view.

#### Returns

String: | The directory for the requested type.

:api: public

disable(*components)

Disables the given core components, like a Gem for example.

#### Parameters

*args: | One or more symbols of Merb internal components.

:api: public

disabled?(*components)

#### Returns

Boolean: | True if all components (or just one) are disabled.

:api: public

disabled_components()

#### Returns

Array: | All components that have been disabled.

:api: public

disabled_components=(components)

#### Parameters

Array: | All components that should be disabled.

:api: public

env?(env)

Ask the question about which environment you‘re in.

#### Parameters

env<Symbol, String>: | Name of the environment to query

#### Examples

Merb.env #=> production Merb.env?(:production) #=> true Merb.env?(:development) #=> false

:api: public

exception(e)

Required to show exceptions in the log file

e<Exception>: | The exception that a message is being generated for

:api: plugin

exiting=(bool)

Set the current exiting state of Merb. Setting this state to true also alerts Extlib to exit and clean up its state.

#### Returns

Boolean: | The current exiting state of Merb

:api: private

fatal!(str, e = nil)

Perform a hard Exit. Print a backtrace to the merb logger before exiting if verbose is enabled.

:api: private

forking_environment?()

:api: plugin

framework_root()

#### Returns

String: | The path of root directory of the Merb framework.

:api: public

generators()

### Returns

Array(String): | Paths generators are loaded from

### Notes

Recommended way to find out what paths generators are loaded from.

:api: public

glob_for(type)

#### Parameters

type<Symbol>: | The type of path to retrieve glob for, e.g. :view.

##### Returns

String: | The pattern with which to match files within the type directory.

:api: public

load_config(options = {})

Load configuration and assign the logger.

#### Parameters

options<Hash>: | Options to pass on to the Merb config.

#### Options

:host<String>: | host to bind to, default is 0.0.0.0.
:port<Fixnum>: | port to run Merb application on, default is 4000.
:adapter<String>: | name of Rack adapter to use, default is "runner"
:rackup<String>: | name of Rack init file to use, default is "rack.rb"
:reload_classes<Boolean>: | whether Merb should reload classes on each request, default is true
:environment<String>: | name of environment to use, default is development
:merb_root<String>: | Merb application root, default is Dir.pwd
:use_mutex<Boolean>: | turns action dispatch synchronization on or off, default is on (true)
:log_delimiter<String>: | what Merb logger uses as delimiter between message sections, default is " ~ "
:log_auto_flush<Boolean>: | whether the log should automatically flush after new messages are added, defaults to true.
:log_stream<IO>: | IO handle for logger. Defaults to STDOUT.
:log_file<String>: | File path for logger. Overrides :log_stream.
:log_level<Symbol>: | logger level, default is :info
:disabled_components<Array[Symbol]>: | array of disabled component names, for instance, to disable json gem, specify :json. Default is empty array.
:deferred_actions<Array(Symbol, String)]>: | names of actions that should be deferred no matter what controller they belong to. Default is empty array.

Some of these options come from command line on Merb application start, some of them are set in Merb init file or environment-specific.

:api: public

load_dependencies(options = {})

Load all basic dependencies (selected BootLoaders only). This sets up Merb framework component paths (directories for models, controllers, etc) using framework.rb or default layout, loads init file and dependencies specified in it and runs before_app_loads hooks.

#### Parameters

options<Hash>: | Options to pass on to the Merb config.

:api: public

log_path()

#### Returns

String: | Path to the log directory which contains the log file.

:api: public

log_stream(port = "main")

#### Returns

String: | The path to the log file. If this Merb instance is running as a daemon this will return `STDOUT`.

#### Notes

When Merb.testing? the port is modified to become :test - this keeps this special environment situation from ending up in the memoized @streams just once, thereby never taking changes into account again. Now, it will be memoized as :test - and just logging to merb_test.log.

:api: public

logger()

Return the Merb Logger object for the current thread. Set it up if it does not exist.

:api: public

merge_env(env,use_db=false)

Merge environment settings

This can allow you to have a "localdev" environment that runs like your "development".

      OR

A "staging" environment that runs identical to your "production" environment.

#### Examples

From any environment config file (ie, development.rb, custom.rb, localdev.rb, etc).

      staging.rb:
        Merb.merge_env "production"         # We want to use all the settings production uses
        Merb::Config.use do |c|
          c[:log_level]         = "debug"   # except we want debug log level
          c[:log_stream]        = @some_io  # and log to this IO handle
          c[:exception_details] = true      # and we want to see exception details
        end

#### Parameters

env<~String>: | Environment to run like
use_db<~Boolean>: | Should Merb use the merged environments DB connection

        Defaults to +false+

:api: public

mime_transform_method(key)

#### Parameters

key<Symbol>: | The key that represents the mime-type.

#### Returns

Symbol: | The transform method for the mime type, e.g. :to_json.

#### Raises

ArgumentError: | The requested mime type is not valid.

:api: private

on_jruby?()

:api: plugin

on_windows?()

:api: plugin

orm()

Returns the default ORM for this application. For instance, :datamapper.

#### Returns

<Symbol>: | default ORM.

:api: public

orm_generator_scope()

@deprecated

print_colorized_backtrace(e)

Print a colorized backtrace to the merb logger.

:api: private

push_path(type, path, file_glob = "**/*.rb")

This is the mechanism for setting up your application layout. There are three application layouts in Merb:

1. Regular app/:type layout of Ruby on Rails fame:

app/models for models app/mailers for mailers (special type of controllers) app/parts for parts, Merb components app/views for templates app/controllers for controller lib for libraries

1. Flat application layout:

application.rb for models, controllers, mailers, etc config/init.rb for initialization and router configuration config/framework.rb for framework and dependencies configuration views for views

1. Camping-style "very flat" application layout, where the whole Merb

application and configs are contained within a single file.

#### Notes

Autoloading for lib uses an empty glob by default. If you want to have your libraries under lib use autoload, add the following to Merb init file:

Merb.push_path(:lib, Merb.root / "lib", "**/*.rb") # glob set explicity.

Then lib/magicwand/lib/magicwand.rb with MagicWand module will be autoloaded when you first access that constant.

#### Examples

This method gives you a way to build up your own application structure, for instance, to reflect the structure Rails uses to simplify transition of legacy application, you can set it up like this:

Merb.push_path(:model, Merb.root / "app" / "models", "**/*.rb") Merb.push_path(:mailer, Merb.root / "app" / "models", "**/*.rb") Merb.push_path(:controller, Merb.root / "app" / "controllers", "**/*.rb") Merb.push_path(:view, Merb.root / "app" / "views", "**/*.rb")

#### Parameters

type<Symbol>: | The type of path being registered (i.e. :view)
path<String>: | The full path
file_glob<String>: | A glob that will be used to autoload files under the path. Defaults to "**/*.rb".

:api: public

rakefiles()

#### Returns

Array(String): | Paths Rakefiles are loaded from.

#### Notes

Recommended way to find out what paths Rakefiles are loaded from.

:api: public

reload()

Reload application and framework classes. See Merb::BootLoader::ReloadClasses for details.

:api: public

remove_mime_type(key)

Removes a MIME-type from the mime-type list.

#### Parameters

key<Symbol>: | The key that represents the mime-type to remove.

#### Returns

(Boolean, Hash{Symbol => Object}): | If it was present, the old specification of the MIME-type. Same structure

      as a value in Merb.available_mime_types. False if the key was not present.

#### Notes

:all is the key for */*; It can‘t be removed.

:api: public

remove_paths(*args)

Removes given types of application components from load path Merb uses for autoloading.

#### Parameters

*args<Array(Symbol)>: | component(s) names, for instance, :views, :models

#### Examples

Using this combined with Merb::GlobalHelpers.push_path you can make your Merb application use legacy Rails application components.

Merb.root = "path/to/legacy/app/root" Merb.remove_paths(:mailer) Merb.push_path(:mailer, Merb.root / "app" / "models", "**/*.rb")

Will make Merb use app/models for mailers just like Ruby on Rails does.

:api: public

reset_logger!()

Removes the logger for the current thread (nil).

:api: public

restart_environment(argv={})

Restart the Merb environment explicitly.

#### Parameters

argv<String, Hash>: | The config arguments to restart Merb with. Defaults to +Merb::Config+.

:api: public

root()

#### Returns

String: | The Merb root path.

:api: public

root=(value)

#### Parameters

value<String>: | Path to the root directory.

:api: public

root_path(*path)

#### Parameters

*path: | The relative path (or list of path components) to a directory under the root of the application.

#### Returns

String: | The full path including the root.

#### Examples

      Merb.root = "/home/merb/app"
      Merb.path("images") # => "/home/merb/app/images"
      Merb.path("views", "admin") # => "/home/merb/app/views/admin"

@public

run_later(&blk)
start(argv = ARGV)

Start Merb by setting up the Config and then starting the server. Set the Merb application environment and the root path.

#### Parameters

argv<String, Hash>: | The config arguments to start Merb with. Defaults to `ARGV`.

:api: public

start_environment(argv=ARGV)

Start the Merb environment, but only if it hasn‘t been loaded yet.

#### Parameters

argv<String, Hash>: | The config arguments to start Merb with. Defaults to `ARGV`.

:api: public

template_engine()

Returns the default template engine for this application. For instance :haml.

#### Returns

<Symbol>: | default template engine.

:api: public

test_framework()

Returns the default test framework for this application. For instance :rspec.

#### Returns

<Symbol>: | default test framework.

:api: public

test_framework_generator_scope()

@deprecated

testing?()

#### Returns

Boolean: | True if Merb environment is testing for instance,

Merb is running with RSpec, Test::Unit of other testing facility.

:api: public

trap(signal, &block)

Install a signal handler for a given signal unless signals have been disabled with Merb.disable(:signals)

#### Parameters

signal: | The name of the signal to install a handler for.
&block: | The block to be run when the given signal is received.

:api: public

[Validate]