codebee
codebee

Reputation: 844

Access Ruby Instance Variable from Included Module

I have a Sinatra API file that has following code-

require 'json'
require_relative 'api_logger'

include ApiLogger

get /myapi/:id
 request_params = request.env
 write_log('log message')    
end

Then I have a module containing the methods 'write_log'-

module ApiLogger

def write_log(message)
 file.write(request['user']+message)
end

But request['user'] is coming out blank.

So the question is how to access the request variable from Sinatra API file in ApiLogger module? Also, I'm creating service class objects from API class and pass them request object at initialization. Can the module 'ApiLogger' access that 'request' instance variable from service class if the service classes just include 'ApiLogger'?

Upvotes: 0

Views: 191

Answers (3)

To마SE
To마SE

Reputation: 581

You were almost there, all you needed was include your module in the helpers in order to have a direct access to the request object. Here's a slightly modified version of your code that runs as a standalone program:

require 'sinatra'

module ApiLogger
  def write_log(message)
    $stdout.write(request.env['sinatra.route'] + message)
  end
end

helpers do
  include ApiLogger
end

get '/test' do
  write_log('log message')

  'ok'
end

Upvotes: 0

codebee
codebee

Reputation: 844

I did not want to pass request object to each method. So I made 'request_params' a global variable in all classes that need to log and added this line in 'ApiLogger' to fetch the value of request object-

request = instance_variable_get '@request_params'

Upvotes: 0

regulation_d
regulation_d

Reputation: 91

You could pass it as an additional argument. Something like:

require 'json'
require_relative '../../lib/helpers/api_logger'

include ApiLogger

get /myapi/:id
  request_params = request.env
  write_json_log('log message', request)    
end

and

def write_json_log(message, request)
  file.write(request['auth_subject']+message)
end

Upvotes: 2

Related Questions