tags:

views:

48

answers:

3

Is there a way to set a default initialize method without writing it down?

class DataClass
  attr_accessor :title, :description, :childs
  def hasChilds?
    @childs.nil?
  end
end

I Want to initialize this class with standard initial attributes. Something like this:

$> a = DataClass.new(:title => "adsf", :description => "test")
$> a.title # --> "asdf"

Is there such a solution?

+2  A: 

You can use this gem and then simply do:

require 'zucker/ivars'

def initialize(variable1, variable2)
  instance_variables_from binding # assigns @variable1 and @variable2
end

The "zucker" gem also allows you to use a hash! Have a look at the example.

halfdan
Nice gem, thanks! But I dont want to introduce another gem in my project for such a simple task.
Fu86
+2  A: 

One option would be to use a Struct as the base of your class. For example:

class DataClass < Struct.new(:title, :description, :childs)
  def has_childs?
    @childs.nil?
  end
end

a = DataClass.new('adsf', 'description')
puts a.title

Now the order of the parameters is important.

rjk
Nice technique, I'll keep this in mind!
Fu86
+2  A: 

Depending on what you are trying to achieve you might be able to use OpenStruct

a = OpenStruct.new(:title => "adsf", :description => "test")
>> a.title
=>> "adsf"
Jonas Elfström
Ah, great! Thats what I am searching for!
Fu86
One thing to keep in mind: with `OpenStruct` there is no runtime error checking if you try to reference an attribute that wasn't set in the constructor. `OpenStruct` is effectively a glorified hash. Access an unknown attribute and you get a `nil` response.
rjk