Class: ComicVine::CVObject
- Inherits:
-
Object
- Object
- ComicVine::CVObject
- Defined in:
- lib/comic_vine/cv_object.rb
Overview
Wraps a single resource returned by the API. Every key in the response
becomes a reader method; nested resources that carry an api_detail_url
become CVObjects themselves and can be expanded with get_<key>.
Instance Method Summary collapse
-
#fetch ⇒ CVObject
Retrieves the full object from this object's
api_detail_url. -
#initialize(args) ⇒ CVObject
constructor
A new instance of CVObject.
-
#method_missing(method_sym, *arguments) ⇒ Object
Resolves
get_<key>calls: fetches the full object(s) behind an association, or returns the plain value if it isn't an association. - #respond_to_missing?(method_sym, include_private = false) ⇒ Boolean
Constructor Details
#initialize(args) ⇒ CVObject
Returns a new instance of CVObject.
9 10 11 12 13 14 15 16 |
# File 'lib/comic_vine/cv_object.rb', line 9 def initialize(args) args.each do |k, v| singleton_class.class_eval { attr_reader k } unless respond_to?(k) v.collect! { |i| CVObject.new i } if v.is_a?(Array) && v.first.is_a?(Hash) && v.first.key?("api_detail_url") v = CVObject.new v if v.is_a?(Hash) && v.key?("api_detail_url") instance_variable_set "@#{k}", v end end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_sym, *arguments) ⇒ Object
Resolves get_<key> calls: fetches the full object(s) behind an
association, or returns the plain value if it isn't an association.
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/comic_vine/cv_object.rb', line 28 def method_missing(method_sym, *arguments, &) if method_sym.to_s =~ /^get_(.*)$/ key = $1 if instance_variable_defined?("@#{key}") item = instance_variable_get("@#{key}") if item.is_a?(Array) && item.first.is_a?(CVObject) item.map(&:fetch) elsif item.is_a?(CVObject) item.fetch else item end else super end else super end end |
Instance Method Details
#fetch ⇒ CVObject
Retrieves the full object from this object's api_detail_url.
22 23 24 |
# File 'lib/comic_vine/cv_object.rb', line 22 def fetch ComicVine::API.get_details_by_url(@api_detail_url) end |
#respond_to_missing?(method_sym, include_private = false) ⇒ Boolean
48 49 50 |
# File 'lib/comic_vine/cv_object.rb', line 48 def respond_to_missing?(method_sym, include_private = false) method_sym.to_s =~ /^get_(.*)$/ ? instance_variable_defined?("@#{$1}") : super end |