Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lazy load autoloaded bucket components #678

Merged
merged 5 commits into from Mar 16, 2024

Conversation

joeldrapper
Copy link
Collaborator

@joeldrapper joeldrapper commented Mar 14, 2024

Autoloaded Ruby constants will not have corresponding proxy methods on Buckets, since these methods are defined on const_added. This PR solves that in two ways:

External access

Assuming a runtime environment where none of the constants are loaded by default — such as Rails with Zeitwerk during development — we use a bucket like this:

def view_template
  Components::Heading { "Hello" }
end

This call will autoload the Components module, but it will not autoload the Components::Heading module, since it’s just a method call on Components. How we handle this is the Components bucket catches the call with method_missing, and then tries to load the constant. If loading the constant is successful, it can call the newly defined Heading method on Components.

When included

If we include Components and then try to call Heading, again we will run into the same problem.

class MyComponent < Phlex::HTML
  include Components

  def view_template
    Heading { "Hello" }
  end
end

In this case, though, we can’t use method_missing. If you include Components and AnotherBucket and they both define a Heading component, you would expect AnotherBucket’s Heading component to take precedence over ComponentsHeading component. If both buckets were using the method_missing technique, this precedence would be based on which bucket had their component autoloaded first.

So instead, when you include a bucket, we eager-load all that bucket’s components.

lib/phlex/bucket.rb Outdated Show resolved Hide resolved
lib/phlex/bucket.rb Outdated Show resolved Hide resolved
lib/phlex/bucket.rb Outdated Show resolved Hide resolved
@joeldrapper joeldrapper marked this pull request as ready for review March 16, 2024 11:36
@joeldrapper joeldrapper merged commit b1049cb into main Mar 16, 2024
15 of 17 checks passed
@joeldrapper joeldrapper deleted the lazy-load-autoloaded-bucket-components branch March 16, 2024 11:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant