Skip to content

Commit

Permalink
[logic/converters] Add converter for tag string to tag with vocab
Browse files Browse the repository at this point in the history
  • Loading branch information
johnglover committed Jan 31, 2012
1 parent 2227d51 commit a411b14
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 5 deletions.
37 changes: 32 additions & 5 deletions ckan/logic/converters.py
@@ -1,18 +1,14 @@
from ckan.lib.navl.dictization_functions import Invalid
from ckan.lib.field_types import DateType, DateConvertError


from ckan.logic.validators import tag_length_validator, tag_name_validator

def convert_to_extras(key, data, errors, context):

extras = data.get(('extras',), [])
if not extras:
data[('extras',)] = extras

extras.append({'key': key[-1], 'value': data[key]})

def convert_from_extras(key, data, errors, context):

for data_key, data_value in data.iteritems():
if (data_key[0] == 'extras'
and data_key[-1] == 'key'
Expand All @@ -33,3 +29,34 @@ def date_to_form(value, context):
raise Invalid(str(e))
return value

def convert_to_tags(vocab):
def callable(key, data, errors, context):
tag_string = data.get(key)
new_tags = [tag.strip() for tag in tag_string.split(',') if tag.strip()]

if not new_tags:
return

# get current number of tags
n = 0
for k in data.keys():
if k[0] == 'tags':
n = max(n, k[1] + 1)

# validate
for tag in new_tags:
tag_length_validator(tag, context)
tag_name_validator(tag, context)

# add new tags
for num, tag in enumerate(new_tags):
data[('tags', num+n, 'name')] = tag
data[('tags', num+n, 'vocabulary')] = vocab

return callable

def convert_from_tags(vocab):
def callable(key, data, errors, context):
pass
return callable

20 changes: 20 additions & 0 deletions ckan/tests/logic/test_converters.py
@@ -0,0 +1,20 @@
from ckan import model
from ckan.logic.converters import convert_to_tags
from ckan.lib.navl.dictization_functions import unflatten

class TestConverters:
def test_convert_to_tags(self):
def convert(tag_string, vocab):
key = 'vocab_tag_string'
data = {key: tag_string}
errors = []
context = {'model': model, 'session': model.Session}
convert_to_tags('vocab')(key, data, errors, context)
del data[key]
return data

data = unflatten(convert('tag1, tag2', 'vocab'))
for tag in data['tags']:
assert tag['name'] in ['tag1', 'tag2']
assert tag['vocabulary'] == 'vocab'

0 comments on commit a411b14

Please sign in to comment.