madcolonel10
madcolonel10

Reputation: 743

Sinatra Multiple Parallel Requests Variable Behaviour

I am fairly new to ruby and would like to understand how class instance variables behave in case of multiple parallel requests.

I have a method inside my controller class which is called everytime for each request for a specific operation (create in this case)

class DeployProvision
    def self.create(data)
        raise "Input JSON not received." unless data
        # $logger.info input_data.inspect
        failure = false
        response_result = ""
        response_status = "200"
        @validator = SchemaValidate.new
        validation = @validator.validate_create_workflow(data.to_json)
    end
end

This method is called as (DeployProvision.create(data))

I am a little confused on how @validator class instance variable behaves when multiple requests come. Is it shared among multiple requests. Is it a good idea to declare this as class instance variable instead of a local variable ?

I am working on an existing code base and would like to understand the intent of creating @validator as a class instance variable instead of local variable.

Upvotes: 0

Views: 247

Answers (1)

Bartosz Bonisławski
Bartosz Bonisławski

Reputation: 247

You can write ultra-simple script like this:

require 'sinatra'
class Foo
  def self.bar
    @test = Time.now
    puts @test
  end
end

get '/' do
  Foo.bar
end

and you'll see it does nothing, because with every call, you're creating new instance of Time(SchemaValidate in your code).

If you used memoization and had something like @validator ||= SchemaValidate.new you would have one instance of SchemaValidate stored between requests.

I don't think that'd change anything in terms of performance and I don't have idea why would anyone do something like that.

You can have some fun with ultra-simple scripts with sinatra to test how it behaves.

Good luck with this code!

Upvotes: 1

Related Questions