EastsideDev
EastsideDev

Reputation: 6659

Rails: constant not initializing

I am trying to use different stripe keys (a credit card payment processing system) depending on whether I'm in test/development or production/ Based on suggestions I've seen on StackOverflow, I did the following:

In my /config/initalizers/stripe.rb file, I have the following:

STRIPE_CONFIG = begin
  config = YAML.load(File.open(Rails.root.join('config', 'stripe.yml')))
  config = config[Rails.env] || {}
  config.to_options
end

and in my /config/stripe.yml file, I have the following:

default: &default
  Stripe.api_key:    "testapikeycode"
  STRIPE_PUBLIC_KEY: "testpublickeycode"

development:
  <<: *default

test:
  <<: *default

production:
  Stripe.api_key:    "productionapikeycode"
  STRIPE_PUBLIC_KEY: "productionpublickeycode"

However, when I go into the console (rails console), and I type

puts STRIPE_PUBLIC_KEY

I get the following error message:

NameError: uninitialized constant STRIPE_PUBLIC_KEY

Any ideas?

Alternate method

Only use stripe.rb, and have the following in it:

if Rails.env == 'production'
  Stripe.api_key:    "productionapikeycode"
  STRIPE_PUBLIC_KEY: "productionpublickeycode"
else
  Stripe.api_key:    "tesapikeycode"
  STRIPE_PUBLIC_KEY: "testpublickeycode"     
end 

Upvotes: 0

Views: 1434

Answers (1)

Peter Duijnstee
Peter Duijnstee

Reputation: 3779

STRIPE_PUBLIC_KEY is a key in your yaml config file, you never actually initialize it as a constant. If you type p STRIPE_CONFIG['STRIPE_PUBLIC_KEY'] instead you should get the result you want.

Aside I think YAML.load should be YAML.load_file.

Upvotes: 2

Related Questions