我在说我的道路时,一直存在一个失踪事件和错误。 在对来源进行v弄之后,似乎与产生“方法呼吁”一样,基本上采用初步方法的组块形成了一种新的方法。
get "/" do
@some_local_instance.do_something()
end
因此,在上述方法中,可以有很大的地方变数,可称之为“当地人”的类别,然而,如果对旋转体进行实际评估,则对这种方法的界定没有背景,那么这种方法就会失败。
The reason I ask is because as part of my script I have external classes which are loaded when Sinatra is loaded which register routes and when those routes are called I need to access some local variables on these classes. An example would be:
class SomeRouteClass
def initialize(sinatra, calculator)
@calculator = calculator
@sinatra = sinatra
end
def setup_routes
@sinatra.get "/add" do
return @calculator.add(1,1)
end
end
end
class Calculator
def add(a,b)
return a+b;
end
end
sinatra = Sinatra.new
calculator = Calculator.new
routing_class = SomeRouteClass.new(sinatra, calculator)
routing_class.setup_routes
sinatra.run!
举例来说,这只是一个快速的例子,但是,由于你能够看到一个班级登记路线,当该路线被击中时,该计算器的一个实例产生了一些价值。
Problem I have is that in this example when I try and run the /add route it tells me that @calculator is a nilClass, and I believe it to be down to the way that Sinatra just takes the block of code without context. This seems fine for any simple template rendering, but if you need to do anything more fancy, or want to keep your code modular by not using statics and singletons you do not seem to have any way around this...
我的假设在这里是否正确? 如果我必须把一切都写成静态和单一州,以便从一条路上互动的话,那么,如果这样的话,保持这种环境的任何方法都会迫使我写不好、难以维持。
== Edit ==
Have restructured the question and content to more accurately reflect the actual problem, now that I have a firmer understanding of the library.