Class: Newman::Application

Inherits:
Object
  • Object
show all
Includes:
Filters
Defined in:
lib/newman/application.rb

Instance Method Summary collapse

Methods included from Filters

#subject, #to

Constructor Details

#initialize(&block) ⇒ Application

A ‘Newman::Application` object is a blank slate upon creation, with fields set to hold `callbacks`, `matchers`, and `extensions`. A block may optionally be provided, which then gets executed within the context of the newly created `Newman::Application` instance. This is the common way of building applications, and is demonstrated by the example below:

ping_pong = Newman::Application.new do
  subject("ping") do
    respond(:subject => "pong")
  end
end

Any method that can be called on a ‘Newman::Application` instance can be called within the provided block, including those methods mixed in by `Newman::Filters`.



32
33
34
35
36
37
38
# File 'lib/newman/application.rb', line 32

def initialize(&block)
  self.callbacks  = []
  self.matchers   = {}
  self.extensions = []

  instance_eval(&block) if block_given?
end

Instance Method Details

#call(params) ⇒ Object

‘Newman::Application#call` accepts a hash of parameters which gets used to create a new `Newman::Controller` object. The controller is then extended by all of the modules stored in the `extensions` field on the application object, and is finally passed along to `Newman::Application#trigger_callbacks`, which does the magical work of figuring out which callbacks to run, if any.

This method is meant to be run by a ‘Newman::Server` object, and isn’t especially useful on its own.



52
53
54
55
56
# File 'lib/newman/application.rb', line 52

def call(params)
  controller = Controller.new(params)      
  extensions.each { |mod| controller.extend(mod) }
  trigger_callbacks(controller)
end

#callback(action, filter) ⇒ Object

‘Newman::Application#callback` is a low level feature for defining custom callbacks. For ideas on how to roll your own filters with it, see the implementation of the `Newman::Filters` module.



189
190
191
192
# File 'lib/newman/application.rb', line 189

def callback(action, filter)
  callbacks << { :filter   => filter, 
                 :action   => action }
end

#compile_regex(pattern) ⇒ Object

‘Newman::Application#compile_regex` is used for converting pattern strings into a regular expression string suitable for use in filters. This method is a low-level feature, and is not meant for use by application developers. See the `Newman::Filters` module for how to use it to build your own callback filters.



202
203
204
205
# File 'lib/newman/application.rb', line 202

def compile_regex(pattern)
  Regexp.escape(pattern)
        .gsub(/\\{(.*?)\\}/) { |m| "(?<#{$1}>#{matchers[$1]})" } 
end

#default(&callback) ⇒ Object

‘Newman::Application#default` is used to define a default callback which will run when no other callbacks match the incoming request. For example, you can define a callback such as the one below:

default do
  respond(:subject => "REQUEST NOT UNDERSTOOD")
end

Unless you are building an application that will never fail to match at least one of its filters, you MUST set up a default callback if you want to avoid a possible application error. We know this is not exactly the most desireable behavior, and will try to fix this in a future version of Newman.



74
75
76
# File 'lib/newman/application.rb', line 74

def default(&callback)
  self.default_callback = callback
end

#helpers(&block) ⇒ Object

‘Newman::Application#helpers` is used to build simple controller extensions, and is mostly just syntactic sugar. For example, rather than using an explicit module, the example shown in the `Newman::Application#use` documentation can be rewritten as follows:

list_app = Newman::Application.new do
  helpers do
    def load_list(name)
      store = Newman::Store.new(settings.application.list_db)
      Newman::MailingList.new(name, store)
    end
  end

  match :list_id, "[^.]+"

  to(:tag, "{list_id}.subscribe") do
    list = load_list(params[:list_id])

    if list.subscriber?(sender)
      # send a failure message
    else
      # susbcribe the user and send a welcome message
    end
  end
end

It’s important to note that for any controller extensions that might be reusable, or for more complicated logic, ‘Newman::Application#use` is probably a better tool to use.



151
152
153
# File 'lib/newman/application.rb', line 151

def helpers(&block)
  use Module.new(&block)
end

#match(name, pattern) ⇒ Object

‘Newman::Application#match` is used to define patterns which are used for extracting callback parameters. An example is shown below:

jester = Newman::Application.new do
  match :genre, '\S+'
  match :title, '.*'

  subject(:match, "a {genre} story '{title}'") do
    story_library.add_story(:genre => params[:genre],
                            :title => params[:title],
                            :body => request.body.to_s)

    respond :subject => "Jester saved '#{params[:title]}'"
  end
end

Because Newman’s built in filters are designed to escape regular expression syntax by default, ‘Newman::Application#match` provides the only high-level mechanism for dynamic filter matches. Low level matching is possible via `Newman::Application#callback`, but would be an exercise in tedium for most application developers.



179
180
181
# File 'lib/newman/application.rb', line 179

def match(name, pattern)
  matchers[name] = pattern
end

#use(extension) ⇒ Object

‘Newman:::Application#use` is used to register the extension modules that get mixed in to the controller objects created by `Newman::Application#call`. This allows an application object to provide extensions for use within its callbacks, as in the example shown below.

module ListLoader
  def load_list(name)
    store = Newman::Store.new(settings.application.list_db)
    Newman::MailingList.new(name, store)
  end
end

list_app = Newman::Application.new do
  use ListLoader

  match :list_id, "[^.]+"

  to(:tag, "{list_id}.subscribe") do
    list = load_list(params[:list_id])

    if list.subscriber?(sender)
      # send a failure message
    else
      # susbcribe the user and send a welcome message
    end
  end
end

This method is mainly meant to be used with pre-packaged extensions or more complicated forms of callback helpers. This example was just shown for the sake of its simplicity, but for similar use cases it would actually be better to use ‘Newman::Application#helpers`



114
115
116
# File 'lib/newman/application.rb', line 114

def use(extension)
  extensions << extension
end