Idiomatic object creation in ruby

前端 未结 6 1962
春和景丽
春和景丽 2020-12-01 14:39

In ruby, I often find myself writing the following:

class Foo
  def initialize(bar, baz)
    @bar = bar
    @baz = baz
  end

  << more stuff >>
         


        
6条回答
  •  猫巷女王i
    2020-12-01 15:31

    You could use Virtus, I don't think it's the idiomatic way to do so but it does all the boiler plate for you.

    require 'Virtus'
    
    class Foo
      include 'Virtus'
    
      attribute :bar, Object 
      attribute :baz, Object
    
    end
    

    Then you can do things like

    foo = Foo.new(:bar => "bar") 
    foo.bar # => bar
    

    If you don't like to pass an hash to the initializer then add :

    def initialize(bar, baz)
      super(:bar => bar, :baz => baz)
    end
    

    If you don't think it's DRY enough, you can also do

    def initialize(*args)
      super(self.class.attributes.map(&:name).zip(args)])
    end
    

提交回复
热议问题