Last active
May 10, 2021 12:09
-
-
Save KonnorRogers/c15f286f6e41df0f639f0c408ccab9ee to your computer and use it in GitHub Desktop.
For nested components
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ViewComponentHelper | |
def component(name, context: nil, **args, &block) | |
cache_keys = Array(args.delete(:cache)) | |
cache_if cache_keys.present?, cache_keys do | |
return render_component_in(context, name, **args, &block) if context | |
return render component_class_for(name).new(args), &block | |
end | |
end | |
def render_component_in(context, name, **args, &block) | |
component_class_for(name).new(args).render_in(context, &block) | |
end | |
private | |
def component_class_for(path) | |
file_name = "#{path}/component" | |
namespace = namespace(file_name).camelize | |
return (namespace + "::" + "Component").constantize unless namespace == 'components' | |
component_name.constantize | |
end | |
def namespace(file_name) | |
file_path = component_path(file_name) | |
Pathname.new(File.dirname(file_path)).relative_path_from(Rails.root.join("app/components")).to_s | |
end | |
def component_path(file_name) | |
Dir.glob(File.join(Rails.root, 'app', 'components', '**', file_name + ".rb")).first | |
end | |
end | |
# Example | |
# <%= component "namespace1/namespace2" %> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment