Module: Merb

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

Overview

Most of this list is simply constants frozen for efficiency and lowered memory consumption. Every time Ruby VM comes across a string or a number or a regexp literal, new object is created.

This means if you refer to the same string 6 times per request and your application takes 100 requests per second, there are 600 objects for weak MRI garbage collector to work on.

GC cycles take up to 80% (!) time of request processing in some cases. Eventually Rubinius and maybe MRI 2.0 gonna improve this situation but at the moment, all commonly used strings, regexp and numbers used as constants so no extra objects created and VM just operates pointers.

Defined Under Namespace

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

Constant Summary collapse

VERSION =
'1.0'

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.adapterObject

:api: public



198
199
200
# File 'lib/merb-core.rb', line 198

def adapter
  @adapter
end

.environmentObject Also known as: env

:api: public



198
199
200
# File 'lib/merb-core.rb', line 198

def environment
  @environment
end

.environment_infoObject

:api: private



200
201
202
# File 'lib/merb-core.rb', line 200

def environment_info
  @environment_info
end

.exitingObject

Returns the value of attribute exiting.



43
44
45
# File 'lib/merb-core.rb', line 43

def exiting
  @exiting
end

.klass_hashesObject

Set up default variables under Merb



470
471
472
# File 'lib/merb-core.rb', line 470

def klass_hashes
  @klass_hashes
end

.load_pathsObject

:api: private



200
201
202
# File 'lib/merb-core.rb', line 200

def load_paths
  @load_paths
end

.ormObject

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

Returns

<Symbol>

default ORM.

:api: public



470
471
472
# File 'lib/merb-core.rb', line 470

def orm
  @orm
end

.startedObject Also known as: started?

:api: private



200
201
202
# File 'lib/merb-core.rb', line 200

def started
  @started
end

.template_engineObject

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

Returns

<Symbol>

default template engine.

:api: public



470
471
472
# File 'lib/merb-core.rb', line 470

def template_engine
  @template_engine
end

.test_frameworkObject

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

Returns

<Symbol>

default test framework.

:api: public



470
471
472
# File 'lib/merb-core.rb', line 470

def test_framework
  @test_framework
end

Class Method Details

.add_generators(*generators) ⇒ Object

Parameters

*generators

Generator paths to add to the list of generators.

Notes

Recommended way to add Generator load paths for plugin authors.

:api: public



749
750
751
752
# File 'lib/merb-core.rb', line 749

def add_generators(*generators)
  @generators ||= []
  @generators += generators
end

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

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>

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



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/merb-core/controller/mime.rb', line 70

def add_mime_type(key, transform_method, mimes, new_response_headers = {}, default_quality = 1, &block) 
  enforce!(key => Symbol, mimes => Array)
  
  content_type = new_response_headers["Content-Type"] || mimes.first
  
  if charset = new_response_headers.delete(:charset)
    content_type += "; charset=#{charset}"
  end
  
  ResponderMixin::TYPES.update(key => 
    {:accepts           => mimes, 
     :transform_method  => transform_method,
     :content_type      => content_type,
     :response_headers  => new_response_headers,
     :default_quality   => default_quality,
     :response_block    => block })

  mimes.each do |mime|
    ResponderMixin::MIMES.update(mime => key)
  end

  Merb::RenderMixin.class_eval <<-EOS, __FILE__, __LINE__
    def render_#{key}(thing = nil, opts = {})
      self.content_type = :#{key}
      render thing, opts
    end
  EOS
  
  nil
end

.add_rakefiles(*rakefiles) ⇒ Object

Parameters

*rakefiles

Rakefile paths to add to the list of Rakefiles.

Notes

Recommended way to add Rakefiles load path for plugins authors.

:api: public



737
738
739
740
# File 'lib/merb-core.rb', line 737

def add_rakefiles(*rakefiles)
  @rakefiles ||= []
  @rakefiles += rakefiles
end

.at_exit(&blk) ⇒ Object

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



84
85
86
# File 'lib/merb-core.rb', line 84

def at_exit(&blk)
  self.at_exit_procs << blk
end

.at_exit_procsObject

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



52
53
54
# File 'lib/merb-core.rb', line 52

def at_exit_procs
  @at_exit_procs ||= []
end

.available_acceptsObject

Returns

Hash=> Symbol

A hash mapping Content-Type values to the mime type key of the appropriate entry in #available_mime_types

:api: public



30
31
32
# File 'lib/merb-core/controller/mime.rb', line 30

def available_accepts
  ResponderMixin::MIMES
end

.available_mime_typesObject

