Module: Grpcx::Entity

Defined in:
lib/grpcx/entity.rb

Overview

Entity releated helpers

Constant Summary collapse

TRUE_VALUES =
[true, 1, '1', 't', 'T', 'true', 'TRUE', 'on', 'ON'].to_set.freeze

Class Method Summary collapse

Class Method Details

._convert(field, value, &block) ⇒ Object



7
8
9
# File 'lib/grpcx/entity.rb', line 7

def self._convert(field, value, &block)
  field.label == :repeated ? value.map(&block) : yield(value) if value # rubocop:disable Style/IfUnlessModifierOfIfUnless
end

.build(msgclass, attrs = {}) ⇒ Object

Parameters:

  • msgclass (Class)

    messagepack message class

  • attrs (Hash) (defaults to: {})

    attributes to assign



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
# File 'lib/grpcx/entity.rb', line 17

def build(msgclass, attrs = {}) # rubocop:disable Metrics/MethodLength
  attrs  = ActiveSupport::HashWithIndifferentAccess.new(attrs)
  fields = {}
  msgclass.descriptor.each do |field| # rubocop:disable Metrics/BlockLength
    next unless attrs.key?(field.name)

    source = attrs[field.name]
    target = nil

    case field.type
    when :int64, :int32
      target = Entity._convert(field, source, &:to_i)
    when :float, :double
      target = Entity._convert(field, source, &:to_f)
    when :string
      target = Entity._convert(field, source, &:to_s)
    when :bool
      target = Entity._convert(field, source) do |vv|
        TRUE_VALUES.include?(vv)
      end
    when :enum
      target = Entity._convert(field, source) do |vv|
        case vv
        when Integer
          vv
        when String, Symbol
          field.subtype.lookup_name(vv.to_s.upcase.to_sym)
        end
      end
    when :message
      target = Entity._convert(field, source) do |vv|
        build(field.subtype.msgclass, vv)
      end
    end

    fields[field.name] = target if target
  end

  msgclass.new(fields)
end