File: parser.rb

package info (click to toggle)
ruby-jsonapi-renderer 0.1.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 80 kB
  • sloc: ruby: 238; makefile: 3
file content (65 lines) | stat: -rw-r--r-- 1,565 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
module JSONAPI
  class IncludeDirective
    # Utilities to create an IncludeDirective hash from various types of
    # inputs.
    module Parser
      module_function

      # @api private
      def parse_include_args(include_args)
        case include_args
        when Symbol
          { include_args => {} }
        when Hash
          parse_hash(include_args)
        when Array
          parse_array(include_args)
        when String
          parse_string(include_args)
        else
          {}
        end
      end

      # @api private
      def parse_string(include_string)
        include_string.split(',')
          .each_with_object({}) do |path, hash|
            deep_merge!(hash, parse_path_string(path))
        end
      end

      # @api private
      def parse_path_string(include_path)
        include_path.split('.')
          .reverse
          .reduce({}) { |a, e| { e.to_sym => a } }
      end

      # @api private
      def parse_hash(include_hash)
        include_hash.each_with_object({}) do |(key, value), hash|
          hash[key.to_sym] = parse_include_args(value)
        end
      end

      # @api private
      def parse_array(include_array)
        include_array.each_with_object({}) do |x, hash|
          deep_merge!(hash, parse_include_args(x))
        end
      end

      # @api private
      def deep_merge!(src, ext)
        ext.each do |k, v|
          if src[k].is_a?(Hash) && v.is_a?(Hash)
            deep_merge!(src[k], v)
          else
            src[k] = v
          end
        end
      end
    end
  end
end