Sai
Sai

Reputation: 7209

How can I rename a Ruby library module's namespace?

I'd like to use the ruby Stripe library in a Rails app. It uses the module Stripe as its namespace.

I want to use Stripe as the namespace for my ActiveRecord models, and rename the library module to something like StripeApi, so that e.g. StripeApi::Charge refers to the Stripe library, but Stripe::Charge refers to my Stripe-namespaced ActiveRecord model (so that e.g. Stripe::Charge.create(...) creates a database record, rather than just making API calls).

Is there a good way to do this?

(Sure, I could rename my namespace, or try to use differently named models, but I find that kinda ugly.)

Upvotes: 3

Views: 2826

Answers (2)

markusschwed
markusschwed

Reputation: 142

I really recommend to rename your own namespace since you have full control over the code. Otherwise it could really become a pain in the ass if you want to update the version of the Stripe gem or search for a Bug relating to your namespace as well to the original Stripe namespace.

It's a lot easier to change the own namespace instead of changing an existing gem (eventually for every version again).

Upvotes: 2

Jörg W Mittag
Jörg W Mittag

Reputation: 369428

There is no such thing as "namespace" in Ruby. It's just a variable (well, constant):

StripeApi = Stripe

Boom. You're done.

Make sure to set Stripe to a new module, so that you don't accidentally reopen the module when you think you are creating a new one:

Stripe = Module.new

Now you can do

class Stripe::Charge; end

Upvotes: 4

Related Questions