Skip to content

Instantly share code, notes, and snippets.

@KonnorRogers
Last active May 10, 2021 12:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KonnorRogers/c15f286f6e41df0f639f0c408ccab9ee to your computer and use it in GitHub Desktop.
Save KonnorRogers/c15f286f6e41df0f639f0c408ccab9ee to your computer and use it in GitHub Desktop.
For nested components
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