I’ve just started writing a reasonably straightforward site using sinatra. My problem is that I wanted to refactor the main app.rb file but am getting errors trying to access the url params.
In my get ‘/’ action, Sinatra’s looking at which params are set and then needs to do a few different things depending on what’s in the url. Something like this.
class App < Sinatra::Application
...
get '/' do
if params['code1']
@network = 'code1'
mode code here
elsif params['called'] && params['mac']
@network = 'code2'
mode code here
elsif params['code3']
@network = 'code3'
mode code here
end
end
The problem is that I need to require a file that also uses the params.
I’ve put the following in the above code:
require File.dirname(__FILE__) + '/lib/networks/code1.rb'
Where code1.rb includes:
class App < Sinatra::Application
if params['login'] # == 'login'
pass = 'uampass'
elsif
...
But that gives me the following error:
undefined local variable or method `params' for main:Object
How can I refactor this without causing an error
As far as i know you can’t use two (or more) Sinatra applications in, well one application. Since both files define a
Sinatra::Applicationdescendant this isn’t possible.Also if you want to use values from the
params-hash you should define helper methods Helper Documentation, which you call when processing the route, or you just create Class which has class or instance methods which take params-values as parameters. Actually calling params from another file/class doesn’t seem like good practice.To put this in context: Sinatra applications are organised as handlers. The
Sinatra::Applicationdescendant is something like the main handler which uses support methods(helpers and instance methods of theSinatra::Applicationdescendant) or support Classes, which are usually defined in other files, but do not descend fromSinatra::Application.To make this a little bit more clearly:
Your main Sinatra file:
Another file (‘another_file.rb’):
Actual code would of course depend on the real problem you’re trying to solve, so if you would elaborate i could be more precise…