Home > Software design >  Refactoring processing of JSON attributes
Refactoring processing of JSON attributes

Time:11-28

In an API processing a large number of attributes, the following pattern is frequent

      if !article[:ingredients].nil?
        clean_ingredients = article[:ingredients].tr('*$ !@#Â', ' ')
        ingredients = clean_ingredients.downcase.capitalize
      else
        ingredients = nil
      end

for a JSON string as: { "id": "YYYYYY", "article": [ { "ingredients": "long string", [...]
Unfortunately, a method defined as

  def empty_and_clean(array_element, element_attribute)
      if !array_element[:element_attribute].nil?
        clean_ingredients = array_element[:element_attribute].tr('*$ !@#Â', ' ')
        ingredients = clean_ingredients.downcase.capitalize
      else
        ingredients = nil
      end  
  end

cannot be called in the method as empty_and_clean(article, ingredients) as it returns
undefined local variable or method 'ingredients'

What syntax allows to refactor this pattern?

CodePudding user response:

You can call your empty_and_clean method this way:

empty_and_clean(article, :ingredients)

Just modify empty_and_clean to use element_attribute directly rather than the symbol :element_attribute.

I suggest you read more about symbols in Ruby to understand how this works.

Also, array_element is a misleading name because it is an array, not an element of an array. array would be slightly better, but is still too generic. Maybe objects or something else that describes what is actually in the array.

  • Related