I am trying to create a class that does a couple of things:
1) Implements a custom getter for an attribute
2) Calls the custom getter from within the initialize method
Here’s what it looks like:
class Book
# RSolr lib for interacting with Solr
require 'rsolr'
# Instance variables
@isbn
@title
# Solr playlist instance URL
@solr_domain
@solr
def initialize(isbn)
@solr_domain = "http://solr.com:9003/solr"
@solr = RSolr.connect :url => @solr_domain
@isbn = isbn
@title = self.title(isbn)
end
# Get Solr URL
def solr_domain
return @solr_domain
end
# Set Solr URL and reset Solr connection object
def solr_domain(newurl)
@solr_domain = newurl
@solr = RSolr.connect :url => @solr_domain
end
# Custom getter for title
def title=(isbn)
result = solr.get 'select', :params => {:q => 'isbn:(' + isbn + ')'}
return result["response"]["docs"][0]["title"]
end
end
The key lines are
@title = self.title(isbn)
where we attempt to call the getter for title, so that title gets set when the object is initialized.
What we want is a publicly accessible getter for title, as well as a way to populate @title during initialization of the object.
For being able to preset the title, you could do something like this:
There’s an optional argument the user can supply. If he/she does,
@titlewill get set to that value, otherwise we’ll look up the title ourselves with the ISBN. I hope I understood you correctly…Edit: BTW, are you sure you want class level instance variables?
http://railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/