Skip to content

Instantly share code, notes, and snippets.

@ericmoritz
Created July 21, 2011 19:09
Show Gist options
  • Select an option

  • Save ericmoritz/1097946 to your computer and use it in GitHub Desktop.

Select an option

Save ericmoritz/1097946 to your computer and use it in GitHub Desktop.
Fun with crossbreeding.
from guard import Guard
import webob
from webob import Request
import webob.exc
def method(*method_list):
def inner(request, *args, **kwargs):
return request.method in method_list
return inner
def method_authorized(*method_list):
def inner(request, *args, **kwargs):
return method(*method_list)(request, *args, **kwargs)\
and request.remote_user is not None
return inner
def method_unauthorized(*method_list):
def inner(request, *args, **kwargs):
return method(*method_list)(request, *args, **kwargs)\
and request.remote_user is None
return inner
view = Guard()
@view.when(method("GET"))
def _(request):
print "GET"
@view.when(method_authorized("PUT"))
def _(request):
print "PUT"
@view.when(method_authorized("DELETE"))
def _(request):
print "DELETE"
@view.when(method_unauthorized("PUT", "DELETE"))
def _(request):
raise webob.exc.HTTPUnauthorized()
@view.otherwise
def _(request):
raise webob.exc.HTTPNotImplemented()
view(webob.Request.blank("/", method="GET"))
view(Request.blank("/", method="PUT", remote_user="eric"))
view(Request.blank("/", method="DELETE", remote_user="eric"))
try:
view(webob.Request.blank("/", method="PUT"))
assert False
except webob.exc.HTTPUnauthorized, error:
print error.status
try:
view(webob.Request.blank("/", method="DELETE"))
assert False
except webob.exc.HTTPUnauthorized, error:
print error.status
try:
view(webob.Request.blank("/", method="POST"))
assert False
except webob.exc.HTTPNotImplemented, error:
print error.status
from guard import Guard
factoral = Guard()
@factoral.when(lambda n, accum=1: n <= 1)
def factoral(n, accum=1):
return accum
@factoral.otherwise
def factoral(n, accum=1):
return factoral(n - 1, accum * n)
import webob
from webob import Request
import webob.exc
class NoMatch(Exception):
pass
class Guard(object):
def __init__(self):
self.case_list = []
self._otherwise = None
def when(self, test):
def dec(function):
self.case_list.append((test, function))
return self
return dec
def otherwise(self, function):
self._otherwise = function
return self
def __call__(self, *args, **kwargs):
for test, function in self.case_list:
if(test(*args, **kwargs)):
return function(*args, **kwargs)
if self._otherwise:
return self._otherwise(*args, **kwargs)
raise NoMatch()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment