Set ruby 2.0 keyword arguments with attr_accessor on initialize

前端 未结 2 955
一向
一向 2021-02-13 10:44

How can I dynamically set without having to write the same code all over.

Right now the code looks like this:

def initialize(keywords: keywords, title: t         


        
2条回答
  •  别跟我提以往
    2021-02-13 11:25

    Here is a working example based on Sawa's answer. Option number #1 is not working right with inheritance.

    class CsvOutline
      def initialize( headers: [],
                      body: [],
                      folder: 'tmp',
                      file_prefix: 'test',
                      filename: "#{file_prefix}_#{Time.zone.now.strftime("%Y%m%d%H%M%S")}.csv",
                      path: File.join(folder, filename))
        # Set instance variables and attribute accessors based on named parameters in initialize
        local_variables.each do |k|
          class_eval do
            attr_accessor k
          end
          v = eval(k.to_s)
          instance_variable_set("@#{k}", v) unless v.nil?
        end
      end
    end
    

    now if I was to create a child class

    class ReportCsv < CsvOutline
      def initialize
         super(folder: 'reports', file_prefix: 'Report')
      end
    end 
    

    Now the child will initialize with the proper folder and file_prefix. If I was to use the second option - they'll be initialized to nil.

提交回复
热议问题