css_inline-rails 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 14e855f556e322444a8be5b6637242c2651dcbcd14dfa86c6713acff9933e88a
4
+ data.tar.gz: d28484893f4fd5a7aaffff23e765a7a6835bfe7a8384ee2e12b34a23974f4659
5
+ SHA512:
6
+ metadata.gz: a33e5c782c5680885a531b5892bdc25bab7f1006fee3f6b7bb86b8f09abcea06fda1164fe7a32f4f043c52904669d17bf8409fc578596d609dc05b0edae78e4d
7
+ data.tar.gz: 672bd869c7fd448e2cd2631fdc0ad7fac3ac9e0c1bd6dfa6b489491a1f8d23779848400714450c3f789cb2b0cc28d52b08b1858529b9417d15b21bfb4be54808
data/CHANGELOG.md ADDED
@@ -0,0 +1,12 @@
1
+ # Changelog
2
+
3
+ ## [Unreleased]
4
+
5
+ ## [0.25.0] - 2026-12-03
6
+
7
+ ### Added
8
+
9
+ - ActionMailer interceptor that inlines CSS into outgoing HTML mail with `css_inline`.
10
+
11
+ [Unreleased]: https://github.com/Stranger6667/css-inline/compare/rails-v0.25.0...HEAD
12
+ [0.25.0]: https://github.com/Stranger6667/css-inline/compare/ruby-v0.25.0...rails-v0.25.0
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020-2026 Dmitry Dygalo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,191 @@
1
+ # css_inline-rails
2
+
3
+ Inlines CSS into your Rails emails with [`css_inline`](https://github.com/Stranger6667/css-inline),
4
+ which runs 64x to 191x faster than `premailer` and 9.6x to 583x faster than `roadie` in
5
+ [the benchmarks](https://github.com/Stranger6667/css-inline/tree/master/crates/css-inline-ruby#performance).
6
+
7
+ ```ruby
8
+ # Gemfile
9
+ gem "css_inline-rails"
10
+ ```
11
+
12
+ The gem registers an ActionMailer interceptor and a preview interceptor. They inline
13
+ `<style>` blocks and linked stylesheets into `style` attributes in every HTML message
14
+ you send with `deliver_now` or `deliver_later`, and in every mailer preview. Text-only
15
+ messages pass through unchanged.
16
+
17
+ Requires Ruby 3.2+ and Rails 7.1+.
18
+
19
+ ## Migrating from premailer-rails
20
+
21
+ ### No generated text part
22
+
23
+ `premailer-rails` generates a `text/plain` part for every HTML-only message unless you
24
+ set `generate_text_part: false`. This gem does not generate one.
25
+
26
+ If your mailers render only `format.html`, they will send HTML-only mail after the
27
+ swap. SpamAssassin's `MIME_HTML_ONLY` rule scores such mail, and any spec that reads
28
+ `text_part` or `parts` starts failing on `nil`. Add a text template next to each HTML
29
+ one (`welcome.text.erb`) and render both formats:
30
+
31
+ ```ruby
32
+ mail(to: user.email) do |format|
33
+ format.text
34
+ format.html
35
+ end
36
+ ```
37
+
38
+ ### Renames
39
+
40
+ Replace these across `app/` and `config/` in one pass. The old names do nothing here:
41
+ a leftover `skip_premailer` header goes out to the recipient, and the message gets
42
+ inlined anyway.
43
+
44
+ | premailer-rails | css_inline-rails |
45
+ |---|---|
46
+ | `skip_premailer: true` | `skip_css_inline: true` |
47
+ | `<style data-premailer="ignore">` | `<style data-css-inline="ignore">` plus `keep_style_tags: true` (see below) |
48
+ | `<link data-premailer="ignore">` | `<link data-css-inline="ignore">`, which removes the tag. `keep_link_tags: true` keeps every `<link>`, inlined ones included |
49
+ | `Premailer::Rails::Hook.perform(mail)` | `CSSInline::Rails::Hook.perform(mail)` |
50
+ | `Premailer::Rails.register_interceptors` | `CSSInline::Rails.register_interceptors` |
51
+
52
+ premailer leaves an ignored `<style>` in the output without inlining it.
53
+ `data-css-inline="ignore"` skips inlining but deletes the block, and
54
+ `keep_style_tags: true` brings it back, along with every other `<style>` block.
55
+ `data-css-inline="keep"` is not a substitute: it keeps the block but still inlines its
56
+ rules, so a broad rule such as `a { color: inherit }` overrides your linked stylesheet.
57
+
58
+ Remove `premailer-rails` from the Gemfile and delete `config/initializers/premailer*.rb`:
59
+ the app fails to boot with `uninitialized constant Premailer` while it references the old
60
+ gem. A custom premailer strategy keeps working unchanged, since both gems call `load(url)`
61
+ on it. Add it after the built-in strategies in `config/application.rb`:
62
+
63
+ ```ruby
64
+ config.css_inline.strategies += [MyPremailerStrategy]
65
+ ```
66
+
67
+ ### Linked stylesheets apply last
68
+
69
+ premailer, like a browser, applies stylesheets in document order. Here every linked
70
+ stylesheet applies after every `<style>` block, so at equal specificity a rule in
71
+ `email.css` beats a per-mail `<style>` override that follows the link. Give the
72
+ override a more specific selector, or move it into a stylesheet linked later.
73
+
74
+ ### Not supported
75
+
76
+ - The `:network` strategy: remote links are skipped. A Vite dev server URL such as
77
+ `/vite-dev/styles/email.css` raises `FileNotFound`. Add a
78
+ [custom strategy](#custom-strategies) that reads it from the dev server, or skip the
79
+ link in development with `data-css-inline="ignore"`.
80
+ - `-premailer-width`, `-premailer-cellpadding` and other `-premailer-*` properties: they
81
+ stay in the `style` attribute instead of becoming HTML attributes. Write
82
+ `width="100%"` and friends in the template.
83
+ - `remove_comments` and `remove_ids`: comments and ids stay in the output.
84
+ - Rules `css_inline` cannot inline, such as `:hover` or `::after`, are dropped.
85
+ premailer keeps them in a `<style>` block. Outside a kept block, only `@`-rules
86
+ survive, through `keep_at_rules`. Put the rules you need in a `<style data-css-inline="keep">` block.
87
+
88
+ ## How stylesheets are found
89
+
90
+ Mailer layouts link stylesheets like this:
91
+
92
+ ```erb
93
+ <%= stylesheet_link_tag "email" %>
94
+ ```
95
+
96
+ That renders a digested path such as `/assets/email-8f3a1c.css`, or
97
+ `https://cdn.example.com/assets/email-8f3a1c.css` with an asset host. `css_inline`
98
+ cannot fetch that path, so the gem resolves it from the URL path and passes the CSS to
99
+ `css_inline` as `extra_css`. It tries three strategies in order:
100
+
101
+ 1. `:filesystem` reads `public/`, where `assets:precompile` puts assets in production.
102
+ 2. `:sprockets` asks the Sprockets manifest.
103
+ 3. `:propshaft` asks Propshaft, so development works without precompiling.
104
+
105
+ If no strategy resolves a link without a host, `deliver_now` raises
106
+ `CSSInline::Rails::CSSHelper::FileNotFound` to the caller and sends nothing. With
107
+ `deliver_later` the job fails and ActiveJob's retry rules apply. A mailer preview shows
108
+ the error. All errors inherit from `CSSInline::Rails::Error`.
109
+
110
+ The gem skips a link with a host that no strategy resolves and never fetches it over the
111
+ network, because a CDN outage would then fail your mail. That covers Google Fonts, and
112
+ also your own asset host when the file is missing locally: the mail goes out without
113
+ that stylesheet. `css_inline` removes the skipped `<link>` tags. To keep a font link,
114
+ set `config.css_inline.inline_options = { keep_link_tags: true }`, which keeps every
115
+ `<link>`, the inlined stylesheets included.
116
+
117
+ ### Caching
118
+
119
+ With `config.enable_reloading = false`, the production default, the gem caches each
120
+ stylesheet by URL until the process restarts. Digested URLs change with the file, so
121
+ a deploy picks up new CSS. With reloading on, as in development, the gem reads
122
+ stylesheets for every message.
123
+
124
+ ### Custom strategies
125
+
126
+ A strategy is any object that responds to `load(url)` and returns the CSS as a string,
127
+ or `nil` to let the next strategy try:
128
+
129
+ ```ruby
130
+ module S3Loader
131
+ def self.load(url)
132
+ S3_BUCKET.object(URI.parse(url).path.delete_prefix("/")).get.body.read
133
+ rescue Aws::S3::Errors::NoSuchKey
134
+ nil
135
+ end
136
+ end
137
+
138
+ config.css_inline.strategies = [:filesystem, S3Loader]
139
+ ```
140
+
141
+ ## Media queries and kept tags
142
+
143
+ Media queries cannot be inlined. The gem sets `keep_at_rules: true`, so `css_inline`
144
+ inlines the rest of each stylesheet and keeps `@media` rules, including those from
145
+ linked files, in a `<style>` block, as premailer does. Set `keep_at_rules: false` in
146
+ `inline_options` to drop them.
147
+
148
+ `data-css-inline="ignore"` works on any element and skips inlining into it. On a
149
+ `<style>` or `<link>` it also removes the tag. `data-css-inline="keep"` inlines a
150
+ `<style>` block's rules and also leaves the block in the output, for clients that
151
+ support `<style>`:
152
+
153
+ ```erb
154
+ <style data-css-inline="keep">
155
+ a:hover { text-decoration: underline; }
156
+ </style>
157
+ ```
158
+
159
+ ## Configuration
160
+
161
+ Set options in `config/application.rb` or an environment file:
162
+
163
+ ```ruby
164
+ config.css_inline.inline_options = { keep_style_tags: true }
165
+ config.css_inline.strategies = %i[filesystem propshaft]
166
+ ```
167
+
168
+ | Key | Default | Meaning |
169
+ |---|---|---|
170
+ | `inline_options` | `{}` | Passed to `CSSInline.inline`, see [the options](https://github.com/Stranger6667/css-inline/tree/master/crates/css-inline-ruby#configuration) |
171
+ | `strategies` | `%i[filesystem sprockets propshaft]` | Tried in order for each linked stylesheet |
172
+
173
+ `load_remote_stylesheets` in `inline_options` has no effect: the gem resolves links
174
+ itself. An `extra_css` you configure comes before the linked CSS, so linked rules win at
175
+ equal specificity.
176
+
177
+ To keep the options in `config/css_inline.yml`:
178
+
179
+ ```ruby
180
+ config.css_inline = config_for(:css_inline)
181
+ ```
182
+
183
+ Skip a single message:
184
+
185
+ ```ruby
186
+ mail(to: "user@example.com", skip_css_inline: true)
187
+ ```
188
+
189
+ ## License
190
+
191
+ MIT
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "concurrent/map"
4
+ require "nokogiri"
5
+ require "uri"
6
+
7
+ module CSSInline
8
+ module Rails
9
+ # `css_inline` cannot fetch an `/assets/...` href; only the asset pipeline
10
+ # can resolve one. So the hrefs are resolved here and handed over as
11
+ # `extra_css`.
12
+ module CSSHelper
13
+ extend self
14
+
15
+ HEAD_END = %r{</head\s*>}i
16
+ LINK = /<link/i
17
+
18
+ class FileNotFound < Error; end
19
+
20
+ attr_accessor :cache
21
+ self.cache = Concurrent::Map.new
22
+
23
+ def css_for_html(html)
24
+ css = stylesheet_urls(html).filter_map { |url| css_for_url(url) }
25
+ css.join("\n") unless css.empty?
26
+ end
27
+
28
+ def css_for_url(url)
29
+ return load_css(url) if CSSLoaders::App.reloading?
30
+
31
+ cache.compute_if_absent(url) { load_css(url) }
32
+ end
33
+
34
+ private
35
+
36
+ # `css_inline` removes stylesheet links anywhere, but parsing a whole body
37
+ # costs about as much as inlining it, so `<head>` alone when no `<link`
38
+ # follows it. Parsed only to read hrefs; `css_inline` gets the original.
39
+ def stylesheet_urls(html)
40
+ Nokogiri::HTML(link_scope(html))
41
+ .css('link[rel="stylesheet"]')
42
+ .reject { |link| link["data-css-inline"] == "ignore" }
43
+ .map { |link| link["href"].to_s }
44
+ .reject(&:empty?)
45
+ .select { |url| web_url?(url) }
46
+ end
47
+
48
+ def link_scope(html)
49
+ head_end = HEAD_END.match(html)&.end(0)
50
+ return html if head_end.nil? || html.match?(LINK, head_end)
51
+
52
+ html[0, head_end]
53
+ end
54
+
55
+ # `data:` and `cid:` hrefs are not files any strategy can find.
56
+ def web_url?(url)
57
+ scheme = URI.parse(url).scheme
58
+ scheme.nil? || %w[http https].include?(scheme)
59
+ rescue URI::InvalidURIError
60
+ false
61
+ end
62
+
63
+ # Sprockets reads precompiled files as binary and a custom strategy can
64
+ # return anything, so the result is relabelled as UTF-8. A BOM goes:
65
+ # css_inline reads it as part of the first selector.
66
+ #
67
+ # Like premailer-rails, the path decides, so a link on the asset host
68
+ # resolves locally. An unresolved link with a host is someone else's,
69
+ # such as a font CDN, and is skipped.
70
+ def load_css(url)
71
+ CSSInline::Rails.config.fetch(:strategies).each do |strategy|
72
+ css = strategy_for(strategy).load(url)
73
+ return String.new(css, encoding: Encoding::UTF_8).delete_prefix("\uFEFF") if css
74
+ end
75
+ return if URI.parse(url).host
76
+
77
+ raise FileNotFound, %(Stylesheet "#{url}" could not be loaded by any strategy.)
78
+ end
79
+
80
+ # A name is a symbol, or a string from YAML config; anything else is a
81
+ # strategy object of its own. An unknown name is a typo.
82
+ def strategy_for(key)
83
+ return key unless key.is_a?(Symbol) || key.is_a?(String)
84
+
85
+ case key.to_sym
86
+ when :filesystem then CSSLoaders::FileSystemLoader
87
+ when :sprockets then CSSLoaders::SprocketsLoader
88
+ when :propshaft then CSSLoaders::PropshaftLoader
89
+ else raise ArgumentError, "Unknown css_inline-rails strategy: #{key.inspect}"
90
+ end
91
+ end
92
+ end
93
+ end
94
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CSSInline
4
+ module Rails
5
+ module CSSLoaders
6
+ # Both pipelines precompile into `public/` + the assets prefix, so in
7
+ # production the digested file is already on disk:
8
+ # https://github.com/rails/propshaft/blob/v1.3.2/lib/propshaft/railtie.rb#L42
9
+ module FileSystemLoader
10
+ extend self
11
+
12
+ # UTF-8 regardless of locale: under `LANG=C` Rails' `default_internal`
13
+ # makes a plain read raise on the first non-ASCII byte.
14
+ def load(url)
15
+ path = file_name(url)
16
+ ::File.read(path, encoding: Encoding::UTF_8) if path && ::File.file?(path)
17
+ end
18
+
19
+ private
20
+
21
+ # The assets prefix stays, it is a directory under `public/`. The
22
+ # relative URL root goes, it is a mount point.
23
+ def file_name(url)
24
+ path = App.decoded_path(url)
25
+ return if path.nil?
26
+
27
+ root = App.relative_url_root
28
+ path = path.delete_prefix(root.chomp("/")) if root && !root.empty?
29
+ contained(::File.join(public_root, path))
30
+ end
31
+
32
+ # `..` in an href must not read outside `public/`.
33
+ def contained(path)
34
+ root = ::File.expand_path(public_root)
35
+ expanded = ::File.expand_path(path)
36
+ expanded if expanded.start_with?("#{root}#{::File::SEPARATOR}")
37
+ end
38
+
39
+ def public_root
40
+ root = App.root
41
+ root ? ::File.join(root, "public") : "public"
42
+ end
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CSSInline
4
+ module Rails
5
+ module CSSLoaders
6
+ # Mirrors how Propshaft's own middleware serves `/assets/*`:
7
+ # https://github.com/rails/propshaft/blob/v1.3.2/lib/propshaft/server.rb#L16-L20
8
+ module PropshaftLoader
9
+ extend self
10
+
11
+ # Propshaft's own pattern, the same in 0.x and 1.x. Only 1.x exposes it,
12
+ # as `Propshaft::Asset.extract_path_and_digest`:
13
+ # https://github.com/rails/propshaft/blob/v1.3.2/lib/propshaft/asset.rb#L11-L16
14
+ DIGEST = /-([0-9a-zA-Z]{7,128})\.(?!digested)([^.]|.map)+\z/
15
+
16
+ def load(url)
17
+ return unless available?
18
+
19
+ asset = find_asset(url)
20
+ assembly.compilers.compile(asset) if asset
21
+ end
22
+
23
+ private
24
+
25
+ # The pattern also matches an ordinary hyphenated name, so the path is
26
+ # tried as written before the digest is stripped.
27
+ def find_asset(url)
28
+ path = App.relative_path(url)
29
+ return if path.nil?
30
+
31
+ digest = path[DIGEST, 1]
32
+ undigested = digest ? path.sub("-#{digest}", "") : path
33
+ assembly.load_path.find(path) || assembly.load_path.find(undigested)
34
+ end
35
+
36
+ def assembly
37
+ App.application.assets
38
+ end
39
+
40
+ # Sprockets also answers `application.assets`, with a different object.
41
+ def available?
42
+ return false unless defined?(::Propshaft)
43
+
44
+ app = App.application
45
+ app.respond_to?(:assets) && app.assets.is_a?(::Propshaft::Assembly)
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CSSInline
4
+ module Rails
5
+ module CSSLoaders
6
+ # `assets_manifest` is what sprockets-rails hangs off the application:
7
+ # https://github.com/rails/sprockets-rails/blob/v3.5.2/lib/sprockets/railtie.rb#L34
8
+ #
9
+ # `find_sources` returns the compiled source for a logical path:
10
+ # https://github.com/rails/sprockets/blob/v4.4.1/lib/sprockets/manifest.rb#L139-L152
11
+ module SprocketsLoader
12
+ extend self
13
+
14
+ # Sprockets appends an MD5 (32) or SHA256 (64) hex digest before the
15
+ # extension. Unlike Propshaft it exposes no helper to strip one.
16
+ DIGEST = /-(\h{32}|\h{64})\.css\z/
17
+
18
+ def load(url)
19
+ return unless available?
20
+
21
+ path = App.relative_path(url)
22
+ return if path.nil?
23
+
24
+ manifest.find_sources(path).first || manifest.find_sources(path.sub(DIGEST, ".css")).first
25
+ # The manifest can list a file that is missing on disk.
26
+ rescue Errno::ENOENT
27
+ nil
28
+ end
29
+
30
+ private
31
+
32
+ def manifest
33
+ App.application.assets_manifest
34
+ end
35
+
36
+ def available?
37
+ app = App.application
38
+ app.respond_to?(:assets_manifest) && app.assets_manifest
39
+ end
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+
5
+ module CSSInline
6
+ module Rails
7
+ module CSSLoaders
8
+ # Every read of Rails state goes through here. `::Rails` can exist without
9
+ # an application (rails-html-sanitizer defines the namespace), and
10
+ # `::Rails.configuration` raises until one boots.
11
+ module App
12
+ extend self
13
+
14
+ def application
15
+ return unless defined?(::Rails) && ::Rails.respond_to?(:application)
16
+
17
+ ::Rails.application
18
+ end
19
+
20
+ def config
21
+ application&.config
22
+ end
23
+
24
+ def root
25
+ return unless defined?(::Rails) && ::Rails.respond_to?(:root)
26
+
27
+ ::Rails.root
28
+ end
29
+
30
+ # https://guides.rubyonrails.org/configuring.html#config-relative-url-root
31
+ def relative_url_root
32
+ config.respond_to?(:relative_url_root) ? config.relative_url_root : nil
33
+ end
34
+
35
+ # `/assets` by default:
36
+ # https://github.com/rails/propshaft/blob/v1.3.2/lib/propshaft/railtie.rb#L11
37
+ def assets_prefix
38
+ assets = config.respond_to?(:assets) ? config.assets : nil
39
+ assets&.prefix
40
+ end
41
+
42
+ # Code reloading means assets can change between messages too.
43
+ def reloading?
44
+ config.nil? || config.enable_reloading
45
+ end
46
+
47
+ def url_prefix
48
+ ::File.join(relative_url_root.to_s, assets_prefix.to_s, "/")
49
+ end
50
+
51
+ # The logical asset path: `/sub/assets/a.css` -> `a.css`.
52
+ def relative_path(url)
53
+ decoded_path(url)&.delete_prefix(url_prefix)
54
+ end
55
+
56
+ # `nil` for anything unusable, so a loader declines instead of raising
57
+ # out of the delivery interceptor.
58
+ def decoded_path(url)
59
+ path = URI.parse(url.to_s).path.to_s
60
+ return if path.empty?
61
+
62
+ URI.decode_www_form_component(path)
63
+ rescue URI::InvalidURIError, ArgumentError
64
+ nil
65
+ end
66
+ end
67
+ end
68
+ end
69
+ end
70
+
71
+ require "css_inline/rails/css_loaders/file_system_loader"
72
+ require "css_inline/rails/css_loaders/sprockets_loader"
73
+ require "css_inline/rails/css_loaders/propshaft_loader"
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CSSInline
4
+ module Rails
5
+ class Hook
6
+ SKIP_HEADER = :skip_css_inline
7
+ FALSEY = ["", "false", "0"].freeze
8
+
9
+ attr_reader :message
10
+
11
+ class << self
12
+ # The ActionMailer interceptor interface: `delivering_email` for
13
+ # `register_interceptor`, `previewing_email` for the preview variant.
14
+ def delivering_email(message)
15
+ new(message).perform
16
+ message
17
+ end
18
+
19
+ alias_method :previewing_email, :delivering_email
20
+ # premailer-rails' name, for apps that run the hook by hand.
21
+ alias_method :perform, :delivering_email
22
+ end
23
+
24
+ def initialize(message)
25
+ @message = message
26
+ end
27
+
28
+ def perform
29
+ skip_inlining = skip?
30
+ message.header[SKIP_HEADER] = nil
31
+ return if skip_inlining
32
+
33
+ inline_html_part if html_part
34
+ end
35
+
36
+ private
37
+
38
+ # `Mail::Header#[]=` only deletes on `nil`, so `skip_css_inline: false`
39
+ # still creates the field, with an empty value.
40
+ #
41
+ # Set twice, Mail returns an Array. The first is the action's own
42
+ # `headers[]=`: ActionMailer appends mailer defaults after it.
43
+ def skip?
44
+ field = message.header[SKIP_HEADER]
45
+ field = field.first if field.is_a?(Array)
46
+ return false if field.nil?
47
+
48
+ !FALSEY.include?(field.value.to_s.strip.downcase)
49
+ end
50
+
51
+ # Not `content_type.include?`: `multipart/related; type="text/html"`
52
+ # contains "text/html" without being it, and `decoded` raises on it.
53
+ def pure_html_message?
54
+ message.mime_type == "text/html"
55
+ end
56
+
57
+ def html_part
58
+ return @html_part if defined?(@html_part)
59
+
60
+ @html_part = pure_html_message? ? message : message.html_part
61
+ end
62
+
63
+ # A part Mail already encoded keeps its transfer encoding through
64
+ # `body=`, which would label the new plain HTML as, say, base64.
65
+ #
66
+ # With no declared charset Mail decodes to bytes; those are read as UTF-8,
67
+ # and a body that is not valid UTF-8 is left as it is.
68
+ def inline_html_part
69
+ html = html_part.decoded
70
+ html = html.dup.force_encoding(Encoding::UTF_8) if html.encoding == Encoding::BINARY
71
+ return unless html.valid_encoding?
72
+
73
+ html = CSSInline::Rails.inline(html)
74
+ html_part.content_transfer_encoding = nil
75
+ html_part.body = html
76
+ html_part.content_type = "text/html; charset=#{html.encoding}"
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CSSInline
4
+ module Rails
5
+ class Railtie < ::Rails::Railtie
6
+ # The same object, so `config.css_inline.inline_options = {...}` in
7
+ # `config/application.rb` or an environment file configures the gem.
8
+ config.css_inline = CSSInline::Rails.config
9
+
10
+ # `config.css_inline = config_for(:css_inline)` swaps in another object.
11
+ config.after_initialize do |app|
12
+ configured = app.config.css_inline
13
+ app.config.css_inline = CSSInline::Rails.config.merge!(configured) unless configured.equal?(CSSInline::Rails.config)
14
+ end
15
+
16
+ # Not an `initializer`: those never run for a gem required after boot,
17
+ # e.g. `require: false` plus a require in `config/initializers`.
18
+ ActiveSupport.on_load(:action_mailer) { CSSInline::Rails.register_interceptors }
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CSSInline
4
+ module Rails
5
+ # Kept in lockstep with `css_inline`, as every other binding in this repo is.
6
+ VERSION = "0.25.0"
7
+ end
8
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "css_inline"
4
+ require "action_mailer"
5
+ require "active_support/ordered_options"
6
+ # `action_mailer` only autoloads it; `Hook` needs `Mail::Part`.
7
+ require "mail"
8
+
9
+ module CSSInline
10
+ module Rails
11
+ class Error < StandardError; end
12
+
13
+ # Fresh each call, so mutating `config` cannot reach the defaults.
14
+ def self.default_config
15
+ ActiveSupport::OrderedOptions.new.merge!(
16
+ strategies: %i[filesystem sprockets propshaft],
17
+ inline_options: {}
18
+ )
19
+ end
20
+
21
+ # No writer: the Railtie hands this object out as `config.css_inline`.
22
+ class << self
23
+ attr_reader :config
24
+ end
25
+ @config = default_config
26
+
27
+ # Called by the Railtie. Apps that order interceptors themselves can call
28
+ # it earlier; Mail ignores a second registration.
29
+ def self.register_interceptors
30
+ ActionMailer::Base.register_interceptor(Hook)
31
+ ActionMailer::Base.register_preview_interceptor(Hook)
32
+ end
33
+
34
+ # `keep_at_rules` by default: media queries cannot be inlined, and dropping
35
+ # them breaks responsive and dark-mode mail.
36
+ def self.inline(html)
37
+ options = {keep_at_rules: true}
38
+ .merge(config.fetch(:inline_options, {}).to_h.symbolize_keys)
39
+ .merge(load_remote_stylesheets: false)
40
+ # Configured `extra_css` is kept, not replaced by what the links resolved to.
41
+ extra_css = [options[:extra_css], CSSHelper.css_for_html(html)].compact.join("\n")
42
+ options[:extra_css] = extra_css unless extra_css.empty?
43
+ CSSInline.inline(html, **options)
44
+ end
45
+ end
46
+ end
47
+
48
+ require "css_inline/rails/version"
49
+ require "css_inline/rails/css_loaders"
50
+ require "css_inline/rails/css_helper"
51
+ require "css_inline/rails/hook"
52
+ require "css_inline/rails/railtie" if defined?(::Rails::Railtie)
metadata ADDED
@@ -0,0 +1,101 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: css_inline-rails
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.25.0
5
+ platform: ruby
6
+ authors:
7
+ - Dmitry Dygalo
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: actionmailer
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '7.1'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '7.1'
26
+ - !ruby/object:Gem::Dependency
27
+ name: css_inline
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - "~>"
31
+ - !ruby/object:Gem::Version
32
+ version: 0.25.0
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: 0.25.0
40
+ - !ruby/object:Gem::Dependency
41
+ name: nokogiri
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '1.13'
47
+ type: :runtime
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '1.13'
54
+ description: |
55
+ Hooks `css_inline` into ActionMailer so that stylesheets linked from your
56
+ mailer views are inlined into "style" attributes on delivery.
57
+ email:
58
+ - dmitry@dygalo.dev
59
+ executables: []
60
+ extensions: []
61
+ extra_rdoc_files: []
62
+ files:
63
+ - CHANGELOG.md
64
+ - LICENSE
65
+ - README.md
66
+ - lib/css_inline/rails.rb
67
+ - lib/css_inline/rails/css_helper.rb
68
+ - lib/css_inline/rails/css_loaders.rb
69
+ - lib/css_inline/rails/css_loaders/file_system_loader.rb
70
+ - lib/css_inline/rails/css_loaders/propshaft_loader.rb
71
+ - lib/css_inline/rails/css_loaders/sprockets_loader.rb
72
+ - lib/css_inline/rails/hook.rb
73
+ - lib/css_inline/rails/railtie.rb
74
+ - lib/css_inline/rails/version.rb
75
+ homepage: https://github.com/Stranger6667/css-inline
76
+ licenses:
77
+ - MIT
78
+ metadata:
79
+ bug_tracker_uri: https://github.com/Stranger6667/css-inline/issues
80
+ changelog_uri: https://github.com/Stranger6667/css-inline/tree/master/crates/css-inline-ruby/rails/CHANGELOG.md
81
+ source_code_uri: https://github.com/Stranger6667/css-inline/tree/master/crates/css-inline-ruby/rails
82
+ funding_uri: https://github.com/sponsors/Stranger6667/
83
+ rubygems_mfa_required: 'true'
84
+ rdoc_options: []
85
+ require_paths:
86
+ - lib
87
+ required_ruby_version: !ruby/object:Gem::Requirement
88
+ requirements:
89
+ - - ">="
90
+ - !ruby/object:Gem::Version
91
+ version: 3.2.0
92
+ required_rubygems_version: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ requirements: []
98
+ rubygems_version: 3.6.9
99
+ specification_version: 4
100
+ summary: Inline CSS into Rails emails with css_inline
101
+ test_files: []