Class: ISBNdb::Result

Inherits:
Object
  • Object
show all
Defined in:
lib/isbndb/result.rb

Overview

The Result object is a true testament of metaprogramming. Almost every method of the Result is dynamically generated through the build_result() method. All attribtues of the XML are parsed, translated, and populated as instance methods on the Result object. This allows for easy Ruby-like access (@book.title), without hardcoding every single possible return value from the ISBNdb API

Instance Method Summary collapse

Constructor Details

#initialize(json = {}) ⇒ Result

Initialize simply calls build_result. Because the method definition is recusive, it must be moved into a separate helper.



12
13
14
# File 'lib/isbndb/result.rb', line 12

def initialize(json = {})
  @store = build_result(json)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object

Because a result may or may not contain a specified key, we always return nil for consistency. This allows developers to easily check for .nil? instead of checking for a myriad of exceptions throughout their code.



19
20
21
# File 'lib/isbndb/result.rb', line 19

def method_missing(m, *args, &block)
  @store[m.to_s.underscore]
end

Instance Method Details

#==(result) ⇒ Object



38
39
40
# File 'lib/isbndb/result.rb', line 38

def ==(result)
  self.inspect == result.inspect
end

#inspectObject



34
35
36
# File 'lib/isbndb/result.rb', line 34

def inspect
  "#<Result #{@store.collect{ |key,value| ':' + key.to_s + ' => ' + value.inspect }.join(', ')}>"
end

#instance_methodsObject

Return a list of all “methods” this class responds to



24
25
26
# File 'lib/isbndb/result.rb', line 24

def instance_methods
  @store.collect{ |key,value| key.to_s }
end

#to_sObject

Pretty print the Result including the number of singleton methods that exist. If you want the ACTUAL singleton methods, call @result.singleton_methods.



30
31
32
# File 'lib/isbndb/result.rb', line 30

def to_s
  "#<Result @num_singleton_methods=#{@store.size}>"
end