Created
April 4, 2014 03:55
-
-
Save jwoertink/9967795 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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? |
whoa, thanks @alexpeachey
class Something::Connection
include Singleton
endrequire '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
endI hope this is right
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm kind of curious why Thing#search and Other#stuff are class methods. If Thing only performs a search, I think it's fine to create a throwaway object after its done.
If they are class methods my best guess (probably awful) is to encapsulate that all in a class.
so it looks like
If they're instance methods, what Paul showed me was:
So the calls wold look like:
I ran into something similar and would love to know a better way to do this!