I had a problem with missing instances and nilClass errors when calling my routes. After going around inside the source, it seems that calling generate_method basically creates a new method using the block of the original method.
get "/" do @some_local_instance.do_something() end
Thus, in the above method, there may well be a local variable inside this class called some_local_instance, however, when the actual rote evaluation has no context as to where the method was defined, so it will fail.
The reason I'm asking is because, as part of my script, I have external classes that load when Sinatra loads, that register routes and when these routes are called, I need to access some local variables in these classes. An example is:
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!
Forgive any spelling / parsing errors, this is just a quick example, but since you can see the classes register the routes and when that route hits, it returns some value generated by the calculator instance that was required when creating it.
The problem is that in this example, when I try to start / add a route, it tells me that @calculator is nilClass, and I believe that this is not the way Sinatra just takes a code block without context, It seems perfect for any simple rendering of the template, but if you need to do something more interesting or want your code to be modular without using statics and singleton, you seem to have no way around this ...
Are my assumptions correct here? and if so, then there is some way to maintain the context, because it feels that it makes me write poorly and it’s hard to maintain code if I need to write everything like static and singleton to interact with the route.
== Edit ==
I rebuilt the question and the content in order to more accurately reflect the real problem, now that I am more clearly versed in the library.