Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Gemfile.lock
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
PATH
remote: .
specs:
fileboost (0.1.5)
fileboost (0.2.0.pre2)
activestorage (>= 6.0)

GEM
Expand Down
143 changes: 137 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,39 @@

Fileboost is a Rails gem that provides seamless integration with the Fileboost.dev image optimization service. It offers drop-in replacement helpers for Rails' native image helpers with automatic optimization, HMAC authentication, and comprehensive transformation support for ActiveStorage objects.

## Table of Contents

- [Features](#features)
- [Installation](#installation)
- [Configuration](#configuration)
- [Usage](#usage)
- [Drop-in Replacement (Recommended)](#drop-in-replacement-recommended)
- [Manual Helper Method](#manual-helper-method)
- [URL Generation](#url-generation)
- [Transformation Options](#transformation-options)
- [Parameter Aliases](#parameter-aliases)
- [ActiveStorage Support](#activestorage-support)
- [ActiveStorage Variants (NEW in v0.2.0)](#activestorage-variants-new-in-v020)
- [Variant Transformation Mapping](#variant-transformation-mapping)
- [Combining Variants with Custom Options](#combining-variants-with-custom-options)
- [Responsive Images](#responsive-images)
- [Error Handling](#error-handling)
- [Security](#security)
- [Development](#development)
- [Testing](#testing)
- [Contributing](#contributing)
- [License](#license)
- [Support](#support)

## Features

- 🚀 **Drop-in replacement** for Rails `image_tag` and `url_for` helpers
- 🚀 **Drop-in replacement** for Rails `image_tag` with zero code changes (NEW in v0.2.0)
- 🎨 **Full ActiveStorage Variant support** with automatic transformation mapping (NEW in v0.2.0)
- 🔒 **Secure HMAC authentication** with Fileboost.dev service
- 📱 **ActiveStorage only** - works exclusively with ActiveStorage attachments
- 🎛️ **Comprehensive transformations** - resize, quality, format conversion, and more
- 🔧 **Simple configuration** - just project ID and token required
- 🔄 **Automatic fallback** - non-ActiveStorage images work exactly as before

## Installation

Expand Down Expand Up @@ -43,11 +69,59 @@ export FILEBOOST_PROJECT_ID="your-project-id"
export FILEBOOST_TOKEN="your-secret-token"
```

Or configure directly in your initializer:

```ruby
# config/initializers/fileboost.rb
Fileboost.configure do |config|
config.project_id = ENV["FILEBOOST_PROJECT_ID"]
config.token = ENV["FILEBOOST_TOKEN"]

# Optional: Enable drop-in replacement for Rails image_tag (default: false)
config.patch_image_tag = true
end
```

## Usage

### Basic Image Tag
### Drop-in Replacement (Recommended)

Enable `patch_image_tag` in your configuration to automatically optimize ActiveStorage images with your existing `image_tag` calls:

```ruby
# config/initializers/fileboost.rb
Fileboost.configure do |config|
config.project_id = ENV["FILEBOOST_PROJECT_ID"]
config.token = ENV["FILEBOOST_TOKEN"]
config.patch_image_tag = true # Enable automatic optimization
end
```

Replace `image_tag` with `fileboost_image_tag` for ActiveStorage objects:
With this enabled, your existing Rails code automatically gets Fileboost optimization:

```erb
<!-- This now automatically uses Fileboost for ActiveStorage objects -->
<%= image_tag user.avatar, resize: { w: 300, h: 300 }, alt: "Avatar" %>
<%= image_tag post.featured_image, resize: { width: 800, quality: 85 }, class: "hero" %>

<!-- ActiveStorage variants work seamlessly -->
<%= image_tag user.avatar.variant(resize_to_limit: [100, 100]), alt: "Thumbnail" %>
<%= image_tag post.image.variant(:thumb), alt: "Post thumbnail" %>

<!-- Non-ActiveStorage images work exactly as before -->
<%= image_tag "/assets/logo.png", alt: "Logo" %>
<%= image_tag "https://example.com/image.jpg", alt: "External" %>
```

**Benefits:**
- Zero code changes required for existing ActiveStorage images
- Full ActiveStorage variant support with automatic transformation mapping
- Automatic fallback to Rails behavior for non-ActiveStorage assets
- Gradual migration path - enable/disable with single configuration option

### Manual Helper Method

Alternatively, use `fileboost_image_tag` explicitly for ActiveStorage objects:

```erb
<!-- Before (Rails) -->
Expand Down Expand Up @@ -104,7 +178,7 @@ fileboost_image_tag(image, resize: { w: 400, h: 300, q: 85 })
fileboost_image_tag(image, resize: { width: 400, height: 300, quality: 85 })
```

**Note:** Avoid using the `format` parameter. Fileboost automatically selects the optimal image format (WebP, AVIF, JPEG, etc.) based on browser headers and capabilities for the best performance and compatibility.
**🎯 Smart Optimization:** Fileboost's CDN automatically detects and delivers the optimal image format (WebP, AVIF, JPEG, etc.) based on browser capabilities, device type, and connection speed for maximum performance.

### ActiveStorage Support

Expand All @@ -123,6 +197,63 @@ Works seamlessly with all ActiveStorage attachment types:
<%= fileboost_image_tag post.featured_image.blob, resize: { w: 800 } %>
```

### ActiveStorage Variants (NEW in v0.2.0)

Fileboost now provides full support for ActiveStorage variants with automatic transformation mapping:

```erb
<!-- Basic variants with automatic transformation mapping -->
<%= image_tag user.avatar.variant(resize_to_limit: [200, 200]) %>
<!-- ↓ Automatically becomes: w=200&h=200&fit=scale-down -->

<%= image_tag post.image.variant(resize_to_fit: [400, 300]) %>
<!-- ↓ Automatically becomes: w=400&h=300&fit=contain -->

<%= image_tag hero.banner.variant(resize_to_fill: [800, 400]) %>
<!-- ↓ Automatically becomes: w=800&h=400&fit=cover -->

<!-- Complex variants with multiple transformations -->
<%= image_tag post.image.variant(
resize_to_limit: [600, 400],
quality: 85
) %>
<!-- ↓ Automatically becomes: w=600&h=400&fit=scale-down&q=85 -->

<!-- Named variants work seamlessly -->
<%= image_tag user.avatar.variant(:thumb) %>
<!-- ↓ Uses predefined variant transformations -->
```

#### Variant Transformation Mapping

Fileboost automatically maps ActiveStorage variant transformations to optimized URL parameters:

| ActiveStorage Variant | Fileboost Parameters | Description |
|----------------------|---------------------|-------------|
| `resize_to_limit: [w, h]` | `w=W&h=H&fit=scale-down` | Resize within bounds, preserving aspect ratio |
| `resize_to_fit: [w, h]` | `w=W&h=H&fit=contain` | Resize to fit exactly, with letterboxing if needed |
| `resize_to_fill: [w, h]` | `w=W&h=H&fit=cover` | Resize and crop to fill exactly |
| `resize_and_pad: [w, h]` | `w=W&h=H&fit=pad` | Resize with padding |
| `quality: 85` | `q=85` | JPEG/WebP quality (1-100) |
| `rotate: "-90"` | `r=-90` | Rotation in degrees |


#### Combining Variants with Custom Options

You can combine variant transformations with additional Fileboost options:

```erb
<!-- Variant transformations + additional options -->
<%= image_tag user.avatar.variant(resize_to_limit: [200, 200]),
resize: { blur: 5, brightness: 110 } %>
<!-- ↓ Combines variant params with additional blur and brightness -->

<!-- Override variant parameters -->
<%= image_tag post.image.variant(resize_to_limit: [400, 300]),
resize: { w: 500 } %>
<!-- ↓ Uses h=300&fit=scale-down from variant, but overrides width to 500 -->
```

### Responsive Images

Generate multiple sizes for responsive designs:
Expand Down Expand Up @@ -171,7 +302,7 @@ After checking out the repo, run:

```bash
$ bundle install
$ rake test
$ bundle exec rspec
```

To test against the dummy Rails application:
Expand All @@ -186,7 +317,7 @@ $ rails server
Run the test suite:

```bash
$ rake test
$ bundle exec rspec
```

Run RuboCop:
Expand Down
2 changes: 2 additions & 0 deletions lib/fileboost.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
require "fileboost/config"
require "fileboost/error_handler"
require "fileboost/signature_generator"
require "fileboost/variant_transformer"
require "fileboost/url_builder"
require "fileboost/helpers"
require "fileboost/image_tag_patch"
require "fileboost/engine"

module Fileboost
Expand Down
3 changes: 2 additions & 1 deletion lib/fileboost/config.rb
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
module Fileboost
class Config
attr_accessor :project_id, :token
attr_accessor :project_id, :token, :patch_image_tag

CDN_DOMAIN = "cdn.fileboost.dev"
BASE_URL = "https://#{CDN_DOMAIN}"

def initialize
@project_id = ENV["FILEBOOST_PROJECT_ID"]
@token = ENV["FILEBOOST_TOKEN"]
@patch_image_tag = false
end

def valid?
Expand Down
5 changes: 5 additions & 0 deletions lib/fileboost/engine.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ class Engine < ::Rails::Engine
initializer "fileboost.action_view" do
ActiveSupport.on_load :action_view do
include Fileboost::Helpers

# Conditionally patch image_tag if enabled in configuration
if Fileboost.config.patch_image_tag
prepend Fileboost::ImageTagPatch
end
end
end
end
Expand Down
26 changes: 26 additions & 0 deletions lib/fileboost/image_tag_patch.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
module Fileboost
module ImageTagPatch
def image_tag(source, options = {})
# If this is an ActiveStorage asset and Fileboost is configured, use fileboost_image_tag
if valid_activestorage_asset?(source) && Fileboost.config.valid?
fileboost_image_tag(source, **options)
else
# Fall back to Rails' original image_tag for all other cases
super(source, options)
end
rescue
# If there's any error with Fileboost processing, fall back to original Rails behavior
super(source, options)
end

private

def valid_activestorage_asset?(asset)
return true if asset.is_a?(ActiveStorage::Blob)
return true if asset.is_a?(ActiveStorage::Attached)
return true if asset.is_a?(ActiveStorage::VariantWithRecord)

false
end
end
end
18 changes: 14 additions & 4 deletions lib/fileboost/url_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def self.build_url(asset, **options)
full_path = "/#{project_id}#{asset_path}"

# Extract and normalize transformation parameters
transformation_params = extract_transformation_params(options)
transformation_params = extract_transformation_params(asset, options)

# Generate HMAC signature for secure authentication
signature = Fileboost::SignatureGenerator.generate(
Expand Down Expand Up @@ -89,10 +89,16 @@ def self.extract_asset_path(asset)
end
end

def self.extract_transformation_params(options)
def self.extract_transformation_params(asset, options)
params = {}

# Only handle nested resize parameter
# First, extract variant transformations if this is a variant
if asset.is_a?(ActiveStorage::VariantWithRecord)
variant_params = Fileboost::VariantTransformer.transform_variant_params(asset)
params.merge!(variant_params)
end

# Then handle explicit resize parameter (this can override variant params)
if options[:resize].is_a?(Hash)
resize_options = options[:resize]
resize_options.each do |key, value|
Expand All @@ -117,9 +123,13 @@ def self.extract_transformation_params(options)

def self.normalize_param_value(key, value)
case key
when "w", "h", "q", "b", "br", "c", "r"
when "w", "h", "b", "br", "c", "r"
# Numeric parameters
value.to_i.to_s if value.to_i > 0
when "q"
# Quality parameter - validate range 1-100
q = value.to_i
(q > 0 && q <= 100) ? q.to_s : nil
when "f"
# Format parameter - validate against common formats
valid_formats = %w[webp jpeg jpg png gif avif]
Expand Down
Loading