现在,我在我的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块中使用project
变量。
答案 0 :(得分: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
希望有所帮助。
答案 1 :(得分: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功能,并且只保留一个语句,因为将返回上一个计算结果。