Track Your Claude Code Costs in Rails with the ClaudeUsage
Using Claude Code to build Rails apps? The ClaudeUsage gem automatically tracks your token usage and calculates costs in real-time, giving you complete visibility into your AI development expenses.
⚡ Installation
Add the gem to your Gemfile:
gem 'claude_usage', group: :development
Then run:
bundle install
rails generate claude_usage:install
rake claude_usage:show_project # Verify which project is tracked
If needed, update the project name in config/initializers/claude_usage.rb:
ClaudeUsage.configure do |config|
config.project_name = "your-rails-app"
end
That's it! Visit http://localhost:3000/claude-usage to see your usage data.
📊 How to Use
Web Dashboard
Navigate to http://localhost:3000/claude-usage to see:
- Total cost and token usage
- Daily breakdown with trends
- Models used and cache statistics
CLI Commands
Quick terminal reports:
rake claude_usage:daily # Daily usage breakdown
rake claude_usage:total # Overall statistics
Ruby API
Access data programmatically in your Rails code:
aggregator = ClaudeUsage::UsageAggregator.new
totals = aggregator.total_usage
puts "Total cost: $#{totals[:total_cost]}"
puts "Total tokens: #{totals[:total_tokens]}"
puts "Models used: #{totals[:models_used].join(', ')}"
💡 Key Features
- 🤖 Zero Configuration - Automatically detects your Rails project
- 💰 Real-Time Pricing - Fetches current rates from LiteLLM API
- 📊 Multiple Interfaces - Web UI, JSON API, and CLI commands
- ⚡ Smart Caching - Reduces API calls while keeping costs accurate
- 🔧 Customizable - Configure project name, cache expiry, and offline mode
🎯 Quick Example: Budget Alert
Set up an automated alert when costs exceed your budget:
# lib/tasks/claude_alert.rake
task alert: :environment do
totals = ClaudeUsage::UsageAggregator.new.total_usage
budget = 100.00
if totals[:total_cost] > budget
puts "⚠️ Usage: $#{totals[:total_cost]} exceeds budget!"
end
end
Conclusion
The ClaudeUsage gem gives you complete visibility into your Claude Code costs with minimal setup. Install it in under 5 minutes and start tracking your AI development expenses today.
Links:
- GitHub: https://github.com/Shoebtamboli/claude_usage
- RubyGems: https://rubygems.org/gems/claude_usage
Connect with me:
- GitHub: github.com/Shoebtamboli
- LinkedIn: linkedin.com/in/shoeb-tamboli