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.



193
194
195
196
# File 'lib/newman/application.rb', line 193

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.



206
207
208
209
# File 'lib/newman/application.rb', line 206

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.

NOTE: ‘Newman::Application#match` converts the provided `name` to a string using `to_s` to make life easier for the internals. Because `Newman::Application#matchers` is an implementation detail, you probably don’t need to worry about this unless you’re hacking on Newman itself.



183
184
185
# File 'lib/newman/application.rb', line 183

def match(name, pattern)
  matchers[name.to_s] = 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