开发者

why can't I use @env['REMOTE_ADDR'] outside a route?

开发者 https://www.devze.com 2023-03-11 17:37 出处:网络
why cannot开发者_C百科 I use @env[\'REMOTE_ADDR\'] outside a route in Sinatra? I want to have client\'s ip available for my whole Sinatra application so I can use it anywhere ...

why cannot开发者_C百科 I use @env['REMOTE_ADDR'] outside a route in Sinatra?

I want to have client's ip available for my whole Sinatra application so I can use it anywhere ...

 clients_ip = @env['REMOTE_ADDR']

  get '/' do
     .. show something ..
     clients_ip
  end
  get '/page1' do
    .. show something ..
    clients_ip
  end


Only the route blocks run in response to a request. The code outside is run once when the handler is set up.

Instead of using a variable you can do what you want with a method, this makes sure that the lookup in @env is done in the correct scope.

def clients_ip
  @env['REMOTE_ADDR']
end

get '/' do
  # ... show something ...
  clients_ip
end
0

精彩评论

暂无评论...
验证码 换一张
取 消