Ruby SDK
The official Ruby SDK for RenderScreenshot.
Installation
Add to your Gemfile:
gem 'renderscreenshot'
Then run:
bundle install
Or install directly:
gem install renderscreenshot
Requirements
- Ruby 3.0 or higher
Quick Start
require 'renderscreenshot' client = RenderScreenshot.client('rs_live_xxxxx') # Take a screenshot image = client.take( RenderScreenshot::TakeOptions .url('https://example.com') .preset('og_card') ) # Save to file File.binwrite('screenshot.png', image)
Client
Constructor
client = RenderScreenshot.client(api_key, base_url: nil, timeout: nil)
| Parameter | Type | Description |
|---|---|---|
api_key |
String | Your API key (rs_live_* or rs_test_*) |
base_url |
String | API base URL (default: https://api.renderscreenshot.com) |
timeout |
Integer | Request timeout in seconds (default: 30) |
Global Configuration
RenderScreenshot.configure do |config| config.base_url = 'https://api.renderscreenshot.com' config.timeout = 30 end
Methods
take(options)
Take a screenshot and return binary data.
image = client.take( RenderScreenshot::TakeOptions .url('https://example.com') .preset('og_card') ) File.binwrite('screenshot.png', image)
Returns: String (binary data)
take_json(options)
Take a screenshot and return JSON metadata.
response = client.take_json( RenderScreenshot::TakeOptions .url('https://example.com') .preset('og_card') ) puts response['image']['url'] # CDN URL puts response['image']['width'] # 1200 puts response['image']['height'] # 630 puts response['cache']['hit'] # true/false
Returns: Hash
generate_url(options, expires_at:)
Generate a signed URL for public embedding.
signed_url = client.generate_url( RenderScreenshot::TakeOptions .url('https://example.com') .preset('og_card'), expires_at: Time.now + 86400 # 24 hours ) # Use in HTML: <img src="#{signed_url}" />
Returns: String
batch(urls, options:) / batch_advanced(requests)
Process multiple screenshots in a batch.
# Simple batch results = client.batch( ['https://example1.com', 'https://example2.com'], options: RenderScreenshot::TakeOptions.url('').preset('og_card') ) # Advanced batch with per-URL options results = client.batch_advanced([ { url: 'https://example1.com', options: { preset: 'og_card' } }, { url: 'https://example2.com', options: { width: 1920 } }, ])
Returns: Hash
get_batch(batch_id)
Get the status of a batch job.
status = client.get_batch('batch_abc123') puts "#{status['completed']}/#{status['total']}"
Returns: Hash
presets / preset(id)
Get available presets.
presets = client.presets og_card = client.preset('og_card')
devices
Get available device presets.
devices = client.devices
TakeOptions
Immutable fluent builder for screenshot options. All methods return a new instance.
Creating Options
require 'renderscreenshot' # From URL options = RenderScreenshot::TakeOptions.url('https://example.com') # From HTML options = RenderScreenshot::TakeOptions.html('<h1>Hello World</h1>') # From hash options = RenderScreenshot::TakeOptions.from(url: '...', width: 1200)
Viewport Options
RenderScreenshot::TakeOptions.url('...') .width(1200) # Viewport width .height(630) # Viewport height .scale(2) # Device scale factor (1-3) .mobile # Enable mobile emulation
Capture Options
RenderScreenshot::TakeOptions.url('...') .full_page # Capture full scrollable page .element('.hero') # Capture specific element .format('png') # png, jpeg, webp, pdf .quality(90) # JPEG/WebP quality (1-100)
Wait Options
RenderScreenshot::TakeOptions.url('...') .wait_for('networkidle') # load, networkidle, domcontentloaded .delay(2000) # Additional delay (ms) .wait_for_selector('.loaded') # Wait for selector .wait_for_timeout(30000) # Max wait time (ms)
Presets & Devices
RenderScreenshot::TakeOptions.url('...') .preset('og_card') # Use a preset .device('iphone_14_pro') # Emulate a device
Content Blocking
RenderScreenshot::TakeOptions.url('...') .block_ads # Block ad networks .block_trackers # Block analytics .block_cookie_banners # Auto-dismiss cookie popups .block_chat_widgets # Block chat widgets .block_urls(['*.ads.com/*']) # Block URL patterns .block_resources(['font']) # Block resource types
Browser Emulation
RenderScreenshot::TakeOptions.url('...') .dark_mode # Enable dark mode .reduced_motion # Prefer reduced motion .media_type('print') # screen or print .user_agent('Custom UA') # Custom user agent .timezone('America/New_York') .locale('en-US') .geolocation(40.7128, -74.006)
Network Options
RenderScreenshot::TakeOptions.url('...') .headers({ 'X-Custom' => 'value' }) .cookies([{ name: 'session', value: 'abc', domain: 'example.com' }]) .auth_basic('user', 'pass') .auth_bearer('token') .bypass_csp
Cache Options
RenderScreenshot::TakeOptions.url('...') .cache_ttl(86400) # Cache TTL in seconds .cache_refresh # Force refresh
PDF Options
RenderScreenshot::TakeOptions.url('...') .format('pdf') .pdf_paper_size('a4') # a4, letter, legal, etc. .pdf_landscape .pdf_margin('1in') .pdf_print_background .pdf_header('<div>Header</div>') .pdf_footer('<div>Page <span class="pageNumber"></span></div>')
Storage Options (BYOS)
RenderScreenshot::TakeOptions.url('...') .storage_enabled .storage_path('{year}/{month}/{hash}.{ext}') .storage_acl('public-read')
Cache Management
cache = client.cache # Get cached screenshot image = cache.get('cache_xyz789') # Delete single entry cache.delete('cache_xyz789') # Bulk purge by keys cache.purge(['cache_abc', 'cache_def']) # Purge by URL pattern cache.purge_url('https://mysite.com/blog/*') # Purge by storage path pattern cache.purge_pattern('screenshots/2024/*') # Purge by date cache.purge_before(Time.now - 86400 * 7)
Webhook Helpers
# Verify signature is_valid = RenderScreenshot::Webhook.verify( payload: payload, signature: signature, timestamp: timestamp, secret: ENV['WEBHOOK_SECRET'] ) # Parse event event = RenderScreenshot::Webhook.parse(payload) if event[:event] == 'screenshot.completed' puts event[:data] end # Extract headers (case-insensitive) headers = RenderScreenshot::Webhook.extract_headers(request.headers)
Error Handling
begin client.take(RenderScreenshot::TakeOptions.url('...')) rescue RenderScreenshot::RateLimitError => e puts e.retry_after # Seconds to wait sleep(e.retry_after) if e.retry_after retry rescue RenderScreenshot::Error => e puts e.http_status # 400, 429, etc. puts e.code # 'invalid_url', 'rate_limited' puts e.message # Human-readable message puts e.retryable? # true/false puts e.request_id # Request ID for support end
Error Codes
| Code | HTTP | Retryable | Description |
|---|---|---|---|
invalid_request |
400 | No | Malformed request |
invalid_url |
400 | No | Invalid URL provided |
unauthorized |
401 | No | Invalid API key |
forbidden |
403 | No | Access denied |
not_found |
404 | No | Resource not found |
rate_limited |
429 | Yes | Rate limit exceeded |
timeout |
408 | Yes | Screenshot timed out |
render_failed |
500 | Yes | Browser rendering failed |
internal_error |
500 | Yes | Internal server error |