| Conditions | 9 |
| Total Lines | 52 |
| Lines | 0 |
| Ratio | 0 % |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | # Licensed to the StackStorm, Inc ('StackStorm') under one or more |
||
| 130 | def render_values(mapping=None, context=None, allow_undefined=False): |
||
| 131 | """ |
||
| 132 | Render an incoming mapping using context provided in context using Jinja2. Returns a dict |
||
| 133 | containing rendered mapping. |
||
| 134 | |||
| 135 | :param mapping: Input as a dictionary of key value pairs. |
||
| 136 | :type mapping: ``dict`` |
||
| 137 | |||
| 138 | :param context: Context to be used for dictionary. |
||
| 139 | :type context: ``dict`` |
||
| 140 | |||
| 141 | :rtype: ``dict`` |
||
| 142 | """ |
||
| 143 | |||
| 144 | if not context or not mapping: |
||
| 145 | return mapping |
||
| 146 | |||
| 147 | # Add in special __context variable that provides an easy way to get access to entire context. |
||
| 148 | # This mean __context is a reserve key word although backwards compat is preserved by making |
||
| 149 | # sure that real context is updated later and therefore will override the __context value. |
||
| 150 | super_context = {} |
||
| 151 | super_context['__context'] = context |
||
| 152 | super_context.update(context) |
||
| 153 | |||
| 154 | env = get_jinja_environment(allow_undefined=allow_undefined) |
||
| 155 | rendered_mapping = {} |
||
| 156 | for k, v in six.iteritems(mapping): |
||
| 157 | # jinja2 works with string so transform list and dict to strings. |
||
| 158 | reverse_json_dumps = False |
||
| 159 | if isinstance(v, dict) or isinstance(v, list): |
||
| 160 | v = json.dumps(v) |
||
| 161 | reverse_json_dumps = True |
||
| 162 | else: |
||
| 163 | v = str(v) |
||
| 164 | |||
| 165 | try: |
||
| 166 | rendered_v = env.from_string(v).render(super_context) |
||
| 167 | except Exception as e: |
||
| 168 | # Attach key and value which failed the rendering |
||
| 169 | e.key = k |
||
| 170 | e.value = v |
||
| 171 | raise e |
||
| 172 | |||
| 173 | # no change therefore no templatization so pick params from original to retain |
||
| 174 | # original type |
||
| 175 | if rendered_v == v: |
||
| 176 | rendered_mapping[k] = mapping[k] |
||
| 177 | continue |
||
| 178 | if reverse_json_dumps: |
||
| 179 | rendered_v = json.loads(rendered_v) |
||
| 180 | rendered_mapping[k] = rendered_v |
||
| 181 | return rendered_mapping |
||
| 182 |