Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby DSL变量初始化_Ruby_Sinatra_Dsl - Fatal编程技术网

Ruby DSL变量初始化

Ruby DSL变量初始化,ruby,sinatra,dsl,Ruby,Sinatra,Dsl,我试图复制Sinatra的功能。特别是类似DSL的部分,您可以在类的定义中定义路由。当我尝试运行persons DSL的我的版本时,我得到一个错误,undefined method'您从未将@persons初始化为除nil以外的任何值。一个简单的解决办法是 class MyPersons < Persons reset! add_person 'Dr.', 'Bob' add_person 'Mr.', 'Jones' end 在睡了一个好觉,又在谷歌上搜索了一会儿之后,我终

我试图复制Sinatra的功能。特别是类似DSL的部分,您可以在类的定义中定义路由。当我尝试运行persons DSL的我的版本时,我得到一个错误,
undefined method'您从未将
@persons
初始化为除nil以外的任何值。一个简单的解决办法是

class MyPersons < Persons
  reset!
  add_person 'Dr.', 'Bob'
  add_person 'Mr.', 'Jones'
end

在睡了一个好觉,又在谷歌上搜索了一会儿之后,我终于找到了答案。Ruby中似乎有一个继承的
方法;在继承类时调用(duh)

实际上,这就是Sinatra在
Sinatra::Base
中实现实例变量的方式

class Persons
  class << self
    def reset!
      @persons = []
    end

    def add_person title, name
      @persons << {
        title: title,
        name: name
      }
    end

    def inherited child
      child.reset!
    end
  end
end

class MyPersons < Persons
  add_person 'Dr.', 'Bob'
  add_person 'Mr.', 'Jones'
end
班级人员

第二部分是我的问题。如何在不调用子类中的方法的情况下初始化
persons
class Persons
  @@persons = []
  class << self
    def reset!
      @@persons = []
    end

    def add_person title, name
      @@persons << { title: title, name: name }
    end
  end
end

class MyPersons < Persons
  add_person 'Dr.', 'Bob'
  add_person 'Mr.', 'Jones'
end
class Persons
  class << self
    def reset!
      @persons = []
    end

    def add_person title, name
      @persons << {
        title: title,
        name: name
      }
    end

    def inherited child
      child.reset!
    end
  end
end

class MyPersons < Persons
  add_person 'Dr.', 'Bob'
  add_person 'Mr.', 'Jones'
end