Module: Camping::Base

Defined in:
lib/camping-unabridged.rb,
lib/camping.rb

Overview

Camping::Base is built into each controller by way of the generic routing class Camping::R. In some ways, this class is trying to do too much, but it saves code for all the glue to stay in one place. Forgivable, considering that it’s only really a handful of methods and accessors.

Everything in this module is accessible inside your controllers.

Constant Summary collapse

T =
{}
L =
:layout

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



20
21
22
# File 'lib/camping.rb', line 20

def body
  @body
end

#cookiesObject

Returns the value of attribute cookies.



20
21
22
# File 'lib/camping.rb', line 20

def cookies
  @cookies
end

#envObject

Returns the value of attribute env.



20
21
22
# File 'lib/camping.rb', line 20

def env
  @env
end

#headersObject

Returns the value of attribute headers.



20
21
22
# File 'lib/camping.rb', line 20

def headers
  @headers
end

#inputObject

Returns the value of attribute input.



20
21
22
# File 'lib/camping.rb', line 20

def input
  @input
end

#requestObject

Returns the value of attribute request.



20
21
22
# File 'lib/camping.rb', line 20

def request
  @request
end

#rootObject

Returns the value of attribute root.



20
21
22
# File 'lib/camping.rb', line 20

def root
  @root
end

#stateObject

Returns the value of attribute state.



20
21
22
# File 'lib/camping.rb', line 20

def state
  @state
end

#statusObject

Returns the value of attribute status.



20
21
22
# File 'lib/camping.rb', line 20

def status
  @status
end

#url_prefixObject

Returns the value of attribute url_prefix.



20
21
22
# File 'lib/camping.rb', line 20

def url_prefix
  @url_prefix
end

Instance Method Details

#initialize(env, m, p) ⇒ Object

initialize Turns a camping controller class into an object and sets up the environment with input, cookies, state, headers, etc…



452
453
454
455
456
# File 'lib/camping-unabridged.rb', line 452

def initialize env,m,p
r=@request=Rack::Request.new(@env=env);@root,@input,@cookies,@state,@headers,
@status,@method,@url_prefix=r.script_name.sub(/\/$/,''),n(r.params),
Cookies[r.cookies],H[r.session[SK]||{}],{E=>Z},m=~/r(\d+)/?$1.to_i: 200,m,p
@cookies._p=self/"/";end

#lookup(n) ⇒ Object

Finds a template, returning either:

false             # => Could not find template
true              # => Found template in Views
instance of Tilt  # => Found template in a file


280
281
282
283
# File 'lib/camping-unabridged.rb', line 280

def lookup n;T.fetch(n.to_sym){|k|t=Views.
method_defined?(k)||(t=O[:_t].keys.grep(/^#{n}\./)[0]and Template[t].new{
O[:_t][t]})||(f=Dir[[O[:views]||"views","#{n}.*"]*'/'][0])&&Template.
new(f,O[f[/\.(\w+)$/,1].to_sym]||{});O[:dynamic_templates]?t: T[k]=t}end

#mab(&b) ⇒ Object

You can directly return HTML from your controller for quick debugging by calling this method and passing some Markaby to it.

module Nuts::Controllers
  class Info
    def get; mab{ code @headers.inspect } end
  end
end

You can also pass true to use the :layout HTML wrapping method



343
# File 'lib/camping-unabridged.rb', line 343

def mab(&b)extend Mab;mab(&b)end

#n(h) ⇒ Object

n method accepts parameters and converts them to a hash. helper method for initialize



465
# File 'lib/camping-unabridged.rb', line 465

def n h;Hash===h ?h.inject(H[]){|m,(k,v)|m[k]=n(v);m}: h end

#r(s, b, h = {}) ⇒ Object

A quick means of setting this controller’s status, body and headers based on a Rack response:

r(302, 'Location' => self / "/view/12", '')
r(*another_app.call(@env))

