razorpay / razorpay-ruby

Razorpay Ruby SDK
https://rubygems.org/gems/razorpay
MIT License
64 stars 59 forks source link

Allow using multiple merchant accounts in a single project #66

Open rubish opened 6 years ago

rubish commented 6 years ago

Its convenient that all the API calls and entities of razorpay can be accessed using class methods, but the design makes heavy use of class variables. Class variables should be frowned upon because they are not thread safe. Moreover, despite everything implemented as classes; usage is mostly as if these were modules. Currently no instances can be created which can be configured at runtime.

There can be many different ways to implement thread safe code, which can be configured at runtime. One such implementation can be as follows:

class Razorpay::Client
  attr_accessor :auth, :custom_headers
  def initialize(auth=nil, custom_headers=nil)
    self.auth = auth || Razorpay.auth
    self.custom_header = custom_headers || Razorpay.custom_headers
  end

  def self.payment
    new.payment
  end

  def self.refund
    new.refund
  end

  # ...... other methods

  def payment
     @payment ||= Razorpay::Payment.new(self)
  end

  def refund
    @refund ||= Razorpay::Refund.new(self)
  end

  # ..... other similar methods
end

class Razorpay::Payment
  attr_accessor :request
  def initialize(client=nil)
    self.request = Razorpay::Request.new(client || Razorpay::Client.new, "payments")
  end

  def fetch(id)
    self.request.fetch id
  end

  # ..... other methods
end

class Request
  def initialize(client=nil, entity_name=nil)
    # similar to current implementation, but use client.auth and client.custom_headers, instead of Razorpay.auth and Razorpay.custom_headers
  end

  # ... other request methods
end

##### Basic usage #####
Razorpay::Client.payment.fetch(id)

##### Advanced usage with multiple merchant accounts #####
account1 = Razorpay::Client.new(auth1)
account1.payment.fetch(id)

account2 = Razorpay::Client.new(auth2)
account2.payment.fetch(id)

I am open to feedback and other suggestions to be able use multiple merchant accounts in a single project.

harman28 commented 5 years ago

Thanks for the suggestion @rubish! This is actually a pretty sound idea, and we would like to implement it. It would naturally involve a bit of a refactor and new major release, but it seems worth it. We're not going to be picking this up immediately, but you can feel free to raise a pull request if you're interested in working on this!

megatux commented 2 years ago

Any updates on this?