开发者

"Magic constructor" in Ruby for all attributes

开发者 https://www.devze.com 2023-01-16 05:05 出处:网络
Is there a way to set a default initialize method without writing it down? class DataClass attr_accessor :title, :description, :childs

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 = 开发者_C百科DataClass.new(:title => "adsf", :description => "test")
$> a.title # --> "asdf"

Is there such a solution?


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.


I believe the constructor gem does exactly what you want: http://atomicobject.github.com/constructor/

  require 'constructor'

  class Horse
    constructor :name, :breed, :weight
  end
  Horse.new :name => 'Ed', :breed => 'Mustang', :weight => 342


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"


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.


Hashie works great for this.

horse = Hashie::Mash.new(name: 'Ed', breed: 'Mustang', weight: 342)
horse.name    # 'Ed'
horse[:name]  # 'Ed'
horse['name'] # 'Ed'

You can also its Dash class to make a real class with restricted attribute names. And a bunch of other useful data structures too.

0

精彩评论

暂无评论...
验证码 换一张
取 消