Hey there, fellow code enthusiasts! Ready to supercharge your Ruby projects with some sweet Strava data? You're in the right place. We're diving into the Strava API using the nifty strava-ruby-client
gem. Buckle up!
Before we hit the ground running, make sure you've got:
Let's kick things off by adding the gem to your project:
# In your Gemfile gem 'strava-ruby-client'
Now, give it a quick:
bundle install
And we're off to the races!
Strava uses OAuth 2.0, so we'll need to do a little dance to get our access token. Here's the quick version:
client = Strava::OAuth::Client.new( client_id: ENV['STRAVA_CLIENT_ID'], client_secret: ENV['STRAVA_CLIENT_SECRET'] ) access_token = client.oauth_token( code: 'authorization_code', grant_type: 'authorization_code' )
Pro tip: Keep those credentials safe! Environment variables are your friends.
Now that we've got our access token, let's set up our client:
client = Strava::Api::Client.new(access_token: access_token)
Easy peasy, right?
Time to fetch some data! Let's grab the athlete info:
athlete = client.athlete puts "Hello, #{athlete.firstname}!"
Want to see those activities? Coming right up:
activities = client.athlete_activities activities.each do |activity| puts "#{activity.name} - #{activity.distance} meters" end
Strava's got your back with pagination. Here's how to use it:
page = 1 per_page = 30 loop do activities = client.athlete_activities(page: page, per_page: per_page) break if activities.empty? # Do something with activities page += 1 end
Don't let errors catch you off guard:
begin client.athlete rescue Strava::Errors::Fault => e puts "Oops! #{e.message}" end
Play nice with the API! Keep an eye on those rate limits:
response = client.athlete puts "Rate limit: #{response.headers['X-RateLimit-Limit']}" puts "Usage: #{response.headers['X-RateLimit-Usage']}"
Let's put this to work! How about analyzing your performance?
total_distance = activities.sum(&:distance) total_time = activities.sum(&:moving_time) average_speed = total_distance / total_time puts "Average speed: #{average_speed} m/s"
Or generate a quick activity summary:
activities.each do |activity| puts "#{activity.name}: #{activity.type}, #{activity.distance}m, #{activity.moving_time}s" end
Don't forget to test! Here's a quick example using RSpec:
RSpec.describe Strava::Api::Client do let(:client) { Strava::Api::Client.new(access_token: 'fake_token') } it 'fetches athlete information' do VCR.use_cassette('athlete_info') do athlete = client.athlete expect(athlete.firstname).to eq('John') end end end
And there you have it! You're now armed and ready to integrate Strava into your Ruby projects. Remember, the strava-ruby-client
docs are your best friend for diving deeper. Now go forth and code something awesome!
Happy coding, and may your PRs be swift and your builds be green! 🚴♂️💨