Returns a hash of the available mime types.

Returns

Hash=> 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



21
22
23
# File 'lib/merb-core/controller/mime.rb', line 21

def available_mime_types
  ResponderMixin::TYPES
end

.bundled?Boolean

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

Returns:

  • (Boolean)


527
528
529
# File 'lib/merb-core.rb', line 527

def bundled?
  $BUNDLE || ENV.key?("BUNDLE")
end

.config(&block) ⇒ Object

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



668
669
670
671
# File 'lib/merb-core.rb', line 668

def config(&block)
  Merb::Config.configure(&block) if block_given?
  Config
end

.deferred_actionsObject

Returns

RegExp

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

Notes

Concatenates :deferred_actions configuration option values.

:api: public



425
426
427
428
429
430
431
432
433
# File 'lib/merb-core.rb', line 425

def deferred_actions
  @deferred ||= begin
    if Merb::Config[:deferred_actions].empty?
      /^\0$/
    else
      /#{Merb::Config[:deferred_actions].join("|")}/
    end
  end
end

.dir_for(type) ⇒ Object

Parameters

type<Symbol>

The type of path to retrieve directory for, e.g. :view.

Returns

String

The directory for the requested type.

:api: public



294
295
296
# File 'lib/merb-core.rb', line 294

def dir_for(type)
  Merb.load_paths[type].first
end

.disable(*components) ⇒ Object

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

Parameters

*args

One or more symbols of Merb internal components.

:api: public



679
680
681
# File 'lib/merb-core.rb', line 679

def disable(*components)
  disabled_components.push(*components)
end

.disabled?(*components) ⇒ Boolean

Returns

Boolean

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

:api: public

Returns:

  • (Boolean)


703
704
705
# File 'lib/merb-core.rb', line 703

def disabled?(*components)
  components.all? { |c| disabled_components.include?(c) }
end

.disabled_componentsObject

Returns

Array

All components that have been disabled.

:api: public



695
696
697
# File 'lib/merb-core.rb', line 695

def disabled_components
  Merb::Config[:disabled_components] ||= []
end

.disabled_components=(components) ⇒ Object

Parameters

Array

All components that should be disabled.

:api: public



687
688
689
# File 'lib/merb-core.rb', line 687

def disabled_components=(components)
  disabled_components.replace components
end

.env?(env) ⇒ Boolean

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

Returns:

  • (Boolean)


639
640
641
# File 'lib/merb-core.rb', line 639

def env?(env)
  Merb.env == env.to_s
end

.exception(e) ⇒ Object

Required to show exceptions in the log file

e<Exception>

The exception that a message is being generated for

:api: plugin



346
347
348
349
# File 'lib/merb-core/controller/exceptions.rb', line 346

def self.exception(e)
  "#{ e.message } - (#{ e.class })\n" <<  
  "#{(e.backtrace or []).join("\n")}" 
end

.fatal!(str, e = nil) ⇒ Object

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

:api: private



439
440
441
442
443
444
445
446
447
448
449
450
451
# File 'lib/merb-core.rb', line 439

def fatal!(str, e = nil)
  Merb.logger.fatal!
  Merb.logger.fatal!("\e[1;31;47mFATAL: #{str}\e[0m")
  Merb.logger.fatal!

  print_colorized_backtrace(e) if e && Merb::Config[:verbose]
  
  if Merb::Config[:show_ugly_backtraces]
    raise e
  else
    exit(1)
  end
end

.forking_environment?Boolean

:api: plugin

Returns:

  • (Boolean)


768
769
770
# File 'lib/merb-core.rb', line 768

def forking_environment?
  !on_windows? && !on_jruby?
end

.framework_rootObject

Returns

String

The path of root directory of the Merb framework.

:api: public



412
413
414
# File 'lib/merb-core.rb', line 412

def framework_root
  @framework_root ||= File.dirname(__FILE__)
end

.generatorsObject

Returns

Array(String)

Paths generators are loaded from

Notes

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

:api: public



726
727
728
# File 'lib/merb-core.rb', line 726

def generators
  @generators ||= []
end

.glob_for(type) ⇒ Object

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



305
306
307
# File 'lib/merb-core.rb', line 305

def glob_for(type)
  Merb.load_paths[type][1]
end

.load_config(options = {}) ⇒ Object

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>

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



590
591
592
593
# File 'lib/merb-core.rb', line 590

def load_config(options = {})
  Merb::Config.setup(Merb::Config.defaults.merge(options))
  Merb::BootLoader::Logger.run
end

.load_dependencies(options = {}) ⇒ Object

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



