import webhelpers.rails.form_tag
# ModelWebHelpers
# It's often useful to have a simple way to say "if this variable actually is
# an instance of my model class, give me the value of such and such an attribute,
# otherwise give me an empty string." Rails has this with its FormHelper module,
# but until now, this has been lacking from WebHelpers. For an example, consider
# the following console session from a Pylons app:
# >>> p = model.Post.get(1)
# >>> p.title
# u'Hello World!'
# >>> h.m.text_field(p, 'title')
# ''
# >>> p = ''
# >>> h.m.text_field(p, 'title')
# ''
# The m object provides versions of most of the WebHelpers form tags that will "do
# the right thing". The select() helper provides some trouble, though, since the
# current value is set in the options, not on the actual select tag, and there are
# several different ways to generate the options tags. Therefore, the m object also
# provides a generic value() function that simply returns the value or the empty string,
# without any enclosing html tag. You could use this as follows:
# ${h.select('language', h.options_for_select(
# dict(German='de', Japanese='jp', English='en'),
# selected=h.m.value(p, 'lang')
# ))}
#
# Model instances are determined to be undefined if they are equivalent to any of the
# values in the class attribute caller.undefinedval. This is an array that by default
# contains only the empty string.
class caller(object):
undefinedval = ['']
def __init__(self, func, arg="value"):
self.func = func
self.arg = arg
def __call__(self, modelobj, name, *args, **kwargs):
if modelobj not in self.undefinedval:
if not hasattr(modelobj, name):
raise AttributeError
kwargs[self.arg] = getattr(modelobj, name)
elif kwargs.has_key('default'):
kwargs[self.arg] = kwargs['default']
if self.func is 'value':
return kwargs.get(self.arg, '')
return self.func(name, *args, **kwargs)
class M(object):
basehelpers = {}
for helper in ['text_field', 'hidden_field', 'file_field', 'password_field', 'text_area', 'check_box', 'radio_button']:
basehelpers[helper] = getattr(webhelpers.rails.form_tag, helper)
basehelpers['value'] = 'value'
def __getattr__(self, name):
if not self.basehelpers.has_key(name):
raise AttributeError
if name is 'text_area':
return caller(self.basehelpers[name], 'content')
return caller(self.basehelpers[name])
m = M()
# keep M, caller, and webhelpers from being imported when you import *
__all__ = ['m']