簡體   English   中英

如何在Ruby中干燥此代碼

[英]How to DRY this code in Ruby

我有以下代碼來表示Ruby中的不同Value Object。 不同類之間唯一發生變化的是INITIALIZATION_ATTRIBUTES數組,該數組表示值對象的屬性列表。 我找不到干燥該代碼的方法。 我嘗試使用Module並訪問包含的類的Constants,但是遇到了此處描述的怪異的Constant查找行為。 本質上,對模塊代碼進行多次評估,並解釋最后評估的類的常量,並將其值應用於所有值對象類。

還有更好的選擇嗎? 我也嘗試過使用基類,但是無法使其正常工作。

  module Values
    class MaintenanceRegimeSerializer
      INITIALIZATION_ATTRIBUTES = [:distance_between_services, :months_between_services]

      def self.load(json)
        json ||= '{}'
        hash = JSON.parse json, symbolize_names: true
        self.new(*INITIALIZATION_ATTRIBUTES.map {|key| hash[key]})
      end

      def self.dump(obj)
        unless obj.is_a?(self)
          raise ::ActiveRecord::SerializationTypeMismatch,
            "Attribute was supposed to be a #{self}, but was a #{obj.class}. -- #{obj.inspect}"
        end

        obj.to_json
      end

      attr_reader *INITIALIZATION_ATTRIBUTES

      define_method :initialize do |*args|
        raise ArgumentError unless INITIALIZATION_ATTRIBUTES.length == args.length
        INITIALIZATION_ATTRIBUTES.each_with_index do |attribute, index|
          instance_variable_set "@#{attribute}", args[index]
        end
      end    

    end
  end

這可以通過分層兩個模塊來完成。 外部模塊將提供初始化內部模塊的功能。 因為使用的類屬性對於每個包含類都是唯一的,所以一個包含類的屬性不能與另一個包含類的屬性沖突。

module Values
  module MaintenanceRegimeSerializer
    extend ActiveSupport::Concern

    class_methods do

      def acts_as_maintenance_regime_serializer(attributes)
        # include the inner module
        # thereby adding the required methods and class attributes
        include JsonMethods
        # set the class variables made available by including the inner module
        self.serializer_attributes = attributes
      end
    end

    module JsonMethods
      extend ActiveSupport::Concern

      included do
        class_attribute :serializer_attributes

        def initialize(*args)
          raise ArgumentError unless self.class.serializer_attributes.length == args.length
          self.class.serializer_attributes.each_with_index do |attribute, index|
            instance_variable_set "@#{attribute}", args[index]
          end
        end    
      end

      class_methods do
        def load(json)
          json ||= '{}'
          hash = JSON.parse json, symbolize_names: true
          new(*serializer_attributes.map {|key| hash[key]})
        end

        def dump(obj)
          unless obj.is_a?(self)
            raise ::ActiveRecord::SerializationTypeMismatch,
              "Attribute was supposed to be a #{self}, but was a #{obj.class}. -- #{obj.inspect}"
          end

          obj.to_json
        end
      end
    end
  end
end

# in the including class

class SomeClass
  # This might also be put into an initializer patching ActiveRecord::Base
  # to avoid having to call this in every class desiring the regime serializer functionalit
  include Values::MaintenanceRegimeSerializer
  acts_as_maintenance_regime_serializer([:distance_between_services, 
                                         :months_between_services])
end

# in another including class

class SomeOtherClass

  include Values::MaintenanceRegimeSerializer
  acts_as_maintenance_regime_serializer([:foo, 
                                         :bar])
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM