I have a class, Autodrop, that contains several methods , a.o. ‘metadata’, that call an external API (dropbox). They are slow.
However, I already often have that metadata around when initializing the AutodropImage, so I should make the methods smarter.
What I have in mind is this:
class Autodrop
include Dropbox
attr_reader :path
def initialize(path)
@path = path
end
def self.from_entry(drop_entry)
@drop_entry = drop_entry
self.initialize(@drop_entry.path)
end
def metadata
if @drop_entry = nil
return heavy_lifting_and_network_traffic
else
return @drop_entry.metadata
end
end
#...
end
Now, I would expect to call
entry = BarEntry.new()
foo = Autodrop.from_entry(entry)
foo.metadata
In order to avoid that heavy lifting and network traffic call.
But this does not work. And somehow, in all my newbieness, I am sure I am goind at this all wrong.
Is there a term I should look for and read about first? How would you go for this?
Note, that the examples are simplified: in my code, I inherit AutodropImage < Autodrop for example, which is called from withing AutodropGallery < Autodrop. The latter already knows all metadata for the AutodropImage, so I mostly want to avoid AutodropImage going over the heavy lifting again.
You are creating an instance variable
@drop_entryin your class methodfrom_entryand obviously it wont be available to your object that you are creating in this method. One workaround is to pass it as a parameter when you are initializing the class. It should work if you do the following modifications:In your
from_entryclass method changeto
Modify
initializemethod to:Or if your class is tied up to pass only the
pathparameter, ie. you dont want to change the other existing code then you can use an optional parameter drop entry like so