File: data.rb

package info (click to toggle)
ruby-app-store-connect 0.38.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 516 kB
  • sloc: ruby: 1,193; makefile: 4
file content (63 lines) | stat: -rw-r--r-- 1,533 bytes parent folder | download
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
# frozen_string_literal: true

require 'active_support/concern'

module AppStoreConnect
  module Object
    module Data
      extend ActiveSupport::Concern

      included do
        attr_reader :data

        klass = Class.new do |data|
          include Object::DataType
          include Object::Attributes
          include Object::Type
          include Object::Id

          data.send(:define_method, :initialize) do |**kwargs|
            instance_variable_set('@relationships', kwargs.delete(:relationships).to_h)
            instance_variable_set('@data', Array(kwargs.delete(:data)))
            instance_variable_set('@attributes', data::Attributes.new(**kwargs))
            instance_variable_set('@id', kwargs[id_arg_name])
          end

          def to_h
            props = {
              relationships: @relationships,
              attributes: attributes.to_h,
              type: type
            }
            props[:id] = @id if id?
            props.reject { |_k, v| v.blank? }
          end

          def to_a
            @data.each do |item|
              item[:type] = type
            end
            @data
          end

          def to_data_type
            if data_type == Array
              to_a
            else
              to_h
            end
          end
        end

        const_set('Data', klass)
      end

      class_methods do
        def data(type = Hash, &block)
          self::Data.data_type = type
          self::Data.class_eval(&block)
        end
      end
    end
  end
end