DRY Ruby Initialization with Hash Argument

后端 未结 6 2103

I find myself using hash arguments to constructors quite a bit, especially when writing DSLs for configuration or other bits of API that the end user will be exposed to. Wha

6条回答
  •  囚心锁ツ
    2020-11-29 17:49

    My solution is similar to Marc-André Lafortune. The difference is that each value is deleted from the input hash as it is used to assign a member variable. Then the Struct-derived class can perform further processing on whatever may be left in the Hash. For instance, the JobRequest below retains any "extra" arguments from the Hash in an options field.

    module Message
      def init_from_params(params)
        members.each {|m| self[m] ||= params.delete(m)}
      end
    end
    
    class JobRequest < Struct.new(:url, :file, :id, :command, :created_at, :options)
      include Message
    
      # Initialize from a Hash of symbols to values.
      def initialize(params)
        init_from_params(params)
        self.created_at ||= Time.now
        self.options = params
      end
    end
    

提交回复
热议问题