Class: TypeStruct

Inherits:
Object show all
Defined in:
lib/type_struct.rb,
lib/type_struct/ext.rb,
lib/type_struct/union.rb,
lib/type_struct/hash_of.rb,
lib/type_struct/version.rb,
lib/type_struct/array_of.rb,
lib/type_struct/interface.rb

Defined Under Namespace

Modules: Unionable Classes: ArrayOf, HashOf, Interface, Union

Constant Summary collapse

UnionNotFoundError =
Class.new(StandardError)
VERSION =
"0.5.0"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(arg) ⇒ TypeStruct

Returns a new instance of TypeStruct.



10
11
12
13
14
15
16
17
18
# File 'lib/type_struct.rb', line 10

def initialize(arg)
  sym_arg = {}
  arg.each do |k, v|
    sym_arg[k.to_sym] = v
  end
  self.class.members.each do |k|
    self[k] = sym_arg[k]
  end
end

Class Method Details

.new(**args, &block) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/type_struct.rb', line 52

def new(**args, &block)
  c = Class.new(TypeStruct) do
    const_set :DEFINITION, args

    class << self
      alias_method :new, :original_new

      def from_hash(h)
        unless Hash === h
          h = h.to_hash if h.respond_to?(:to_hash)
          unless Hash === h
            raise TypeError, "#{self}.from_hash only accept Hash got `#{h.class}'"
          end
        end
        args = {}
        h.each do |key, value|
          key = key.to_sym
          t = type(key)
          args[key] = try_convert(t, key, value)
        end
        new(args)
      end

      def definition
        const_get(:DEFINITION)
      end

      def members
        definition.keys
      end

      def type(k)
        definition[k]
      end

      def valid?(k, v)
        definition[k] === v
      end

      private

      def try_convert(klass, key, value)
        return nil unless !klass.nil? && !value.nil?

        case klass
        when Union
          errors = []
          klass.each do |k|
            t = begin
                  try_convert(k, key, value)
                rescue TypeError => e
                  errors << e
                  nil
                end
            return t if !t.nil?
          end
          raise UnionNotFoundError, "#{klass} is not found with value `#{value}'\nerrors:\n#{errors.join("\n")}"
        when ArrayOf
          unless Array === value
            raise TypeError, "#{self}##{key} expect #{klass.inspect} got #{value.inspect}"
          end
          value.map { |v| try_convert(klass.type, key, v) }
        when HashOf
          unless Hash === value
            raise TypeError, "#{self}##{key} expect #{klass.inspect} got #{value.inspect}"
          end
          new_hash = {}
          value.each do |hk, hv|
            new_hash[hk] = try_convert(klass.value_type, key, hv)
          end
          new_hash
        else
          if klass.respond_to?(:ancestors)
            if klass.ancestors.include?(TypeStruct)
              klass.from_hash(value)
            elsif klass.ancestors.include?(Struct)
              struct = klass.new
              value.each { |k, v| struct[k] = v }
              struct
            elsif klass === value
              value
            else
              raise TypeError, "#{self}##{key} expect #{klass.inspect} got #{value.inspect}"
            end
          else
            value
          end
        end
      end
    end

    args.each_key do |k|
      define_method(k) do
        instance_variable_get("@#{k}")
      end

      define_method("#{k}=") do |v|
        unless self.class.valid?(k, v)
          raise TypeError, "#{self.class}##{k} expect #{self.class.type(k)} got #{v.inspect}"
        end
        instance_variable_set("@#{k}", v)
      end
    end
  end
  if block_given?
    c.module_eval(&block)
  end
  c
end

.original_newObject



51
# File 'lib/type_struct.rb', line 51

alias original_new new

Instance Method Details

#==(other) ⇒ Object



20
21
22
23
24
# File 'lib/type_struct.rb', line 20

def ==(other)
  return false unless TypeStruct === other
  return false unless to_h == other.to_h
  true
end

#[](k) ⇒ Object



30
31
32
# File 'lib/type_struct.rb', line 30

def [](k)
  __send__(k)
end

#[]=(k, v) ⇒ Object



26
27
28
# File 'lib/type_struct.rb', line 26

def []=(k, v)
  __send__("#{k}=", v)
end

#inspectObject Also known as: to_s



34
35
36
37
38
39
# File 'lib/type_struct.rb', line 34

def inspect
  m = to_h.map do |k, v|
    "#{k}=#{v.inspect}"
  end
  "#<#{self.class} #{m.join(', ')}>"
end

#to_hObject



42
43
44
45
46
47
48
# File 'lib/type_struct.rb', line 42

def to_h
  m = {}
  self.class.members.each do |k|
    m[k] = self[k]
  end
  m
end