From 8e027ee6e2d8bf47233be165bd02ee1d48b3575e Mon Sep 17 00:00:00 2001 From: Joel Hawksley Date: Fri, 14 Jan 2022 14:23:27 -0700 Subject: [PATCH] add some examples of good/bad code to ViewComponents in Practice (#1217) * add some example of good/bad code to ViewComponents in Practice * add changelog * mdlint --- docs/CHANGELOG.md | 4 +++ docs/viewcomponents-in-practice.md | 46 ++++++++++++++++++++++++++++-- 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 2dffa7386..622802409 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -7,6 +7,10 @@ title: Changelog ## main +* Add good and bad examples to `ViewComponents in practice`. + + *Joel Hawksley* + ## 2.48.0 * Correct path in example test command in Contributing docs. diff --git a/docs/viewcomponents-in-practice.md b/docs/viewcomponents-in-practice.md index e30c545c0..8222923a3 100644 --- a/docs/viewcomponents-in-practice.md +++ b/docs/viewcomponents-in-practice.md @@ -127,13 +127,55 @@ Use ViewComponents in place of helpers that return HTML. The more a ViewComponent is dependent on global state (such as request parameters or the current URL), the less likely it's to be reusable. Avoid implicit coupling to global state, instead passing it into the component explicitly. Thorough unit testing is a good way to ensure decoupling from global state. +```ruby +# good +class MyComponent < ViewComponent::Base + def initialize(name:) + @name = name + end +end + +# bad +class MyComponent < ViewComponent::Base + def initialize + @name = params[:name] + end +end +``` + ### Avoid inline Ruby in ViewComponent templates -Avoid writing inline Ruby in ViewComponent templates. Try using an instance method on the ViewComponent instead. +Avoid writing inline Ruby in ViewComponent templates. Try using an instance method on the ViewComponent instead: + +```ruby +# good +class MyComponent < ViewComponent::Base + def message + "Hello, #{@name}!" + end +end +``` + +``` erb +<%# bad %> +<% message = "Hello, #{@name}" %> +``` ### Pass an object instead of 3+ object attributes -ViewComponents should be passed individual object attributes unless three or more attributes are needed from the object, in which case the entire object should be passed. +ViewComponents should be passed individual object attributes unless three or more attributes are needed from the object, in which case the entire object should be passed: + +```ruby +# good +class MyComponent < ViewComponent::Base + def initialize(repository:); end +end + +# bad +class MyComponent < ViewComponent::Base + def initialize(repository_name:, repository_owner:, repository_created_at:); end +end +``` ### Avoid database queries