Welcome!

Ruby-On-Rails Authors: Liz McMillan, Pat Romanski, Elizabeth White, Hovhannes Avoyan, Yeshim Deniz

Related Topics: Ruby-On-Rails, Open Source Cloud

Ruby-On-Rails: Blog Feed Post

How to Generate Boxscores with Ruby from Live MLB Data

As an avid baseball fan, I’ve always been interested in the statistics that surround baseball

As an avid baseball fan, I’ve always been interested in the statistics that surround baseball. More so than in any other sport, baseball is a game ruled by statistics. In this post, I will describe a program that I wrote in the Ruby language to generate box scores for any Major Leage Baseball(MLB) game by using the live XML data provided by MLB. Ruby makes it easy to do using plain Ruby along with just a few libraries.

Live MLB Data
The amount of raw data that MLB makes available is extensive. It includes all of the traditional boxscore statistics plus deep detail on every pitch thrown including its velocity, movement, and location. If you have ever used the Gameday baseball game watcher application than you’ve indirectly been a consumer of this data. All of the data that powers the Gameday application is made available on an MLB server as raw XML files. Also, this is not just historical data. The data is real-time and updated with every pitch thrown during live games. You also have historical data available to you. The data goes back to the 1926 season.

Building a boxscore template with ERb
For those not familiar with ERb, it is a templating engine that allows you to embed Ruby code inside of a document. The Ruby code can then be evaluated at run time and merged with the rest of the document to form a new document. The Rails framework uses ERb to generate HTML content from templates. For the boxscore generator, I used an ERb template to format the layout of the boxscore. This allowed me to keep the presentation seperate from the logic layers of the application. Most Ruby developers are familiar with the ERb templating engine from its usage in Ruby on Rails applications. However, not all developers are aware that ERb can be used very easily outside of a Rails application. ERb is in no way tightly coupled to the Rails framework. ERb is normally included with the standard Ruby distribution. You can use ERb templates by simply requiring ‘erb’ in your Ruby application.

Here is an example of ERb taken from my boxscore template. This section is used to display the linescore of a game:

<div id="linescore">
  <label><%= cities[0] %></label>
  <% (0..8).each do |num| %>
    <%= innings[num][0] %>
  <% end %>
  &nbsp;<b><%= tots[0][0] + '  ' + tots[0][1] + '  ' + tots[0][2] %></b>
  <br/>
  <label><%= cities[1] %></label>
  <% (0..8).each do |num| %>
    <%= innings[num][1] %>
  <% end %>
  &nbsp;<b><%= tots[1][0] + '  ' + tots[1][1] + '  ' + tots[1][2] %></b>
</div>

At the bottom of this post you can find links to download the complete source code for this project including the full boxscore ERb template.

Steps to generate a boxscore
Now that you know about the MLB data source, and ERb, I’ll describe the steps that are used to generate a boxscore in a Ruby application.

  • Find the correct Gameday ID for the game you are interested in.
  • Retreive the correct boxscore.xml file from gd2.mlb.com
  • Parse the boxscore XML to pull out relevant data.
  • Merge the data into the boxscore template and save the result.

The sections below describe each of these steps in more detail.

Find the correct Gameday ID for the game you are interested in

Each MLB game can be identified on the gameday server with a gameday ID. The gameday ID is a string that contains the date of the game concatenated with team information. A gameday ID has the following format:

2009_06_09_chnmlb_houmlb_1

Finding the gameday ID for a game you are interested in is done by looking at the subdirectories contained in a directory that corresponds to the game date you are looking for. That directory will contain a subdirectory for each game played on that date. The game ID can be parsed from the name of that game’s subdirectory. For example, if you were interested in the Detroit Tigers game played on June 6, 2009, you would scan through the subdirectories contained in this directotry:

http://gd2.mlb.com/components/game/mlb/year_2009/month_06/day_21/

Within that directory, you would find a subdirectory named:

gid_2009_06_21_milmlb_detmlb_1/

and from that you can find the game id by stripping off the leading ‘gid_’ from the directory name.

Retreive the correct boxscore.xml file from gd2.mlb.com
After you have identified the correct gameday ID, you have to make an HTTP call to retrieve the boxscore.xml file from the gd2.mlb.com server. This is a fairly simple task in Ruby done using the Net::HTTP library.

I have defined a constant to represent the root path for the gameday server.

GD2_MLB_BASE = "http://gd2.mlb.com/components/game"

Below is the ruby code used to retrieve the boxscore.xml file.

def get_boxscore(year, month, day, gid)
  url = "#{GD2_MLB_BASE}/mlb/year_" + year +
             "/month_" + month + "/day_" + day +
             "/gid_"+gid+"/boxscore.xml"
  xml_data = Net::HTTP.get_response(URI.parse(url)).body
  return xml_data
end

Parse the boxscore XML to pull out relevant data
Now that you have the boxscore.xml file, the next thing that you’ll want to do is parse this file to pull out data that you’ll want to use in your formatted boxscore. There are several XML parsing libraries available for ruby. I chose to use the REXML library to do this parsing. REXML is easy to work with and made the task relatively simple to code. In the sample shown below, I am parsing the boxscore XML file to find all of the batter statistics and pushing those into an array of batters. I will then use that array of batters from my boxscore ERb template to display the batters section of the boxscore.

# Returns an array of hashes where each hash holds data
# for a batter whom appeared in the game.  Specify either
# home or away team batters.
def get_batters(home_or_away)
  doc = REXML::Document.new(@xml_data)
  batters = []
  doc.elements.each(
    "boxscore/batting[@team_flag='#{home_or_away}']/batter")
    { |element|
      batter = {}
      batter['name'] = element.attributes['name']
      batter['pos'] = element.attributes['pos']
      batter['ab'] = element.attributes['ab']
      batter['r'] = element.attributes['r']
      batter['bb'] = element.attributes['bb']
      batter['sf'] = element.attributes['sf']
      batter['h'] = element.attributes['h']
      batter['e'] = element.attributes['e']
      batter['d'] = element.attributes['d']
      batter['t'] = element.attributes['t']
      batter['hbp'] = element.attributes['hbp']
      batter['so'] = element.attributes['so']
      batter['hr'] = element.attributes['hr']
      batter['rbi'] = element.attributes['rbi']
      batter['sb'] = element.attributes['sb']
      batter['avg'] = element.attributes['avg']
      batters.push batter
  }
  return batters
end

Merge the data into the boxscore template and save the result
After you have parsed all of the relevant data out of the boxscore XML, you are ready to use that data to build the final boxscore presentation. The code below is a method in the BoxScore class that I created. This method converts the boxscore into a formatted HTML representation. The first few lines call methods which parse the boxscore XML and setup the corect data variables. After that I create a new ERb instance and load the boxscore.html.erb template into it. This is the template that I created to display the boxscore. The next line binds the template to the variables previously defined in this method and returns the result of the template bound with the variables. This produces the resultant boxscore HTML file.

  # Converts the boxscore into a formatted HTML representation.
  def to_html
    cities = get_cities
    innings = get_innings
    tots =  get_linescore_totals
    home_pitchers = get_pitchers('home')
    away_pitchers = get_pitchers('away')
    home_batters = get_batters('home')
    away_batters = get_batters('away')
    home_batters_text = get_batting_text('home')
    away_batters_text = get_batting_text('away')
    game_info = get_game_info

    gameday_info = parse_gameday_id('gid_' + gid)
    template = ERB.new File.new("boxscore.html.erb").read, nil, "%"
    return template.result(binding)
  end

View the results and download the code
Here are links to download the complete sourcecode for my gameday API in ruby. I’ve also provided a link to a boxscore that has been generated using this code.
Full sourcecode
Generated boxscore

MLB copyright notice
If you decide to do something with my api or the MLB data, be sure that you understand the limitations of using the data. MLB provides the data for experimental usage only. You are not permitted to use it for a commercial application. Below is a line taken from their copyright notice covering all of the data available from their gameday server:
“Only individual, non-commercial, non-bulk use of the Materials is permitted and any other use of the Materials is prohibited without prior written authorization from MLBAM.”

Read the original blog entry...

More Stories By Timothy Fisher

Timothy Fisher has recognized expertise in the areas of Java, Ruby, Rails, Social Media, Web 2.0, and Enterprise 2.o. He has served in technical leadership and senior architecture roles with companies such as Motorola, Cyclone Commerce, and Compuware. He is the author of the Java Phrasebook, and the Ruby on Rails Bible. Currently he is employed as a senior web architect with Compuware in Detroit, Michigan.

Follow Timothy on Twitter at http://twitter.com/tfisher

@ThingsExpo Stories
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
DevOps at Cloud Expo – being held June 5-7, 2018, at the Javits Center in New York, NY – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Among the proven benefits,...
@DevOpsSummit at Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, is co-located with 22nd Cloud Expo | 1st DXWorld Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
SYS-CON Events announced today that T-Mobile exhibited at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on qua...
SYS-CON Events announced today that Cedexis will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Cedexis is the leader in data-driven enterprise global traffic management. Whether optimizing traffic through datacenters, clouds, CDNs, or any combination, Cedexis solutions drive quality and cost-effectiveness. For more information, please visit https://www.cedexis.com.
SYS-CON Events announced today that Google Cloud has been named “Keynote Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Companies come to Google Cloud to transform their businesses. Google Cloud’s comprehensive portfolio – from infrastructure to apps to devices – helps enterprises innovate faster, scale smarter, stay secure, and do more with data than ever before.
SYS-CON Events announced today that Vivint to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. As a leading smart home technology provider, Vivint offers home security, energy management, home automation, local cloud storage, and high-speed Internet solutions to more than one million customers throughout the United States and Canada. The end result is a smart home solution that sav...
SYS-CON Events announced today that Opsani will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Opsani is the leading provider of deployment automation systems for running and scaling traditional enterprise applications on container infrastructure.
SYS-CON Events announced today that Nirmata will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nirmata provides a comprehensive platform, for deploying, operating, and optimizing containerized applications across clouds, powered by Kubernetes. Nirmata empowers enterprise DevOps teams by fully automating the complex operations and management of application containers and its underlying ...
SYS-CON Events announced today that Opsani to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. Opsani is creating the next generation of automated continuous deployment tools designed specifically for containers. How is continuous deployment different from continuous integration and continuous delivery? CI/CD tools provide build and test. Continuous Deployment is the means by which...