605
606
607
608
609
610
# File 'lib/merb-core.rb', line 605

def load_dependencies(options = {})
  load_config(options)
  Merb::BootLoader::BuildFramework.run
  Merb::BootLoader::Dependencies.run
  Merb::BootLoader::BeforeAppLoads.run
end

.log_pathObject

Returns

String

Path to the log directory which contains the log file.

:api: public



401
402
403
404
405
406
# File 'lib/merb-core.rb', line 401

def log_path
  case Merb::Config[:log_file]
  when String then File.dirname(Merb::Config[:log_file])
  else Merb.root_path("log")
  end
end

.log_stream(port = "main") ⇒ Object

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



370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'lib/merb-core.rb', line 370

def log_stream(port = "main")
  port = :test if Merb.testing?
  @streams ||= {}
  @streams[port] ||= begin
    log = if Merb.testing?
      log_path / "merb_test.log"
    elsif !Merb::Config[:daemonize] && !Merb::Config[:force_logging]
      STDOUT
    else
      log_path / "merb.#{port}.log"
    end
    
    if log.is_a?(IO)
      stream = log
    elsif File.exist?(log)
      stream = File.open(log, (File::WRONLY | File::APPEND))
    else
      FileUtils.mkdir_p(File.dirname(log))
      stream = File.open(log, (File::WRONLY | File::APPEND | File::CREAT))
      stream.write("#{Time.now.httpdate} #{Merb::Config[:log_delimiter]} " \
        "info #{Merb::Config[:log_delimiter]} Logfile created\n")
    end
    stream.sync = true
    stream
  end
end

.loggerObject

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

:api: public



347
348
349
# File 'lib/merb-core.rb', line 347

def logger
  Thread.current[:merb_logger] ||= Merb::Logger.new
end

.merge_env(env, use_db = false) ⇒ Object

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



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/merb-core.rb', line 110

def merge_env(env,use_db=false)
  if Merb.environment_info.nil?
    Merb.environment_info = {
      :real_env => Merb.environment,
      :merged_envs => [],
      :db_env => Merb.environment
    }
  end
  
  #Only load if it hasn't been loaded
  unless Merb.environment_info[:merged_envs].member? env
    Merb.environment_info[:merged_envs] << env
    
    env_file = Merb.dir_for(:config) / "environments" / ("#{env}.rb")
    if File.exists?(env_file)
      load(env_file)
    else
      Merb.logger.warn! "Environment file does not exist! #{env_file}"
    end
  end
  
  # Mark specific environment to load when ORM loads,
  # if multiple environments are loaded, the last one
  # with use_db as TRUE will be loaded
  if use_db
    Merb.environment_info[:db_env] = env
  end
end

.mime_transform_method(key) ⇒ Object

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

Raises:

  • (ArgumentError)


129
130
131
132
# File 'lib/merb-core/controller/mime.rb', line 129

def mime_transform_method(key)
  raise ArgumentError, ":#{key} is not a valid MIME-type" unless ResponderMixin::TYPES.key?(key)
  ResponderMixin::TYPES[key][:transform_method]
end

.on_jruby?Boolean

:api: plugin

Returns:

  • (Boolean)


773
774
775
# File 'lib/merb-core.rb', line 773

def on_jruby?
  RUBY_PLATFORM =~ Merb::Const::JAVA_PLATFORM_REGEXP
end

.on_windows?Boolean

:api: plugin

Returns:

  • (Boolean)


778
779
780
# File 'lib/merb-core.rb', line 778

def on_windows?
  RUBY_PLATFORM =~ Merb::Const::WIN_PLATFORM_REGEXP
end

.orm_generator_scopeObject

Deprecated.


483
484
485
486
487
# File 'lib/merb-core.rb', line 483

def orm_generator_scope
  Merb.logger.warn!("WARNING: Merb.orm_generator_scope is deprecated!")
  return :merb_default if Merb.orm == :none
  Merb.orm
end

Print a colorized backtrace to the merb logger.

:api: private



456
457
458
459
460
461
462
463
464
465
466
467
# File 'lib/merb-core.rb', line 456

