Module Kernel
In: merb-core/lib/merb-core/core_ext/kernel.rb
merb-core/lib/merb-core/test/test_ext/rspec.rb

Methods

Public Instance methods

@param i<Fixnum> The caller number. Defaults to 1.

@return <Array[Array]> The file, line and method of the caller.

@example

  __caller_info__(1)
    # => ['/usr/lib/ruby/1.8/irb/workspace.rb', '52', 'irb_binding']

:api: private

[Source]

     # File merb-core/lib/merb-core/core_ext/kernel.rb, line 342
342:   def __caller_info__(i = 1)
343:     file, line, meth = caller[i].scan(/(.*?):(\d+):in `(.*?)'/).first
344:   end

@param file<String> The file to read. @param line<Fixnum> The line number to look for. @param size<Fixnum>

  Number of lines to include above and below the the line to look for.
  Defaults to 4.

@return <Array[Array]>

  Triplets containing the line number, the line and whether this was the
  searched line.

@example

  __caller_lines__('/usr/lib/ruby/1.8/debug.rb', 122, 2) # =>
    [
      [ 120, "  def check_suspend",                               false ],
      [ 121, "    return if Thread.critical",                     false ],
      [ 122, "    while (Thread.critical = true; @suspend_next)", true  ],
      [ 123, "      DEBUGGER__.waiting.push Thread.current",      false ],
      [ 124, "      @suspend_next = false",                       false ]
    ]

:api: private

[Source]

     # File merb-core/lib/merb-core/core_ext/kernel.rb, line 367
367:   def __caller_lines__(file, line, size = 4)
368:     line = line.to_i
369:     if file =~ /\(erubis\)/
370:       yield :error, "Template Error! Problem while rendering", false
371:     elsif !File.file?(file) || !File.readable?(file)
372:       yield :error, "File `#{file}' not available", false
373:     else
374:       lines = File.read(file).split("\n")
375:       first_line = (f = line - size - 1) < 0 ? 0 : f
376:       
377:       if first_line.zero?
378:         new_size = line - 1
379:         lines = lines[first_line, size + new_size + 1]
380:       else
381:         new_size = nil
382:         lines = lines[first_line, size * 2 + 1]
383:       end
384: 
385:       lines && lines.each_with_index do |str, index|
386:         line_n = index + line
387:         line_n = (new_size.nil?) ? line_n - size : line_n - new_size
388:         yield line_n, str.chomp
389:       end
390:     end
391:   end

Takes a block, profiles the results of running the block specified number of times and generates HTML report.

@param name<to_s>

  The file name. The result will be written out to
  Merb.root/"log/#{name}.html".

@param min<Fixnum>

  Minimum percentage of the total time a method must take for it to be
  included in the result. Defaults to 1.

@return <String>

  The result of the profiling.

@note

  Requires ruby-prof (<tt>sudo gem install ruby-prof</tt>)

@example

  __profile__("MyProfile", 5, 30) do
    rand(10)**rand(10)
    puts "Profile run"
  end

  Assuming that the total time taken for #puts calls was less than 5% of the
  total time to run, #puts won't appear in the profile report.
  The code block will be run 30 times in the example above.

:api: private

[Source]

     # File merb-core/lib/merb-core/core_ext/kernel.rb, line 420
420:   def __profile__(name, min=1, iter=100)
421:     require 'ruby-prof' unless defined?(RubyProf)
422:     return_result = ''
423:     result = RubyProf.profile do
424:       iter.times{return_result = yield}
425:     end
426:     printer = RubyProf::GraphHtmlPrinter.new(result)
427:     path = File.join(Merb.root, 'log', "#{name}.html")
428:     File.open(path, 'w') do |file|
429:       printer.print(file, {:min_percent => min,
430:                       :print_file => true})
431:     end
432:     return_result
433:   end

Define debugger method so that code even works if debugger was not requested. Drops a note to the logs that Debugger was not available.

[Source]

     # File merb-core/lib/merb-core/core_ext/kernel.rb, line 471
471:     def debugger
472:       Merb.logger.info! "\n***** Debugger requested, but was not " +
473:         "available: Start server with --debugger " +
474:         "to enable *****\n"
475:     end

Loads both gem and library dependencies that are passed in as arguments. Execution is deferred to the Merb::BootLoader::Dependencies.run during bootup.

Parameters

*args<String, Hash, Array> The dependencies to load.

Returns

Array[(Gem::Dependency, Array[Gem::Dependency])]:Gem::Dependencies for the
  dependencies specified in args.

:api: public

[Source]

     # File merb-core/lib/merb-core/core_ext/kernel.rb, line 185
185:   def dependencies(*args)
186:     args.map do |arg|
187:       case arg
188:       when String then dependency(arg)
189:       when Hash   then arg.map { |r,v| dependency(r, v) }
190:       when Array  then arg.map { |r|   dependency(r)    }
191:       end
192:     end
193:   end

Loads the given string as a gem. Execution is deferred until after the logger has been instantiated and the framework directory structure is defined.

If that has already happened, the gem will be activated immediately, but it will still be registered.

Parameters

name<String> The name of the gem to load. *ver<Gem::Requirement, Gem::Version, Array, to_str>

  Version requirements to be passed to Gem::Dependency.new.
  If the last argument is a Hash, extract the :immediate option,
  forcing a dependency to load immediately.

Options

:immediate when true, gem is loaded immediately even if framework is not yet ready. :require_as file name to require for this gem.

See examples below.

Notes

If block is given, it is called after require is called. If you use a block to require multiple files, require first using :require_as option and the rest in the block.

Examples

Usage scenario is typically one of the following:

  1. Gem name and loaded file names are the same (ex.: amqp gem uses amqp.rb). In this case no extra options needed.

dependency "amqp"

  1. Gem name is different from the file needs to be required (ex.: ParseTree gem uses parse_tree.rb as main file).

dependency "ParseTree", :require_as => "parse_tree"

  1. You need to require a number of files from the library explicitly (ex.: cherry pick features from xmpp4r). Pass an array to :require_as.

dependency "xmpp4r", :require_as => %w(xmpp4r/client xmpp4r/sasl xmpp4r/vcard)

  1. You need to require a specific version of the gem.

dependency "RedCloth", "3.0.4"

  1. You want to load dependency as soon as the method is called.

dependency "syslog", :immediate => true

  1. You need to execute some arbitraty code after dependency is loaded:

dependency "ruby-growl" do

  g = Growl.new "localhost", "ruby-growl",
             ["ruby-growl Notification"]
  g.notify "ruby-growl Notification", "Ruby-Growl is set up",
        "Ruby-Growl is set up"

end

When specifying a gem version to use, you can use the same syntax RubyGems support, for instance, >= 3.0.2 or >~ 1.2.

See rubygems.org/read/chapter/16 for a complete reference.

Returns

Gem::Dependency:The dependency information.

:api: public

[Source]

     # File merb-core/lib/merb-core/core_ext/kernel.rb, line 111
111:   def dependency(name, *opts, &blk)
112:     immediate = opts.last.delete(:immediate) if opts.last.is_a?(Hash)
113:     if immediate || Merb::BootLoader.finished?(Merb::BootLoader::Dependencies)
114:       load_dependency(name, caller, *opts, &blk)
115:     else
116:       track_dependency(name, caller, *opts, &blk)
117:     end
118:   end

Checks that the given objects quack like the given conditions.

@param opts<Hash>

  Conditions to enforce. Each key will receive a quacks_like? call with the
  value (see Object#quacks_like? for details).

@raise <ArgumentError>

  An object failed to quack like a condition.

:api: public

[Source]

     # File merb-core/lib/merb-core/core_ext/kernel.rb, line 461
461:   def enforce!(opts = {})
462:     opts.each do |k,v|
463:       raise ArgumentError, "#{k.inspect} doesn't quack like #{v.inspect}" unless k.quacks_like?(v)
464:     end
465:   end

Extracts an options hash if it is the last item in the args array. Used internally in methods that take *args.

@param args<Array> The arguments to extract the hash from.

@example

  def render(*args,&blk)
    opts = extract_options_from_args!(args) || {}
    # [...]
  end

:api: public

[Source]

     # File merb-core/lib/merb-core/core_ext/kernel.rb, line 447
447:   def extract_options_from_args!(args)
448:     args.pop if (args.last.instance_of?(Hash) || args.last.instance_of?(Mash))
449:   end

[Source]

    # File merb-core/lib/merb-core/test/test_ext/rspec.rb, line 3
 3:   def given(*args, &example_group_block)
 4:     args << {} unless Hash === args.last
 5:     params = args.last
 6:     
 7:     params[:shared] = true
 8:     
 9:     describe(*args) do
10:       prepend_before(:each) do
11:         self.instance_eval(&example_group_block)
12:       end
13:     end
14:   end

Loads both gem and library dependencies that are passed in as arguments.

@param *args<String, Hash, Array> The dependencies to load.

@note

  Each argument can be:
  String:: Single dependency.
  Hash::
    Multiple dependencies where the keys are names and the values versions.
  Array:: Multiple string dependencies.

@example dependencies "RedCloth" # Loads the the RedCloth gem @example dependencies "RedCloth", "merb_helpers" # Loads RedCloth and merb_helpers @example dependencies "RedCloth" => "3.0" # Loads RedCloth 3.0

:api: private

[Source]

     # File merb-core/lib/merb-core/core_ext/kernel.rb, line 211
211:   def load_dependencies(*args)
212:     args.map do |arg|
213:       case arg
214:       when String then load_dependency(arg)
215:       when Hash   then arg.map { |r,v| load_dependency(r, v) }
216:       when Array  then arg.map { |r|   load_dependency(r)    }
217:       end
218:     end
219:   end

Loads the given string as a gem.

This new version tries to load the file via ROOT/gems first before moving off to the system gems (so if you have a lower version of a gem in ROOT/gems, it‘ll still get loaded).

@param name<String,Gem::Dependency>

  The name or dependency object of the gem to load.

@param *ver<Gem::Requirement, Gem::Version, Array, to_str>

  Version requirements to be passed to Gem.activate.

@note

  If the gem cannot be found, the method will attempt to require the string
  as a library.

@return <Gem::Dependency> The dependency information.

:api: private

[Source]

     # File merb-core/lib/merb-core/core_ext/kernel.rb, line 138
138:   def load_dependency(name, clr, *ver, &blk)
139:     begin
140:       dep = name.is_a?(Gem::Dependency) ? name : track_dependency(name, clr, *ver, &blk)
141:       return unless dep.require_as
142:       Gem.activate(dep)
143:     rescue Gem::LoadError => e
144:       begin
145:         Merb.logger.debug "Falling back to a regular require"
146:         if name.kind_of?(Gem::Dependency)
147:           require name.name
148:         else
149:           require name
150:         end 
151:       rescue LoadError => le
152:         e.set_backtrace dep.original_caller
153:         Merb.fatal! "The gem #{name}, #{ver.inspect} was not found and we could not require it"
154:       end 
155:     end
156:   
157:     begin
158:       require dep.require_as
159:     rescue LoadError => e
160:       e.set_backtrace dep.original_caller
161:       Merb.fatal! "The file #{dep.require_as} was not found", e
162:     end
163: 
164:     if block = dep.require_block
165:       # reset the require block so it doesn't get called a second time
166:       dep.require_block = nil
167:       block.call
168:     end
169: 
170:     Merb.logger.verbose!("loading gem '#{dep.name}' ...")
171:     return dep # ensure needs explicit return
172:   end

Does a basic require, and prints a message if an error occurs.

@param library<to_s> The library to attempt to include. @param message<String> The error to add to the log upon failure. Defaults to nil.

:api: private @deprecated

[Source]

     # File merb-core/lib/merb-core/core_ext/kernel.rb, line 228
228:   def rescue_require(library, message = nil)
229:     Merb.logger.warn("Deprecation warning: rescue_require is deprecated")
230:     sleep 2.0
231:     require library
232:   rescue LoadError, RuntimeError
233:     Merb.logger.error!(message) if message
234:   end

Keep track of all required dependencies.

@param name<String> The name of the gem to load. @param *ver<Gem::Requirement, Gem::Version, Array, to_str>

  Version requirements to be passed to Gem::Dependency.new.

@return <Gem::Dependency> Dependency information

:api: private

[Source]

    # File merb-core/lib/merb-core/core_ext/kernel.rb, line 21
21:   def track_dependency(name, clr, *ver, &blk)
22:     options = ver.last.is_a?(Hash) ? ver.pop : {}
23:     new_dep = Gem::Dependency.new(name, ver.empty? ? nil : ver)
24:     new_dep.require_block = blk
25:     new_dep.require_as = options.key?(:require_as) ? options[:require_as] : name
26:     new_dep.original_caller = clr
27:     
28:     deps = Merb::BootLoader::Dependencies.dependencies
29: 
30:     idx = deps.each_with_index {|d,i| break i if d.name == new_dep.name}
31: 
32:     idx = idx.is_a?(Array) ? deps.size + 1 : idx
33:     deps.delete_at(idx)
34:     deps.insert(idx - 1, new_dep)
35: 
36:     new_dep
37:   end

Used in Merb.root/config/init.rb to tell Merb which ORM (Object Relational Mapper) you wish to use. Currently Merb has plugins to support ActiveRecord, DataMapper, and Sequel.

Parameters

orm<Symbol>:The ORM to use.

Returns

nil

Example

  use_orm :datamapper

  # This will use the DataMapper generator for your ORM
  $ merb-gen model ActivityEvent

Notes

  If for some reason this is called more than once, latter
  call takes over other.

:api: public

[Source]

     # File merb-core/lib/merb-core/core_ext/kernel.rb, line 257
257:   def use_orm(orm, &blk)
258:     begin
259:       Merb.orm = orm
260:       orm_plugin = "merb_#{orm}"
261:       Kernel.dependency(orm_plugin, &blk)
262:     rescue LoadError => e
263:       Merb.logger.warn!("The #{orm_plugin} gem was not found.  You may need to install it.")
264:       raise e
265:     end
266:     nil
267:   end

Used in Merb.root/config/init.rb to tell Merb which template engine to prefer.

Parameters

template_engine<Symbol>

  The template engine to use.

Returns

nil

Example

  use_template_engine :haml

  # This will now use haml templates in generators where available.
  $ merb-gen resource_controller Project

:api: public

[Source]

     # File merb-core/lib/merb-core/core_ext/kernel.rb, line 314
314:   def use_template_engine(template_engine, &blk)
315:     Merb.template_engine = template_engine
316: 
317:     if template_engine != :erb
318:       if template_engine.in?(:haml, :builder)
319:         template_engine_plugin = "merb-#{template_engine}"
320:       else
321:         template_engine_plugin = "merb_#{template_engine}"
322:       end
323:       Kernel.dependency(template_engine_plugin, &blk)
324:     end
325:     
326:     nil
327:   rescue LoadError => e
328:     Merb.logger.warn!("The #{template_engine_plugin} gem was not found.  You may need to install it.")
329:     raise e
330:   end

[Source]

     # File merb-core/lib/merb-core/core_ext/kernel.rb, line 293
293:   def use_test(*args)
294:     use_testing_framework(*args)
295:   end

Used in Merb.root/config/init.rb to tell Merb which testing framework to use. Currently Merb has plugins to support RSpec and Test::Unit.

Parameters

test_framework<Symbol>:The test framework to use. Currently only supports :rspec and :test_unit.

Returns

nil

Example

  use_test :rspec

  # This will now use the RSpec generator for tests
  $ merb-gen model ActivityEvent

:api: public

[Source]

     # File merb-core/lib/merb-core/core_ext/kernel.rb, line 286
286:   def use_testing_framework(test_framework, *test_dependencies)
287:     Merb.test_framework = test_framework
288:     
289:     Kernel.dependencies test_dependencies if Merb.env == "test" || Merb.env.nil?
290:     nil
291:   end

[Validate]