Skip to content

Commit a528def

Browse files
authored
Merge pull request #36 from a1d4r/fix_blacklist
Fix bug when field gets converted to blacklisted word
2 parents 62d77e6 + 2b7d331 commit a528def

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

json_to_models/models/base.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -105,11 +105,11 @@ def __init__(
105105

106106
@cached_method
107107
def convert_class_name(self, name):
108-
return prepare_label(name, convert_unicode=self.convert_unicode)
108+
return prepare_label(name, convert_unicode=self.convert_unicode, to_snake_case=False)
109109

110110
@cached_method
111111
def convert_field_name(self, name):
112-
return inflection.underscore(prepare_label(name, convert_unicode=self.convert_unicode))
112+
return prepare_label(name, convert_unicode=self.convert_unicode, to_snake_case=True)
113113

114114
def generate(self, nested_classes: List[str] = None, bases: str = None, extra: str = "") \
115115
-> Tuple[ImportPathList, str]:
@@ -279,13 +279,15 @@ def sort_kwargs(kwargs: dict, ordering: Iterable[Iterable[str]]) -> dict:
279279
return sorted_dict
280280

281281

282-
def prepare_label(s: str, convert_unicode: bool) -> str:
283-
if s in blacklist_words:
284-
s += "_"
282+
def prepare_label(s: str, convert_unicode: bool, to_snake_case: bool) -> str:
285283
if convert_unicode:
286284
s = unidecode(s)
287285
s = re.sub(r"\W", "", s)
288286
if not ('a' <= s[0].lower() <= 'z'):
289287
if '0' <= s[0] <= '9':
290288
s = ones[int(s[0])] + "_" + s[1:]
289+
if to_snake_case:
290+
s = inflection.underscore(s)
291+
if s in blacklist_words:
292+
s += "_"
291293
return s

test/test_code_generation/test_attrs_generation.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ def test_attrib_kwargs_sort():
2929
assert 0, "XPass"
3030

3131

32-
3332
def field_meta(original_name):
3433
return f"metadata={{'{METADATA_FIELD_NAME}': '{original_name}'}}"
3534

@@ -90,6 +89,7 @@ class Test:
9089
"qwerty": FloatString,
9190
"asdfg": DOptional(int),
9291
"dict": DDict(int),
92+
"ID": int,
9393
"not": bool,
9494
"1day": int,
9595
"день_недели": str,
@@ -125,6 +125,11 @@ class Test:
125125
"type": "Dict[str, int]",
126126
"body": f"attr.ib({field_meta('dict')})"
127127
},
128+
"ID": {
129+
"name": "id_",
130+
"type": "int",
131+
"body": f"attr.ib({field_meta('ID')})"
132+
},
128133
"not": {
129134
"name": "not_",
130135
"type": "bool",
@@ -155,6 +160,7 @@ class Test:
155160
foo: int = attr.ib()
156161
qwerty: FloatString = attr.ib()
157162
dict_: Dict[str, int] = attr.ib({field_meta('dict')})
163+
id_: int = attr.ib({field_meta('ID')})
158164
not_: bool = attr.ib({field_meta('not')})
159165
one_day: int = attr.ib({field_meta('1day')})
160166
den_nedeli: str = attr.ib({field_meta('день_недели')})

0 commit comments

Comments
 (0)