Module: Tap::Ubiquity::Utils

Includes:
Controller::Extname
Included in:
Ubiquity
Defined in:
lib/tap/ubiquity/utils.rb

Overview

Utils provides methods for serving ubiquity commands that link back to actions on a controller.

:startdoc:::-

# ::controller
# ::ubiquity
class Sample < Tap::Controller
  include Ubiquity::Utils

  def commands
    serve command(:action)
  end

  def action
    input = request['input']
    request.get? ? "got: #{input}" : "received: #{input}"
  end
end

:startdoc:::+

Utils expects to be included in a Tap::Controller.

Instance Method Summary collapse

Instance Method Details

#command(action, cmd = {}) ⇒ Object

Returns a ubiquity command to redirect to action. The action may respond differentl to GET and POST requests; GET results will be displayed in the preview box and the browser will be redirected to view POST results.

The action will be called with an ‘input’ parameter that provides the currently selected text in the browser.

Example

class Sample < Tap::Controller
  include Ubiquity::Utils

  def commands
    serve command(:echo)
  end

  def echo
    input = request['input']
    request.get? ? "got: #{input}" : "received: #{input}"
  end
end

– TODO name should be minipath, not action



73
74
75
76
77
78
# File 'lib/tap/ubiquity/utils.rb', line 73

def command(action, cmd={})
  render 'command.js', :locals => {
    :cmd => {:name => action}.merge(cmd), 
    :uri => uri(:action => action)
  }
end

Returns the link tag for subscribing to a ubiquity command served from the specified action.



44
45
46
# File 'lib/tap/ubiquity/utils.rb', line 44

def command_link(href)
  "<link rel='commands' href='#{href}.js' />"
end

#js_injection(action, cmd = {}) ⇒ Object

Returns a ubiquity command to inject javascript into the current page. The javascript is returned by action and should have a ‘text/plain’ content type. The action may respond differently to GET and POST requests; GET results will be displayed in the preview box while POST results will actually be injected.

The action will be called with an ‘input’ parameter that provides the currently selected text in the browser.

Example

class Sample < Tap::Controller
  include Ubiquity::Utils

  def commands
    serve js_injection(:alert)
  end

  def alert
    response['Content-Type'] = 'text/plain'
    "alert('#{request['input']}')"
  end
end


104
105
106
107
108
109
# File 'lib/tap/ubiquity/utils.rb', line 104

def js_injection(action, cmd={})
  render 'js_injection.js', :locals => {
    :cmd => {:name => action}.merge(cmd), 
    :uri => uri(:action => action)
  }
end

#serve(command) ⇒ Object

Serves the command from the calling method.



32
33
34
35
36
37
38
39
40
# File 'lib/tap/ubiquity/utils.rb', line 32

def serve(command)
  if extname == '.js'
    response['Content-Type'] = 'application/x-javascript'
    command
  else
    caller[0] =~ /in\W+(\w+)\W$/
    "<pre>#{command}</pre>#{command_link(uri($1))}"
  end
end