You can also switch the body and the header if you want:

r(404, "Could not find page")

See also: #r404, #r500 and #r501



359
# File 'lib/camping-unabridged.rb', line 359

def r s,b,h={};b,h=h,b if Hash===b;@status=s;@headers.merge!(h);@body=b end

#r404(p) ⇒ Object

Called when a controller was not found. You can override this if you want to customize the error page:

module Nuts
  def r404(path)
    @path = path
    render :not_found
  end
end


393
# File 'lib/camping-unabridged.rb', line 393

def r404 p;P%"#{p} not found"end

#r500(k, m, e) ⇒ Object

Called when an exception is raised. However, if there is a parse error in Camping or in your application’s source code, it will not be caught.

k is the controller class, m is the request method (GET, POST, etc.) and e is the Exception which can be mined for useful info.

By default this simply re-raises the error so a Rack middleware can handle it, but you are free to override it here:

module Nuts
  def r500(klass, method, exception)
    send_email_alert(klass, method, exception)
    render :server_error
  end
end


412
# File 'lib/camping-unabridged.rb', line 412

def r500 k,m,e;raise e end

#r501(m) ⇒ Object

Called if an undefined method is called on a controller, along with the request method m (GET, POST, etc.)



418
# File 'lib/camping-unabridged.rb', line 418

def r501 m;P % "#{m.upcase} not implemented"end

#redirect(*a) ⇒ Object

Formulate a redirect response: a 302 status with Location header and a blank body. Uses Helpers#URL to build the location from a controller route or path.

So, given a root of http://localhost:3301/articles:

redirect "view/12"  # redirects to "//localhost:3301/articles/view/12"
redirect View, 12   # redirects to "//localhost:3301/articles/view/12"

NOTE: This method doesn’t magically exit your methods and redirect. You’ll need to return redirect(...) if this isn’t the last statement in your code, or throw :halt if it’s in a helper.

See: Controllers



380
# File 'lib/camping-unabridged.rb', line 380

def redirect *a;r 302,'','Location'=>URL(*a).to_s;end

#render(v, *a, &b) ⇒ Object

Display a view, calling it by its method name v. If a layout method is found in Camping::Views, it will be used to wrap the HTML.

module Nuts::Controllers
  class Show
    def get
      @posts = Post.find :all
      render :index
    end
  end
end


319
320
321
322
# File 'lib/camping-unabridged.rb', line 319

def render v,*a,&b;if t=lookup(v);r=@_r;@_r=o=Hash===a[-1]?a.pop: {};s=(t==true)?mab{
send v,*a,&b}: t.render(self,o[:locals]||{},&b);s=render(L,o.merge(L=>false)){s
} if o[L] or o[L].nil?&&lookup(L)&&!r&&v.to_s[0]!=?_;s else raise "no template: #{v}"
end end

#serve(p, c) ⇒ Object

Serves the string c with the MIME type of the filename p. Defaults to text/html.



424
# File 'lib/camping-unabridged.rb', line 424

def serve p,c;t=Rack::Mime.mime_type(p[/\..*$/], Z)and@headers[E]=t;c;end

#service(*a) ⇒ Object

All requests pass through this method before going to the controller. Some magic in Camping can be performed by overriding this method.



478
# File 'lib/camping-unabridged.rb', line 478

def service *a;r=catch(:halt){send(@method,*a)};@body||=r;self end

#to_aObject

Turn a controller into a Rack response. This is designed to be used to pipe controllers into the r method. A great way to forward your requests!

class Read < '/(\d+)'
  def get(id)
    Post.find(id)
  rescue
    r *Blog.get(:NotFound, @headers.REQUEST_URI)
  end
end


440
441
# File 'lib/camping-unabridged.rb', line 440

def to_a;@env['rack.session'][SK]=Hash[@state];r=Rack::Response.new(@body,
@status,@headers);@cookies._n.each{|k,v|r.set_cookie k,v};r.to_a end