Sha256: c9639705d29301f0a9c39608a892ea7c912a724ad80facbff7c54d9b6d841cf4

Contents?: true

Size: 1.42 KB

Versions: 49

Compression:

Stored size: 1.42 KB

Contents

module LHS::Problems
  module Nested
    module Base
      # Filters base errors by scope
      # and reduces key by given scope name;
      # returns plain array if end of tree is reached
      def nest(messages, scope = nil)
        scope = translate_rails_to_api_scope(scope)
        return messages unless scope
        messages = messages.select do |key, _|
          key.match(/^#{scope}/)
        end
        # if only one key and this key has no dots, exit with plain
        if reached_leaf?(messages)
          messages.first[1]
        else
          remove_scope(messages, scope)
        end
      end

      # Identifies if the end of nested errors tree is reached
      def reached_leaf?(messages)
        messages.keys.length == 1 &&
          !messages.first[0].match(/\./)
      end

      # Removes scope from given messages' key
      def remove_scope(messages, scope)
        messages.each_with_object({}) do |element, hash|
          key = element[0].to_s.gsub(/^#{scope}\./, '')
          hash[key.to_sym] = element[1]
        end
      end

      # Translates rails like accessors for collections
      # like first, second, last to api error paths
      def translate_rails_to_api_scope(scope)
        case scope
        when :first
          0
        when :second
          1
        when :last
          return values.length - 1 if messages.present?
          0
        else
          scope
        end
      end
    end
  end
end

Version data entries

49 entries across 49 versions & 1 rubygems

Version Path
lhs-16.1.5 lib/lhs/problems/nested/base.rb
lhs-16.1.4 lib/lhs/problems/nested/base.rb
lhs-16.1.3 lib/lhs/problems/nested/base.rb
lhs-16.1.2 lib/lhs/problems/nested/base.rb
lhs-16.1.1 lib/lhs/problems/nested/base.rb
lhs-16.1.0 lib/lhs/problems/nested/base.rb
lhs-16.0.1 lib/lhs/problems/nested/base.rb
lhs-16.0.0 lib/lhs/problems/nested/base.rb
lhs-15.7.0 lib/lhs/problems/nested/base.rb
lhs-15.6.1 lib/lhs/problems/nested/base.rb
lhs-15.6.0 lib/lhs/problems/nested/base.rb
lhs-15.5.1 lib/lhs/problems/nested/base.rb
lhs-15.5.0 lib/lhs/problems/nested/base.rb
lhs-15.4.1 lib/lhs/problems/nested/base.rb
lhs-15.4.0 lib/lhs/problems/nested/base.rb
lhs-15.4.0.pre.hasone.1 lib/lhs/problems/nested/base.rb
lhs-15.3.3 lib/lhs/problems/nested/base.rb
lhs-15.3.3.pre.fixoptions.1 lib/lhs/problems/nested/base.rb
lhs-15.3.2 lib/lhs/problems/nested/base.rb
lhs-15.3.1 lib/lhs/problems/nested/base.rb