This is one way I've managed to accomplish this.

class Test
 class << self
    attr_accessor :stuff

    def thing msg
      @stuff ||= ""
      @stuff += msg
    end
  end

  def initialize
    @stuff = self.class.stuff
    puts @stuff
  end
end

# Is there a better way of accomplishing this?
class AThing < Test
  thing "hello"
  thing "world"
end

AThing.new
# Prints "helloworld"

The interface in AThing is what I would like as a final result. What I really hate (and I feel there must be a better way of accomplishing) is @stuff = self.class.stuff.

Is there a better way to use the eigenclass to set the default dataset for all instances of itself while maintaining a "pretty" interface?

What I want to accomplish with code like this is to have a class method, say add_something that adds something to an array stored in a class variable.

When the class is instantiated, it will use this array in its' initialize method to setup the state of that instance.

有帮助吗?

解决方案

class Test
  @@stuff = ""

  class << self
    def thing msg
      @@stuff.concat(msg)
    end
  end

  def initialize
    puts @@stuff
  end
end

class AThing < Test
  thing "hello"
  thing "world"
end

AThing.new
# Prints "helloworld"
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top