espn_rb 0.0.3 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md CHANGED
@@ -4,9 +4,30 @@ A ruby wrapper for the ESPN api. It allows you to interact, in a semantically p
4
4
 
5
5
  ## Installation
6
6
 
7
+ ### As of Version 0.0.3
8
+
7
9
  Add this line to your application's Gemfile:
8
10
 
9
11
  gem 'espn_rb'
12
+
13
+ In order to use espn_rb you need to first get an API key from ESPN [ESPN api request](http://developer.espn.com/member/register). Once you've gotten that squared away you can use the public requests straight away.
14
+
15
+
16
+ ## Set your API key
17
+
18
+ The easiest way to set your api key for use with espn_rb is to export it as an environment variable. Do that like so:
19
+
20
+ ```sh
21
+ $ export espn_api_key=YOUR_SUPER_SECRET_API_KEY
22
+ ```
23
+
24
+ If you want to pass it in to your objects you may do so explicitly like so:
25
+
26
+ ```ruby
27
+ espn = EspnRb.headlines(:api_key => YOUR_SUPER_SECRET_API_KEY)
28
+ ```
29
+
30
+ For the sake of simplicity all my examples will assume that you have exported the API key as an environment variable.
10
31
 
11
32
  ## Espn Headines
12
33
 
@@ -21,10 +42,12 @@ espn = Espn.headlines
21
42
  espn.all
22
43
  ```
23
44
 
24
- Which will return an HeadlineResponse object. To get the response straight from the horses' mouth:
45
+ Which will return an HeadlineResponse object.
25
46
 
26
47
  #### Get ESPN response as JSON
27
48
 
49
+ To get the response straight from the horses' mouth:
50
+
28
51
  ```ruby
29
52
  # from above
30
53
 
@@ -32,10 +55,12 @@ espn.all.response
32
55
  #=> ESPN's response string as JSON
33
56
  ```
34
57
 
35
- The raw response from ESPN will give you the top ten stories meeting your criteria. Since this is a basic collection and each headline share many common attributes there are collection methods defined on the HeadlineResponse object. Use them like so.
58
+ The raw response from ESPN will give you the top ten stories meeting your criteria.
36
59
 
37
60
  #### Collections
38
61
 
62
+ Since the above response is a basic collection and each headline share many common attributes there are collection methods defined on the HeadlineResponse object. Use them like so.
63
+
39
64
  ```ruby
40
65
  # from above
41
66
 
@@ -59,6 +84,24 @@ espn = EspnRb.headlines
59
84
 
60
85
  espn.nba(:news) #=> HeadlineResponse
61
86
  espn.nba(:top) #=> HeadlineResponse
87
+ espn.nba({:for_date => "2012-03-09"}) #=> HeadlineResponse
88
+
89
+ ```
90
+
91
+ #### HeadlineItem
92
+
93
+ The HeadlineResponse Object holdes in it the headlines split into HeadlineItems. Here is where you can get Specific information about each story. Here are some of the options.
94
+
95
+ ```ruby
96
+ espn = EspnRb.headlines
97
+ headline_response = espn.nba[2] #=> HeadlineItem
98
+
99
+ headline_response.web_url #=> "http://sports.espn.go.com/espn/wire?section=nba&id=7664408&ex_cid=espnapi_public"
100
+ headline_response.id #=> 7664408
101
+ headline_response.title #=> "Mavericks-Kings Preview"
102
+
103
+ # More to come in future versions.
104
+ headline_response.headline #=> JSON hash from original response.
62
105
  ```
63
106
 
64
107
  #### HELP
@@ -11,3 +11,6 @@
11
11
  :for_date:
12
12
  :url: /news/dates/:yyyymmdd
13
13
  :description: Retrieves news for a specific date.
14
+ :for_athlete:
15
+ :url: /athletes/:athleteId/news
16
+ :description: Retrieves stories about a particular player/athlete.
@@ -2,20 +2,40 @@ module EspnRb
2
2
  class Headline
3
3
  attr_reader :api_key
4
4
 
5
+ # @raise [StandardError] Will raise StandardError if api_key isn't specified by either options passed into initialize or set from ENV
5
6
  def initialize(opts)
6
- @api_key = opts && opts[:api_key].nil? ? opts[:api_key] : ENV['espn_api_key']
7
+ @api_key = opts && !opts[:api_key].nil? ? opts[:api_key] : ENV['espn_api_key']
7
8
  raise StandardError, "You must specify an API key." if @api_key.nil?
9
+
8
10
  create_headline_methods
9
11
  end
10
12
 
13
+ # Returns the ESPN resources as defined [here](http://developer.espn.com/docs/headlines#parameters).
14
+ #
15
+ # @return [Hash] of sports, urls and their descriptions.
11
16
  def api_resources
12
- @api_resources ||= YAML::load(File.read('lib/espn_rb/api_definitions/headline_resources.yaml'))
17
+ @api_resources ||= YAML::load(File.read(File.expand_path(File.join(File.dirname(__FILE__), "..", 'espn_rb/api_definitions/headline_resources.yaml'))))
13
18
  end
14
19
 
20
+ # Returns the ESPN methods as defined [here](http://developer.espn.com/docs/headlines#parameters).
21
+ #
22
+ # @return [Hash] methods, and their associated urls and brief description.
15
23
  def api_methods
16
- @api_methods ||= YAML::load(File.read('lib/espn_rb/api_definitions/headline_methods.yaml'))
24
+ @api_methods ||= YAML::load(File.read(File.expand_path(File.join(File.dirname(__FILE__), "..", 'espn_rb/api_definitions/headline_methods.yaml'))))
17
25
  end
18
26
 
27
+ # The final request to ESPN api after all option parsing has been completed.
28
+ # @return [HeadlineResponse] a headline response object.
29
+ def get_results(resource, method)
30
+ http = Net::HTTP.new("api.espn.com")
31
+ request = Net::HTTP::Get.new("/#{EspnRb::API_VERSION}#{resource}#{method}?apikey=#{@api_key}")
32
+ HeadlineResponse.new JSON.parse(http.request(request).body)
33
+ end
34
+
35
+ # This will define singleton methods for all resources defined
36
+ # in EspnRb::Headline.api_resources
37
+ #
38
+ # @return [HeadlineResponse] which contains the espn response object and assocated methods.
19
39
  def create_headline_methods
20
40
  api_resources.each do |k,v|
21
41
  define_singleton_method(k) do |opt=nil|
@@ -24,26 +44,57 @@ module EspnRb
24
44
  end
25
45
  end
26
46
 
47
+ # Attempts to parse which EspnRb::Headline.api_methods the user has passed to
48
+ # method defined by EspnRb::Headline.create_headline_methods.
49
+ #
50
+ # @param [Hash] options the options passed in by user.
51
+ # @note This will accept either a string or a hash.
52
+ #
53
+ # @example Call with string
54
+ # get_api_method("news") #=> '/news'
55
+ #
56
+ # @example Call with Hash (for_date)
57
+ # get_api_method({:for_date => "2012-01-01"}) #=> '/news/dates/20120101'
58
+ # @option options [String] :arg When string is passed and :arg
59
+ # is available it will return the url associated with that :arg from EspnRb::Headline.api_methods
60
+ # @option options [Hash] :arg When Hash will pass :arg to opt_from_hash
61
+ #
62
+ # @return [String] a url entry from EspnRb::Headline.api_methods defaults to :news
27
63
  def get_api_method(opt)
28
64
  case opt.class.to_s
29
65
  when "Symbol"
30
- api_method = api_methods.keys.include?(opt) ? api_methods[opt][:url] : (raise StandardError, "The parameter you sent is not available.")
66
+ api_method = api_methods.keys.include?(opt) ? api_methods[opt][:url] : (raise StandardError, "The parameter you sent is not available.")
31
67
  when "Hash"
32
- unless opt[:for_date].nil?
33
- api_method = api_methods[:for_date][:url].gsub(":yyyymmdd", Date.parse(opt[:for_date]).strftime("%Y%m%d"))
34
- else
35
- end
68
+ api_method = opt_from_hash(opt)
36
69
  else
37
- api_method = api_methods[:news][:url]
70
+ api_method = api_methods[:news][:url]
38
71
  end
39
72
  end
40
73
 
41
- def get_results(resource, method)
42
- http = Net::HTTP.new("api.espn.com")
43
- request = Net::HTTP::Get.new("/#{EspnRb::API_VERSION}#{resource}#{method}?apikey=#{@api_key}")
44
- HeadlineResponse.new JSON.parse(http.request(request).body)
74
+ def opt_from_hash(opt)
75
+ if !opt[:for_date].nil?
76
+ for_date opt
77
+ elsif !opt[:for_athlete].nil?
78
+ for_athlete opt
79
+ end
80
+ end
81
+
82
+ # Takes EspnRb::Headline.api_methods[:for_athlete][:url] and subs out the options passed by user
83
+ # @example internal call
84
+ # for_athlete({:for_athlete => "123"}) => '/athletes/123/news'
85
+ def for_athlete(opt)
86
+ api_methods[:for_athlete][:url].gsub(":athleteId", opt[:for_athlete])
87
+ end
88
+
89
+ # Takes EspnRb::Headline.api_methods[:for_date][:url] and subs out the options passed by user
90
+ # @example internal call
91
+ # for_date({:for_date => "2012-01-01"}) => '/news/dates/20120101'
92
+ def for_date(opt)
93
+ api_methods[:for_date][:url].gsub(":yyyymmdd", Date.parse(opt[:for_date]).strftime("%Y%m%d"))
45
94
  end
46
95
 
96
+ # Provides help text. Passes the methods available from create_headline_methods all prettified into a set of
97
+ # strings and passes them to EspnRb::Utilities.help which then inserts it below some nice ascii art.
47
98
  def help
48
99
  EspnRb::Utilities.help api_resources.map {|k,v| "\t#{(':' + k.to_s).ljust(25)} #{v[:description]}"}.join("\n")
49
100
  end
@@ -0,0 +1,81 @@
1
+ class HeadlineResponse
2
+ class HeadlineItem
3
+ attr_reader :headline
4
+
5
+ def initialize(opts)
6
+ @headline = opts
7
+ end
8
+
9
+ # @example
10
+ # espn = EspnRb::Headline
11
+ # espn.nba.first.web_url => "http://some-valid-nba-article"
12
+ # @return [String] web_url for Item
13
+ def web_url(mobile=false)
14
+ (mobile == true) ? @headline["links"]["mobile"]["href"] : @headline["links"]["web"]["href"]
15
+ end
16
+
17
+ # @example
18
+ # espn = EspnRb::Headline
19
+ # espn.ncaa_football.first.title => "Gators Win!!"
20
+ # @return [String] title for Item
21
+ def title
22
+ @headline["headline"]
23
+ end
24
+
25
+
26
+ # @example
27
+ # espn = EspnRb::Headline
28
+ # espn.ncaa_football.first.id => 1234
29
+ # @return [Integer] id for Item
30
+ def id
31
+ @headline["id"]
32
+ end
33
+
34
+ # @example
35
+ # espn = EspnRb::Headline
36
+ # espn.nba.first.api_url => "http://some-valid-nba-article"
37
+ # @return [String] api_url for Item
38
+ def api_url
39
+ @headline["links"]["api"]["news"]["href"]
40
+ end
41
+
42
+
43
+ def collect_category(sym)
44
+ @headline["categories"].inject([]) {|m, i| m << i[sym.to_s] unless i[sym.to_s].nil?; m}
45
+ end
46
+
47
+ # Provides access to categories sub-hash. If available
48
+ #
49
+ # @example
50
+ # espn = EspnRb::Headline
51
+ # espn.nba.first.athletes
52
+ # #=> ["Johnny B", "Freddie Flintstone", "Etc"]
53
+ def athletes
54
+ return collect_category(:description)
55
+ end
56
+
57
+ # Provides access to categories sub-hash. If available
58
+ #
59
+ # @example
60
+ # espn = EspnRb::Headline
61
+ # espn.nba.first.leagues
62
+ # #=> ["46"]
63
+ def leagues
64
+ return collect_category(:leagueId)
65
+ end
66
+
67
+ # Provides access to categories sub-hash. If available
68
+ #
69
+ # @example
70
+ # espn = EspnRb::Headline
71
+ # espn.nba.first.athlete_ids
72
+ # #=> ["123", "132", "123"]
73
+ def athlete_ids
74
+ return collect_category(:athleteId)
75
+ end
76
+
77
+ def categories
78
+ @headline["categories"]
79
+ end
80
+ end
81
+ end
@@ -1,45 +1,46 @@
1
1
  class HeadlineResponse
2
+ include Enumerable
3
+
2
4
  attr_reader :response,:responses
3
5
 
6
+ # Sets response from EspnRb::Headline.get_results. Splits response object into composite parts
7
+ # so that we can include enumerable
4
8
  def initialize(response)
5
- @response = @response || response
9
+ @response = @response || response
6
10
  @responses = @response['headlines'].map {|h| HeadlineItem.new(h)}
7
- @reports = create_reports(reponse)
8
11
  end
9
12
 
13
+ # define each so that Enumerable methods work properly.
14
+ def each &block
15
+ @responses.each do |response|
16
+ if block_given?
17
+ block.call response
18
+ else
19
+ yield response
20
+ end
21
+ end
22
+ end
23
+
24
+ # Allows the user to specify which HeadlineItem they'd like to work with via it's index in the @responses array
25
+ #
26
+ # @return [HeadlineItem] HeadlineItem specified by responses index
10
27
  def [](int)
11
28
  @responses[int]
12
29
  end
13
30
 
31
+ # Defines a few collection methods to allow the user to view all of the @response like attributes
32
+ # @note available methods are headlines, descriptions, sources, bylines, types
33
+ #
34
+ # @example Valid method call
35
+ # EspnRb::Headline.nba.titles #=> ['title1', 'title2', 'title3', 'title4', 'etc']
36
+ # @example Invalid method call
37
+ # EspnRb::Headline.nba.not_an_available_method #=> nil
38
+ # @return [Array] array of like items or nil
14
39
  def method_missing(sym, *args)
15
- sym.to_s == "titles"? sym = :headlines : sym
40
+ sym.to_s == "titles" ? sym = :headlines : sym
16
41
 
17
42
  if %w{headlines descriptions sources bylines types}.include?(sym.to_s)
18
43
  @response["headlines"].map {|h| h[sym.to_s[0..-2]] }
19
44
  end
20
45
  end
21
-
22
- class HeadlineItem
23
- attr_reader :headline
24
-
25
- def initialize(opts)
26
- @headline = opts
27
- end
28
-
29
- def web_url(mobile=false)
30
- (mobile == true) ? @headline["links"]["mobile"]["href"] : @headline["links"]["web"]["href"]
31
- end
32
-
33
- def title
34
- @headline["headline"]
35
- end
36
-
37
- def id
38
- @headline["id"]
39
- end
40
-
41
- def api_url
42
- @headline["links"]["api"]["news"]["href"]
43
- end
44
- end
45
46
  end
@@ -3,11 +3,11 @@ module EspnRb
3
3
  def self.help(str)
4
4
  puts "-----------------------------Welcome to EspnRb.---------------------------------\n\n"
5
5
  puts s = <<EOF
6
- _.-=""=-._
7
- .'\\\\-++++-//'.
8
- ( || || )
9
- '.// \\\\.'
10
- `'-=..=-'`
6
+ _.-=""=-._
7
+ .'\\\\-++++-//'.
8
+ ( || || )
9
+ '.// \\\\.'
10
+ `'-=..=-'`
11
11
  EOF
12
12
  puts "--------------------------------------------------------------------------------"
13
13
  puts "You are currently using the headlines api from here you can do the follow:\n\n"
@@ -1,4 +1,4 @@
1
1
  module EspnRb
2
- VERSION = "0.0.3"
2
+ VERSION = "0.0.4"
3
3
  API_VERSION = "v1"
4
4
  end
data/lib/espn_rb.rb CHANGED
@@ -1,6 +1,7 @@
1
1
  require "espn_rb/version"
2
2
  require "espn_rb/headline.rb"
3
3
  require 'espn_rb/headline_response.rb'
4
+ require 'espn_rb/headline_item.rb'
4
5
  require 'espn_rb/utilities.rb'
5
6
 
6
7
  require 'json'
@@ -9,6 +10,11 @@ require "net/http"
9
10
  module EspnRb
10
11
  include EspnRb::Utilities
11
12
 
13
+ # Returns an EspnRb::Headline object.
14
+ #
15
+ # @param [Hash] options the options to create the Headline object.
16
+ # @option options [String] :api_key Your ESPN developer api key.
17
+ # @return [EspnRb::Headline] entry point to Espn Headline API.
12
18
  def self.headlines(options=nil)
13
19
  EspnRb::Headline.new(options)
14
20
  end
data/spec/espn_rb_spec.rb CHANGED
@@ -11,14 +11,19 @@ describe EspnRb::Headline do
11
11
  :headers => {})
12
12
  end
13
13
 
14
- it "should return valid HeadlineResponse when #all is called." do
14
+ it "#all should return valid HeadlineResponse" do
15
15
  @espn.all.class.should eq(HeadlineResponse)
16
16
  end
17
17
 
18
- it "get_results from api.espn.com" do
18
+ it "#get_results from api.espn.com" do
19
19
  @espn.get_results(@espn.api_resources[:all][:url], @espn.api_methods[:news][:url]).class.should eq(HeadlineResponse)
20
20
  end
21
21
 
22
+ it "@api_key should be set" do
23
+ espn = EspnRb.headlines(:api_key => "abc123")
24
+ espn.api_key.should eq "abc123"
25
+ end
26
+
22
27
  context "api_resources and api_methods should be defined properly (Ensure no typos)" do
23
28
  it {@espn.api_resources[:nba][:url].should eq("/sports/basketball/nba") }
24
29
  it {@espn.api_resources[:all][:url].should eq("/sports") }
@@ -40,9 +45,29 @@ describe EspnRb::Headline do
40
45
 
41
46
 
42
47
  describe HeadlineResponse do
43
- context "returns the correct title information when #title is called" do
48
+ context "Method missing provides correct collection methods." do
44
49
  it {@espn.all.titles.first.should eq("Trail Blazers 86, Hornets 74")}
45
- it {@espn.all.titles.last.should eq("Saint Mary's (Cal) 78, No. 24 Gonzaga 74") }
50
+ it {@espn.all.descriptions.last.should eq("With the score deadlocked in overtime and the ball bouncing free, opposing guards Matthew Dellavedova and Kevin Pangos collided near the scorer's table.") }
51
+ it {@espn.all.sources.last.should eq("Associated Press") }
52
+ it {@espn.all.types.last.should eq("Wire") }
53
+ end
54
+ end
55
+
56
+ describe HeadlineResponse::HeadlineItem do
57
+ context "HeadlineItem returns proper item info when requested" do
58
+ it { @espn.all[1].web_url.should == 'http://sports.espn.go.com/espn/wire?section=nhl&id=7651009&ex_cid=espnapi_public' }
59
+ it { @espn.all[1].title.should == 'Oilers-Sharks Preview' }
60
+ it { @espn.all[1].api_url.should == 'http://api.espn.com/v1/sports/news/7651009' }
61
+ it { @espn.all[1].id.should == 7651009 }
62
+ end
63
+
64
+ context "HeadlineItem should return an array of requested entries from categories sub-hash" do
65
+ it {@espn.all[1].athletes.should == ["NHL", "San Jose Sharks", "Edmonton Oilers", "Douglas Murray",
66
+ "Logan Couture", "Patrick Marleau", "Joe Thornton", "Anaheim Ducks",
67
+ "Jordan Eberle", "Shawn Horcoff", "Taylor Hall"] }
68
+
69
+ it {@espn.all[1].leagues.should == [90] }
70
+ it {@espn.all[1].athlete_ids.should == [2100, 3773, 576, 939, 5032, 1080, 5428] }
46
71
  end
47
72
  end
48
73
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: espn_rb
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.3
4
+ version: 0.0.4
5
5
  prerelease:
6
6
  platform: ruby
7
7
  authors:
@@ -9,7 +9,7 @@ authors:
9
9
  autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
- date: 2012-03-09 00:00:00.000000000 Z
12
+ date: 2012-03-11 00:00:00.000000000 Z
13
13
  dependencies: []
14
14
  description: A Ruby wrapper for ESPN's api.
15
15
  email:
@@ -29,6 +29,7 @@ files:
29
29
  - lib/espn_rb/api_definitions/headline_methods.yaml
30
30
  - lib/espn_rb/api_definitions/headline_resources.yaml
31
31
  - lib/espn_rb/headline.rb
32
+ - lib/espn_rb/headline_item.rb
32
33
  - lib/espn_rb/headline_response.rb
33
34
  - lib/espn_rb/utilities.rb
34
35
  - lib/espn_rb/version.rb
@@ -63,3 +64,4 @@ test_files:
63
64
  - spec/espn_rb_spec.rb
64
65
  - spec/mock_requests/all_headlines_request.txt
65
66
  - spec/spec_helper.rb
67
+ has_rdoc: