Sha256: c847c757e6f668692d532e7ab87455fa5fa3e44cb872c2810682ed97bb253686

Contents?: true

Size: 1.66 KB

Versions: 6

Compression:

Stored size: 1.66 KB

Contents

# frozen_string_literal: true

module MLBStatsAPI
  class LiveFeed < Base
    attr_reader :id

    def initialize(api, data)
      @api = api
      @data = data

      # If we need to nuke and start over, keep this piece
      @id = data['gamePk']
    end

    def boxscore
      @data['liveData']['boxscore']
    end

    def decisions
      @data['liveData']['decisions']
    end

    def leaders
      @data['liveData']['leaders']
    end

    def linescore
      @data['liveData']['linescore']
    end

    def plays
      @data['liveData']['plays']
    end

    def game_data
      @data['gameData']
    end

    def live_data
      @data['liveData']
    end

    def metadata
      @data['metaData']
    end

    def timestamps
      @api.live_feed_timestamps(@id)
    end

    def reload!
      @data = @api.get("/game/#{@id}/feed/live", version: '1.1')

      true
    rescue Net::OpenTimeout
      false
    end

    def update!
      return reload! unless @data

      diffs = @api.live_feed_diff(
        @data['gamePk'],
        timecode: @data['metaData']['timeStamp']
      )

      return process_diffs(diffs) if diffs.is_a?(Array)

      # If the diff is too large or too old, a new feed is returned
      @data = diffs if diffs.is_a?(Hash)

      true
    rescue Net::OpenTimeout
      false
    end

    def process_diffs(diffs)
      diffs.each do |diff_set|
        Hana::Patch.new(diff_set['diff']).apply(@data)
      end

      @api.logger&.info 'Successfully processed live feed diff'

      true
    rescue Hana::Patch::Exception
      @api.logger&.info 'Failed to process live feed diff; nuking'

      # Nuke it!
      @data = nil

      reload!

      false
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
mlb_stats_api-0.2.5 lib/mlb_stats_api/live_feed.rb
mlb_stats_api-0.2.4 lib/mlb_stats_api/live_feed.rb
mlb_stats_api-0.2.3 lib/mlb_stats_api/live_feed.rb
mlb_stats_api-0.2.2 lib/mlb_stats_api/live_feed.rb
mlb_stats_api-0.2.1 lib/mlb_stats_api/live_feed.rb
mlb_stats_api-0.2.0 lib/mlb_stats_api/live_feed.rb