Class: Jabara::Transformer::Flatten

Inherits:
Object
  • Object
show all
Defined in:
lib/jabara/transformer/flatten.rb

Overview

TODO array と set のflat化は別クラスに責務を切り出した方がいいかも

Instance Method Summary collapse

Constructor Details

#initialize(id_key_name: 'id', index_key_name: 'index') ⇒ Flatten



8
9
10
11
# File 'lib/jabara/transformer/flatten.rb', line 8

def initialize(id_key_name: 'id', index_key_name: 'index')
  @id_key_name = id_key_name
  @index_key_name = index_key_name
end

Instance Method Details

#convert(object_repr) ⇒ Object

与えられたオブジェクトを第1正規化する



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
# File 'lib/jabara/transformer/flatten.rb', line 14

def convert(object_repr)
  new_repr_hash = {}
  divided_reprs = []

  id = ::Jabara.id(object_repr)
  ::Jabara.data(object_repr).each do |key, repr|
    data = ::Jabara.data(repr)
    if ::Jabara.primitive?(repr) then
      new_repr_hash[key] = repr
    else
      tag = ::Jabara.tag(repr)
      case tag
      when :object
        _object_repr = data
        ::Jabara.data(_object_repr)[@id_key_name] = id
        divided_reprs.push(_object_repr)
      when :array
        # TODO ヘテロな要素が来るケースへの対応
        # TODO primitiveな要素が来るケースへの対応

        ar = data
        ar.each_with_index do |_object_repr, index|
          ::Jabara.data(_object_repr)[@id_key_name] = id
          ::Jabara.data(_object_repr)[@index_key_name] = index
          divided_reprs.push(_object_repr)
        end
      when :set
        # TODO ヘテロな要素が来るケースへの対応
        # TODO primitiveな要素が来るケースへの対応

        st = data
        st.each do |_object_repr|
          ::Jabara.data(_object_repr)[@id_key_name] = id
          divided_reprs.push(_object_repr)
        end
      else
        raise ArgumentError, "Invalid tag was found :%s" % tag
      end
    end
  end

  ::Jabara.set_data(object_repr, new_repr_hash)
  return object_repr, divided_reprs
end