Как я могу упростить этот тип привязки классов данных в Ruby?

У меня есть библиотека или драгоценный камень, который является привязкой к другой библиотеке, написанной на родном скомпилированном языке. В геме есть много таких классов:

  # not a real class name
  class MyClass1

    # not real attribute names
    attr_reader :attr1, :attr2, :attr3 # , there can be more of these


    # some can be nil
    def initialize(attr1:, attr2: nil, attr3: nil)
      @attr1 = attr1
      @attr2 = attr2
      @attr3 = attr3
    end


    # this method is used by other class that'll convert this data-class into a json object
   # obj1.to_h.to_json

    def to_h
      {
        attr1: @attr1,

        # some attributes can be data-classes themselves too
        attr2: @attr2.nil? ? nil : @attr2.to_h,

        # while others are simple or primitive types
        attr3: @attr3
      }
    end
  end

Некоторые классы могут иметь больше атрибутов. В целом все классы похожи на этот.

Есть ли способ как-то упростить это?

Рубин> = 3.0

0

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *