Class: HeadlineResponse

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/espn_rb/headline_item.rb,
lib/espn_rb/headline_response.rb

Defined Under Namespace

Classes: HeadlineItem

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(response) ⇒ HeadlineResponse

Sets response from EspnRb::Headline.get_results. Splits response object into composite parts so that we can include enumerable



8
9
10
11
# File 'lib/espn_rb/headline_response.rb', line 8

def initialize(response)
  @response  = @response || response
  @responses = @response['headlines'].map {|h| HeadlineItem.new(h)}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args) ⇒ Array

Note:

available methods are headlines, descriptions, sources, bylines, types

Defines a few collection methods to allow the user to view all of the @response like attributes

Examples:

Valid method call

EspnRb::Headline.nba.titles #=> ['title1', 'title2', 'title3', 'title4', 'etc']

Invalid method call

EspnRb::Headline.nba.not_an_available_method #=> nil

Returns:

  • (Array)

    array of like items or nil



39
40
41
42
43
44
45
# File 'lib/espn_rb/headline_response.rb', line 39

def method_missing(sym, *args)
  sym.to_s == "titles" ? sym = :headlines : sym

  if %w{headlines descriptions sources bylines types}.include?(sym.to_s)
    @response["headlines"].map {|h| h[sym.to_s[0..-2]]  }
  end
end

Instance Attribute Details

#responseObject (readonly)

Returns the value of attribute response.



4
5
6
# File 'lib/espn_rb/headline_response.rb', line 4

def response
  @response
end

#responsesObject (readonly)

Returns the value of attribute responses.



4
5
6
# File 'lib/espn_rb/headline_response.rb', line 4

def responses
  @responses
end

Instance Method Details

#[](int) ⇒ HeadlineItem

Allows the user to specify which HeadlineItem they’d like to work with via it’s index in the @responses array

Returns:

  • (HeadlineItem)

    HeadlineItem specified by responses index



27
28
29
# File 'lib/espn_rb/headline_response.rb', line 27

def [](int)
  @responses[int]
end

#each(&block) ⇒ Object

define each so that Enumerable methods work properly.



14
15
16
17
18
19
20
21
22
# File 'lib/espn_rb/headline_response.rb', line 14

def each &block
  @responses.each do |response|
    if block_given?
      block.call response
    else
      yield response
    end
  end
end