How I decide to pass on a parameter within a component.

How I decide to pass on a parameter within a component.

Why I chose to explicitly pass the tag parameter in LinkComponent.

ยท

2 min read

When creating a component in Rails, especially when using a component-based architecture like ViewComponent or similar, I was faced with a question, how should I pass around and manage data, especially configuration data. Here i have 2 options.

  1. Pass to BaseComponent
def call
  content = prepare_content
  render(RapidRailsUI::BaseComponent.new(tag: "a", **@options)) { content }
end
  1. Pass to LinkComponent
class LinkComponent < Component
    def initialize(
      ...
      setup_options
    end

    def setup_options
      @options[:tag] = "a"
      ...
    end
end

Here's why I chose option 1, explicitly pass the tag parameter when calling BaseComponent from LinkComponent:

  1. Clarity in Dependencies: By directly passing tag: "a" in the render method, it becomes immediately clear what type of HTML element BaseComponent will render. This approach avoids confusion and errors that might arise from merging options where the tag could be incorrectly overwritten or omitted.

  2. Ensuring Required Attributes: The tag attribute is essential for BaseComponent to function correctly as it determines the HTML element type. Passing it explicitly ensures that the component always receives this necessary information, preventing runtime errors due to missing attributes.

  3. Separation of Concerns: LinkComponent should not be concerned with the internal workings of BaseComponent or how it processes its options. By passing the tag directly, LinkComponent remains focused on its specific logic, enhancing maintainability and keeping the components loosely coupled.

This method of passing parameters enhances code readability, reliability, and maintainability, making it easier to understand.

Happy coding ๐Ÿ’ป

Did you find this article valuable?

Support Ahmed Nadar by becoming a sponsor. Any amount is appreciated!

ย