Commit Graph

108 Commits

Author SHA1 Message Date
Kaíque Kandy Koga
0dc71acf39 Apply field_error_proc to rich_text_area fields 2022-12-22 11:52:30 -06:00
Jorge Manrubia
14cd0c4dee
Avoid unnecessary replacements when the node doesn't change
This represents a +2x performance optimization when the replacement
logic is based on some condition, and it returns the same unchanged
node when it wants to skip it:

 ```ruby
 html = <<~HTML
       <div>
         #{'<p>ignore me</p>' * 1000}
         #{'<p>replace me</p>' * 1000}
       </div>
 HTML

 content = content_from_html(html)

 replacement_example = -> do
   content.fragment.replace("p") do |node|
     if node.text =~ /replace me/
       "<p>replace me</p>"
     else
       node
     end
   end
 end

 current_implementation = -> do
   class ActionText::Fragment
     def replace(selector)
       update do |source|
         source.css(selector).each do |node|
           replacement_node = yield(node)
           node.replace(replacement_node.to_s)
         end
       end
     end
   end

   replacement_example.call
 end

 new_implementation = -> do
   class ActionText::Fragment
     def replace(selector)
       update do |source|
         source.css(selector).each do |node|
           replacement_node = yield(node)
           node.replace(replacement_node.to_s) if node != replacement_node
         end
       end
     end
   end

   replacement_example.call
 end

 Benchmark.ips do |x|
   x.report "Current implementation", &current_implementation
   x.report "New implementation", &new_implementation

   x.compare!
 end
 ```

 Results:

 ```
 Warming up --------------------------------------
 Current implementation
                          2.000  i/100ms
   New implementation     5.000  i/100ms
 Calculating -------------------------------------
   Current implementation
                          32.484  (±30.8%) i/s -    134.000  in   5.036419s
   New implementation     74.878  (±38.7%) i/s -    250.000  in   5.052168s

 Comparison:
   New implementation:       74.9 i/s
   Current implementation:       32.5 i/s - 2.31x  (± 0.00) slower
 ```
2022-12-17 22:39:51 +01:00
Jonathan Hefner
93038baad7 Use routes.default_url_options in AC::Renderer env
When a host is not specified for an `ActionController::Renderer`'s env,
the host and related options will now be derived from the routes'
`default_url_options` and `ActionDispatch::Http::URL.secure_protocol`.

For example, with:

  ```ruby
  Rails.application.default_url_options = { host: "rubyonrails.org" }
  Rails.application.config.force_ssl = true
  ```

Before:

  ```ruby
  ApplicationController.renderer.render inline: "<%= blog_url %>"
  # => "http://example.org/blog"
  ```

After:

  ```ruby
  ApplicationController.renderer.render inline: "<%= blog_url %>"
  # => "https://rubyonrails.org/blog"
  ```

As a consequence, Action Text attachment URLs rendered in a background
job (a la Turbo Streams) will now use `Rails.application.default_url_options`.

Fixes #41795.
Fixes hotwired/turbo-rails#54.
Fixes hotwired/turbo-rails#155.
2022-12-15 16:22:07 -06:00
David Heinemeier Hansson
d18fc32999
Use storage/ instead of db/ for sqlite3 db files (#46699)
* Use storage/ instead of db/ for sqlite3 db files

db/ should be for configuration only, not data. This will make it easier to mount a single volume into a container for testing, development, and even sqlite3 in production.
2022-12-12 08:32:12 +01:00
Sean Doyle
67a4ac6c56 Focus editor after calling fill_in_rich_text_area
When System Tests call `fill_in_rich_text_area`, they interact with
`<trix-editor>` elements by changing the contents programmatically.

This is unlike how end-users will interact with the element. Overhauling
the test helper to more accurately reflect Real World usage would
require a sizable effort.

With that being said, leaving the `<trix-editor>` with focus after
populating its contents is a minor change that makes it a more genuine
recreation.
2022-12-09 09:48:27 -05:00
Eileen M. Uchitelle
f002536a5d
Merge pull request #46271 from seanpdoyle/has-rich-text-strict-loading
Support `has_rich_text` with `strict_loading:`
2022-12-09 08:44:07 -05:00
Evan Brooks
8d3408e41a Update mailer templates meta tag mailer.html.erb 2022-11-14 21:38:07 -04:00
Sean Doyle
4a743b9e0a Support has_rich_text with strict_loading:
Expand the `has_rich_text` signature to accept a `strict_loading:`
value. Forward that value along to the `has_one` declaration made under
the hood. When omitted, `strict_loading:` will be set to the value of
the `strict_loading_by_default` class attribute (false by default).
2022-10-18 17:06:26 -04:00
Eike Send
5ba8aa5854
Facilitate use of any regular ERB in database.yml
Commit 37d1429ab1d introduced the DummyERB to avoid loading the environment when
running `rake -T`.

The DummyCompiler simply replaced all output from `<%=` with a fixed string and
removed everything else. This worked okay when it was used for YAML values.
When using `<%=` within a YAML key, it caused an error in the YAML parser,
making it impossible to use ERB as you would expect. For example a
`database.yml` file containing the following should be possible:

  development:
    <% 5.times do |i| %>
    shard_<%= i %>:
      database: db/development_shard_<%= i %>.sqlite3
      adapter: sqlite3
    <% end %>

Instead of using a broken ERB compiler we can temporarily use a
`Rails.application.config` that does not raise an error when configurations are
accessed which have not been set as described in #35468.

This change removes the `DummyCompiler` and uses the standard `ERB::Compiler`.
It introduces the `DummyConfig` which delegates all known configurations to the
real `Rails::Application::Configuration` instance and returns a dummy string for
everything else. This restores the full ERB capabilities without compromising on
speed when generating the rake tasks for multiple databases.

Deprecates `config.active_record.suppress_multiple_database_warning`.
2022-09-27 17:07:40 +02:00
Yasuo Honda
0b80408b24 Use system(.., exception: true) for dummy apps
Related to #46064
2022-09-20 22:53:05 +09:00
Jamis Buck
5f342cfdbe make sure rendering the content attachment actually works 2022-08-04 10:07:23 -06:00
Jamis Buck
9918ce4a78 linter appeasement 2022-08-03 08:19:41 -06:00
Jamis Buck
4499a3cdd0 update ContentAttachment so that it works with "content" attributes
this makes it possible for an application to embed markup in a document
that would otherwise be undesirable or expensive to process. For example,
an incoming email may include a complicated bit of DOM in a quote, and
while you don't want to have to process and rewrite it, you also don't want
to discard it; the content attribute of ContentAttachment allows you to
make that work.
2022-08-02 15:08:16 -06:00
Jonathan Hefner
471ab2347f Omit workers and preload_app! from Puma config
Since Puma 5.0 (puma/puma@05936689c8),
Puma will automatically set `workers` to `ENV["WEB_CONCURRENCY"] || 0`.
Additionally, if `ENV["WEB_CONCURRENCY"]` > 1, Puma will automatically
set `preload_app`.

This can lead to confusing scenarios for users who are unaware of this
behavior and have customized `config/puma.rb`.  For example, if a user
uncomments the `workers` and `preload_app!` directives, it is clear that
Puma will preload the app, and the number of workers can be configured
by setting `ENV["WEB_CONCURRENCY"]`.  If the user sets
`ENV["WEB_CONCURRENCY"]` > 1, but then changes their mind and removes
the `workers` or `preload_app!` directives *without* clearing
`ENV["WEB_CONCURRENCY"]`, Puma will still preload the app and launch
`ENV["WEB_CONCURRENCY"]` number of workers.  Similarly, if a user
uncomments *only* the `workers` directive and sets
`ENV["WEB_CONCURRENCY"]` > 1, Puma will preload the app even though the
`preload_app!` directive is still commented out.

To avoid such scenarios, this commit removes the commented-out `workers`
and `preload_app!` directives from the default `config/puma.rb`.

Also, to improve discoverability of available configuration options,
this commit adds a link to the Puma DSL documentation at the top of the
file.
2022-06-03 12:38:21 -05:00
Xavier Noria
2953ae5c8a Define config.enable_reloading to be !config.cache_classes
Every time I write `config.cache_classes` I have to pause for a moment to make
sure I get it right. It makes you think.

On the other hand, if you read `config.enable_reloading = true`, does the
application reload? You do not need to spend 1 cycle of brain CPU to nod.
2022-04-14 18:11:36 +02:00
Andrew White
e9e2fd6f9f
Fix deprecation warnings in Action Text tests
Support for the image/jpg content type will be removed in Rails 7.1
and the use of it within the Action Text tests appears to be a typo.
2022-03-19 07:20:31 +00:00
Jean Boussier
e26372b713 Implicitly assert no exception is raised in assert_queries & al
Fix: https://github.com/rails/rails/pull/44397
Ref: https://github.com/rails/rails/pull/37313
Ref: https://github.com/rails/rails/pull/42459

This avoid mistakes such as:

```ruby
assert_raise Something do
  assert_queries(1) do
    raise Something
  end
end
```

Co-Authored-By: Alex Coomans <alexc@squareup.com>
2022-02-19 09:11:14 +01:00
Gannon McGibbon
aaa64687e8
Revert #38957 (#44287)
* Revert "Pass service_name param to DirectUploadsController"

This reverts commit 193289dbbe146c56ec16faf8dd1a2c88611feb83.

* Revert "Multi-service direct uploads in Action Text attachment uploads"

This reverts commit 0b69ad4de6ef89c285833a90dd23db25cad7b669.
2022-01-29 14:27:45 +01:00
Jonathan Hefner
4917ee9df6 Use dynamic Rails version in framework dummy apps
This matches what we currently generate for plugin dummy apps.
2021-12-08 11:31:49 -06:00
Rafael Mendonça França
83d85b2207
Start Rails 7.1 development 2021-12-07 15:52:30 +00:00
DmitryTsepelev
193289dbbe Support direct uploads to multiple services 2021-11-14 11:49:06 +03:00
matt swanson
0b1f83d0bc
Better ActionText plain text output for nested lists (#37976)
* Improve plaintext output for nested lists

* Update plain_text_conversion_test.rb

* Add additional test cases

* Refactor a bit

* Add changelog entry

* Rearrange methods

Co-authored-by: Matt Swanson <matt@mdswanson.com>
2021-10-12 18:05:04 +02:00
Ryan Baumann
58127ec6d5 Fix tests for actiontext with hidden inputs defaulting to autocomplete="off" 2021-09-21 21:16:01 -04:00
Alexandre Ruban
458908ed42 Fix ActionText::Serialization when dumping an ActionText::RichText 2021-09-20 10:36:20 +02:00
Lucas Mansur
bac0038e20
Don't overwrite default opts in rich_text_area_tag (#43156)
You may want to use your own controller to authenticate requests or
perform server-side validations.
2021-09-19 20:56:17 +02:00
Alex Ghiculescu
5acc32ac54
Generate less initializers in new/upgraded Rails apps (part 2) (#43237) 2021-09-17 09:06:17 +02:00
Rafael Mendonça França
fd41ea1f2d
Merge branch 'main' into less-initializers 2021-09-15 17:18:49 -04:00
David Heinemeier Hansson
e34300a921
Stop trying to configure listen by default on compatible platforms (#42985)
* Stop trying to configure listen by default on compatible platforms

Modern computers with SSDs don't see much/any benefit from having an evented file update watcher. Remove complexity by taking this spinning-drive concession out.

* Actually need listen for testing the opt-in

* Test no longer relevant
2021-08-11 15:18:43 +02:00
Hartley McGuire
bcb300dccb Replace uglifier with terser in dummy applications
Terser is more up to date with modern javascript features, and the
uglifier gem repository recommends using it for minifying ES6+.

Followup for 955041b
2021-06-28 00:48:56 -04:00
Zachary Scott
c797ce966c Update test dummy application defaults
Affected gems:

* actionmailbox
* activestorage
* actiontext

This fixes the following warning:

DEPRECATION WARNING: Using legacy connection handling is deprecated. Please set
`legacy_connection_handling` to `false` in your application.

The new connection handling does not support `connection_handlers`
getter and setter.

Read more about how to migrate at: https://guides.rubyonrails.org/active_record_multiple_databases.html#migrate-to-the-new-connection-handling
 (called from require at ~/.gem/ruby/3.1.0/gems/zeitwerk-2.4.2/lib/zeitwerk/kernel.rb:34)
2021-06-21 07:00:32 +09:00
Alex Ghiculescu
de238125ef Generate less initializers in new/upgraded Rails apps
Currently when you make a new Rails app, we generate a lot of initializers. For new users, I think we should try and include as few as possible - the less files, the less daunting a new app is. And for upgrades I'd like to [continue to simplify the update process](https://github.com/rails/rails/pull/41083), in this case by not bringing back initializers you have probably already dismissed or modified.

In this PR I'm proposing we remove two initializers: `application_controller_renderer.rb` and `cookies_serializer.rb`:

**`application_controller_renderer.rb`**. This configures [`ActionController::Renderer`](https://api.rubyonrails.org/classes/ActionController/Renderer.html), for rendering views outside of controller actions. I don't think this is something most Rails apps will need (certainly not on day 1); users can configure this feature when they need it.

**`cookies_serializer.rb`**. This was added for [Rails 4.1](https://guides.rubyonrails.org/upgrading_ruby_on_rails.html#cookies-serializer). The behaviour is:

- For new apps, the initializer says `:json`.
- For upgraded apps that don't have the initializer, it is added with value `:marshal`.
- If there's no initializer, the [default value](c9a89a4067/actionpack/lib/action_dispatch/middleware/cookies.rb (L589)) is `:marshal`.

Since nobody should be upgrading direct from Rails 4.0 to Rails 7.0, we can simplify this by using new framework defaults. So the behavior will now be:

- For new apps, `config.load_defaults("7.0")` sets the value to `:json`.
- The `new_framework_defaults_7_0.rb` file explains this, and suggests using `:hybrid` to be upgrade to JSON cookies.
- No changes to [the code](c9a89a4067/actionpack/lib/action_dispatch/middleware/cookies.rb (L589)); the default value is `:marshal` if you don't set one.

So if you were not setting a `cookies_serializer` previously and you want to keep using `:marshal`, you'll need to explicitly set this before using `config.load_defaults("7.0")`, otherwise it will switch to `:json`. The upside of this is you won't get the `cookies_serializer.rb` file created for you every time you upgrade.
2021-06-18 16:13:05 -05:00
Rafael França
58ed26f616
Revert "Extract methods assert_queries and assert_no_queries" 2021-06-17 13:35:25 -04:00
Ricardo Díaz
f644f7d35b Extract methods assert_queries and assert_no_queries
Both methods are defined in multiple parts of the framework. It would
be useful to put them in a proper place, so that repetition is
avoided.

I chose the implementation from `ActiveRecord` because it's a bit more
complete with the `SQLCounter` class, and also because other parts
depend on it.
2021-06-14 09:55:13 -05:00
Sean Doyle
68bb2650d5 Action Text: forward form: option to hidden input
Trix's `<trix-editor>` doesn't support the [form][] property like
`<textarea>` or other form fields.

For example, consider the following HTML and event listener:

```html
<form action="/articles" method="post">
  <textarea name="content"></textarea>

  <button type="submit">Save</button>
</form>

<script>
  addEventListener("keydown", ({ key, metaKey, target }) => {
    if (target.form && key == "Enter" && (metaKey || ctrlKey)) {
      form.requestSubmit()
    }
  })
</script>
```

The `target` (an instance of `HTMLTextAreaElement` relies on the
[HTMLTextAreaElement.form][] property for access to its associated
`<form>`. While it's usually equivalent to `target.closest("form")`,
that isn't always the case. Declaring a `[form]` attribute with another
`<form>` element's `[id]` value can associate a field to a `<form>` that
is _not an ancestor_. That means that the event listener from above
would continue to work with this HTML:

```html
<textarea name="content" form="new_article"></textarea>

<!-- elsewhere -->
<form id="new_article" action="/articles" method="post">
  <button type="submit">Save</button>
</form>
```

Unfortunately, if the `<textarea>` element were replaced with a
`<trix-editor>`, the event listener's reliance on accessing the form as
a property would break, since the `<trix-editor>` custom element doesn't
declare that property. There is currently a pull request
([basecamp/trix#899][]) to add support for accessing the `form` as a
property of the `<trix-editor>` element.

The [feedback][] provided on that pull request suggests that we
implement the `form` property by delegating to the `<input
type="hidden">` element. Currently, `<input type="hidden">` elements
constructed by Action Text helpers cannot declare the `[form]`
attribute.

This commit adds support by special-casing the `options[:form]` key
within `ActionText::TagHelper#rich_text_area_tag`.

[form]: https://developer.mozilla.org/en-US/docs/Web/API/HTMLTextAreaElement#properties
[basecamp/trix#899]: https://github.com/basecamp/trix/pull/899#discussion_r618543357
[feedback]: https://github.com/basecamp/trix/pull/899#discussion_r618543357
2021-04-25 20:27:24 -04:00
John Bampton
eef63e05fb chore: fix case of CSS and JavaScript 2021-04-15 21:52:58 +10:00
Jorge Manrubia
28145c3cee Rename master_key => primary_key 2021-04-01 15:02:15 +02:00
Jorge Manrubia
588c972d21 Removes the Action Text dependency from Active Record
Move the Action Text stuff to its own concern in `actiontext`.
2021-04-01 15:02:15 +02:00
Jorge Manrubia
1406ac294f Remove new lines 2021-04-01 15:02:14 +02:00
Jorge Manrubia
638a92f734 Initial extraction from active_record_encryption gem 2021-04-01 15:02:13 +02:00
Henrik Nyh
515108ee03 'lookup' -> 'look up' in dummy webpacker.ymls
Corresponding to this fix: https://github.com/rails/webpacker/pull/2961
2021-03-21 12:36:56 +00:00
James Brooks
b1b0b22f50
Always render attachment partials as HTML with :html format inside trix editor 2021-03-19 13:35:09 -04:00
Mark VanLandingham
bece535c98
Add config.action_text.attachment_tag_name 2021-03-05 16:57:36 -05:00
Christian Schmidt
6cd184ff0f
Use image/jpeg instead of non-standard image/jpg 2021-03-05 13:14:11 -05:00
Abhay Nikam
adc5eb66f8
Action Text: call #to_trix_html on rich_text_area_tag value 2021-02-28 11:20:59 -05:00
Santiago Bartesaghi
e83d7dcb2f Use 4XX instead of 2XX for validation errors responses 2021-01-06 00:10:26 -03:00
Sean Doyle
3500571b43 Improve ActionText extensiblibility
Extensible layout
---

Expose how we render the HTML _surrounding_ rich text content as an
extensible `layouts/action_text/contents/_content.html.erb` template to
encourage user-land customizations, while retaining private API control
over how the rich text itself is rendered by moving the
`#render_action_text_content` helper invocation to the
`action_text/contents/_content.html.erb` partial.

Extensible Attachable `#to_attachable_partial_path`
---

When an application declares a canonical partial for a record, there is
no way to override which partial is used when transformed to Rich Text.
For example, a default `Person < ApplicationRecord` instance returns
`"people/person"` from calls to `#to_partial_path`, resulting in the
`app/views/people/_person.html.erb` partial being rendered.

Prior to this change, when encountering an `<action-text-attachment
sgid="...">` element, ActionText retrieved the corresponding
`Attachable` instance (usually an `ActiveRecord::Base` instance) and
transformed it to rich text HTML by rendering the partial that
corresponds to its `#to_partial_path`.

This proposed change instead invokes
`Attachable#to_attachable_partial_path`. By default,
`#to_attachable_partial_path` is an alias for `#to_partial_path`.

Guides
---

Extend the `guides/action_text_overview` document to
describe how to customize these templates, and to better illustrate how
ActionText::Attachable instances are rendered into HTML.
2020-12-29 20:06:45 -05:00
Jonathan Hefner
ef61c9c8a3
Fix rendering Action Text HTML in new threads
Because `ActionText::Content.renderer` is implemented as a
`thread_cattr_accessor`, any default value set in the main thread will
be inaccessible from other threads.  Therefore, use a `cattr_accessor`
to store the default renderer, and fall back to it when `renderer` has
not been set by e.g. `with_renderer`.

Fixes #40757.
2020-12-07 16:41:44 -05:00
Petrik
0a583c73c1 Change form_with to generate non remote forms by default
`form_with` would generate a remote form by default.
This confused users because they were forced to handle remote requests.

All new 6.1 applications will generate non-remote forms by default.
When upgrading a 6.0 application you can enable remote forms by default by
setting `config.action_view.form_with_generates_remote_forms` to `true`.
2020-12-01 21:14:37 +01:00
Alex Ghiculescu
76e432341c Always recommend config.asset_host in examples 2020-11-30 16:33:51 -06:00
Jonathan Hefner
76e111395c Always render Action Text HTML with :html format
Since #40222, Action Text HTML is rendered in the context of the current
request.  This causes the Action Text template format to default to the
request format, which prevents the template from being resolved when the
request format is not `:html` (e.g. `:json`).  Therefore, override the
template format to always be `:html`.

Fixes #40695.
2020-11-27 10:59:24 -06:00