0

I have a variable assigned like this:

cryptsy = Cryptsy::API::Client.new(key, secret)

How can I make this variable accessible through out the application?

Currently its in the Application controller, but I am using GRAPE gem to create a simple api. I need to be able to access the variable in /app/api/v1/bla.rb and other files in the v1 folder.

nahtnam
  • 2,659
  • 1
  • 18
  • 31

3 Answers3

1

You can create an initializer to instantiate on application load. In config/application.rb do something like

require 'cryptsy/api'

module YourApp 
  Cryptsy = Cryptsy::API::Client.new(key, secret)
  ...
end

This will give you a universally accessible instance of this object.

Daniel Nill
  • 5,539
  • 10
  • 45
  • 63
  • I got an error saying `Unidentified local variable or method`. I pretty much took your code, replaced YourApp with `TheCryptoApi` which is the name of my rails project and stuck it in application.rb. I might have done something wrong (sorry im just getting started with rails). – nahtnam Mar 27 '14 at 04:46
  • Where are you getting Cryptsy from? Is it a gem? – Daniel Nill Mar 27 '14 at 04:54
  • Well, yes. Cryptsy is a online exchange for altcoins. http://cryptsy.com Someone took the API and made it a gem. https://rubygems.org/gems/cryptsy-api https://github.com/nbarthel/cryptsy-api – nahtnam Mar 27 '14 at 04:58
  • updated my answer, from the docs you need to require the lib. Let me know if that works. – Daniel Nill Mar 27 '14 at 05:59
  • I still get this error: `undefined local variable or method 'cryptsy' for V1::Btc:Class (NameError)`. Here is a gist with my code for my application.rb file. https://gist.github.com/nahtnam/8c339d07d6ef1fce6daa – nahtnam Mar 28 '14 at 00:53
0

How about creating a class in lib and adding it there. Make sure to add lib to autoload path in config/application.rb

class Cryptsy
  def self.client
    @cryptsy ||= Cryptsy::API::Client.new(key, secret)
  end
end

And whereever you want to use it, you can call

Cryptsy.client
usha
  • 28,973
  • 5
  • 72
  • 93
0

you can add the following code to the file app_root/config/initializers/cryptsy.rb

require 'cryptsy-api' # this line might be needed
$cryptsy = Cryptsy::API::Client.new(key, secret)

then you can access $cryptsy through out the app.

a14m
  • 7,808
  • 8
  • 50
  • 67