Skip to content

Instantly share code, notes, and snippets.

@jwoertink
Created April 4, 2014 03:55
Show Gist options
  • Select an option

  • Save jwoertink/9967795 to your computer and use it in GitHub Desktop.

Select an option

Save jwoertink/9967795 to your computer and use it in GitHub Desktop.
# Looking to write an API like this.
# Before calling Something::Thing#search, there has to be an instance of Something::Connection
# There are other classes to be used that require the connection instance as well.
conn = Something::Connection.new
things = Something::Thing.search('stuff') # requires that an instance of Something::Connection exists
other = Something::Other.stuff('more') # also requires that instance exists
conn.close
# How can I save that instance in such a way that any other classes in that module will see that,
# without passing that variable every single time?
@seashootz
Copy link
Copy Markdown

whoa, thanks @alexpeachey

class Something::Connection
  include Singleton
end
require 'active_support'

class Something::Thing
  cattr_accessor :connection do
    Something::Connection.instance
  end

  def search
    # much better
  end
end

class Something::Other
  cattr_accessor :connection do
    Something::Connection.instance
  end

  def stuff
    # like a lot better
  end
end

I hope this is right

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment