0

现在,我的 rb 文件中有这段代码。它工作得很好:

project = PivotalTracker::Project.find(123456)  

get '/' do 
  @accepted = project.stories.all(:current_state => 'accepted').length
  @delivered = project.stories.all(:current_state => 'delivered').length
  @finished = project.stories.all(:current_state => 'finished').length    

  erb :home
end

我想创建一个totalStories函数来使用,而不是使用 3 行冗长的冗余代码。

所以,我尝试了以下方法:

get '/' do 
  @accepted = totalStories('accepted')
  @delivered = totalStories('delivered')
  @finished = totalStories('finished')

  def totalStories(storyState)
    var estimate = project.stories.all(:current_state => storyState).length
    return var
  end

  erb :home
end

使用此代码,我得到一个错误:

NoMethodError at /
undefined method `totalStories' for #<Sinatra::Application:0x007f89bae6c800>

有关如何解决此错误的任何提示?谢谢!

更新: 我已将方法移到get块之外,但现在我收到一个新错误:undefined local variable or method项目'`

project变量在方法之外和之上定义。

还值得注意的是,我project在其他 get 块中使用了该变量。

4

2 回答 2

1

改用助手:

get '/' do
  @accepted = total_stories('accepted') 
  @delivered = total_stories('delivered')
  @finished = total_stories('finished')

  erb :home
end

helpers do
  def total_stories(option)
    # project = PivotalTracker::Project.find(123456)
    project.stories.all(:current_state => option).length
  end
end

添加@sergey 的答案,而不是上面的代码,您可以undefined method project通过使用该对象的帮助器来避免错误。就像是:

get '/' do
  # same code
end

def total_stories(option)
  project(12345).stories.all(:current_state => option).length
  # The project object here causes an error since it looks for a 
  # project method (yes, instead of object) under Sinatra's Base or Application
  # hence, we define the method inside the helpers block
end

helpers do
  def project(id)
    # Here goes the PivotalTracker find method for that particular ID.
  end

end

希望有帮助。

于 2012-08-09T07:06:30.423 回答
0

为什么不在“get”函数之外创建这个函数?

def totalStories(storyState)
    project.stories.all(:current_state => storyState).length
end

get '/' do 
  @accepted = totalStories('accepted')
  @delivered = totalStories('delivered')
  @finished = totalStories('finished')

  erb :home
end

你也可以缩短你的 totalStories 函数,只留下一条语句,因为最后一个计算结果将被返回。

于 2012-08-08T14:59:41.527 回答