def print_colorized_backtrace(e)
  e.backtrace.map! do |line|
    line.gsub!(/^#{Merb.framework_root}/, "\e[34mFRAMEWORK_ROOT\e[31m")
  end
  
  Merb.logger.fatal! "\e[34mFRAMEWORK_ROOT\e[0m = #{Merb.framework_root}"
  Merb.logger.fatal!
  Merb.logger.fatal! "\e[31m#{e.class}: \e[1;31;47m#{e.message}\e[0m"
  e.backtrace.each do |line|
    Merb.logger.fatal! "\e[31m#{line}\e[0m"
  end      
end

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

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



260
261
262
263
# File 'lib/merb-core.rb', line 260

def push_path(type, path, file_glob = "**/*.rb")
  enforce!(type => Symbol)
  load_paths[type] = [path, file_glob]
end

.rakefilesObject

Returns

Array(String)

Paths Rakefiles are loaded from.

Notes

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

:api: public



715
716
717
# File 'lib/merb-core.rb', line 715

def rakefiles
  @rakefiles ||= []
end

.reloadObject

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

:api: public



616
617
618
# File 'lib/merb-core.rb', line 616

def reload
  Merb::BootLoader::ReloadClasses.reload
end

.remove_mime_type(key) ⇒ Object

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

Parameters

key<Symbol>

The key that represents the mime-type to remove.

Returns

(Boolean, Hash=> 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



114
115
116
117
# File 'lib/merb-core/controller/mime.rb', line 114

def remove_mime_type(key)
  return false if key == :all
  ResponderMixin::TYPES.delete(key)
end

.remove_paths(*args) ⇒ Object

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



283
284
285
# File 'lib/merb-core.rb', line 283

def remove_paths(*args)
  args.each {|arg| load_paths.delete(arg)}
end

.reset_logger!Object

Removes the logger for the current thread (nil).

:api: public



354
355
356
# File 'lib/merb-core.rb', line 354

def reset_logger!
  Thread.current[:merb_logger] = nil
end

.restart_environment(argv = {}) ⇒ Object

Restart the Merb environment explicitly.

Parameters

argv<String, Hash>

The config arguments to restart Merb with. Defaults to Merb::Config.

:api: public



192
193
194
195
# File 'lib/merb-core.rb', line 192

def restart_environment(argv={})
  @started = false
  start_environment(Merb::Config.to_hash.merge(argv))
end

.rootObject

Returns

String

The Merb root path.

:api: public



313
314
315
# File 'lib/merb-core.rb', line 313

def root
  @root || Merb::Config[:merb_root] || File.expand_path(Dir.pwd)
end

.root=(value) ⇒ Object

Parameters

value<String>

Path to the root directory.

:api: public



321
322
323
# File 'lib/merb-core.rb', line 321

def root=(value)
  @root = value
end

.root_path(*path) ⇒ Object

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"


339
340
341
# File 'lib/merb-core.rb', line 339

def root_path(*path)
  File.join(root, *path)
end

.start(argv = ARGV) ⇒ Object

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



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/merb-core.rb', line 147

def start(argv = ARGV)
  Merb::Config[:original_log_stream] = Merb::Config[:log_stream]
  Merb::Config[:log_stream] ||= STDOUT
  if Hash === argv
    Merb::Config.setup(argv)
  elsif !argv.nil?
    Merb::Config.parse_args(argv)
  end

  Merb::Config[:log_stream] = STDOUT
  
  Merb.environment = Merb::Config[:environment]
  Merb.root = Merb::Config[:merb_root]

  case Merb::Config[:action]
  when :kill
    Merb::Server.kill(Merb::Config[:port], 2)
  when :kill_9
    Merb::Server.kill(Merb::Config[:port], 9)
  when :fast_deploy
    Merb::Server.kill("main", "HUP")
  else
    Merb::Server.start(Merb::Config[:port], Merb::Config[:cluster])
    @started = true
  end
end

.start_environment(argv = ARGV) ⇒ Object

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



181
182
183
# File 'lib/merb-core.rb', line 181

def start_environment(argv=ARGV)
  start(argv) unless (@started ||= false)
end

.test_framework_generator_scopeObject

Deprecated.


500
501
502
503
# File 'lib/merb-core.rb', line 500

def test_framework_generator_scope
  Merb.logger.warn!("WARNING: Merb.test_framework_generator_scope is deprecated")
  Merb.test_framework
end

.testing?Boolean

Returns

Boolean

True if Merb environment is testing for instance,

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

:api: public

Returns:

  • (Boolean)


625
626
627
# File 'lib/merb-core.rb', line 625

def testing?
  $TESTING ||= env?(:test) || Merb::Config[:testing]
end

.trap(signal, &block) ⇒ Object

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



761
762
763
764
765
# File 'lib/merb-core.rb', line 761

def trap(signal, &block)
  if Signal.list.include?(signal)
    Kernel.trap(signal, &block) unless Merb.disabled?(:signals)
  end
end