LoginSignup
1
1

More than 5 years have passed since last update.

クラスのinitializeの中でインスタンス変数の代入処理が1億行あってうんざりするとき

Posted at

データストア的なクラスを作った時にinializeの中でいくつも単純な代入処理を書くのが嫌だったので以下のようにしました。
他に良い書き方あったら教えろください。

data_store.rb
class DataStore
  attr_accessor :hoge
  attr_accessor :fuga
  def initialize *params
    params = params.first
    unless params.empty?
      params.each do |k, v|
        if self.respond_to?(v) && self.respond_to?("#{v}=")
          self.instance_variable_set("@#{k}".to_sym, v)
        end
      end
    end
  end
end

sam = DataStore.new hoge: "hoge", fuga: "fuga", nothing_val: "val"
p sam # <DataStore:0x007ff4f8b903a8 @hoge="hoge", @fuga="fuga">
1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1