Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortcut for setting initialize() args to attributes?

Tags:

ruby

This is a common initializer pattern:

def initialize(title, val, type)
  @title, @val, @type = title, val, type
end

Is there a shortcut that is equivalent to "take every argument, create an attribute of the same name, and set the attribute equal to the argument's value"?

I'm looking for a gem-free solution.

like image 771
Jonah Avatar asked Apr 20 '14 19:04

Jonah


2 Answers

You will lose the function to check against wrong arguments, but can do this:

def initialize(*args)
  @title, @val, @type = args
end

But if you are repeatedly doing this, then your code is not right. You should better redesign your API to take named arguments:

def initialize(title:, val:, type:)
  ...
end

WhateverClass.new(title: "foo", val: "bar", type: "baz")
like image 94
sawa Avatar answered Oct 21 '22 03:10

sawa


You can use Struct as mentioned above or do it dynamically like:

class MyClass

  def initialize input
    input.each do |k,v|
      instance_variable_set("@#{k}", v) unless v.nil?
    end
  end

end

Anyways If it's my code I'll go using Struct.

like image 40
Eki Eqbal Avatar answered Oct 21 '22 03:10

Eki Eqbal