Skip to content

Commit

Permalink
add some examples of good/bad code to ViewComponents in Practice (#1217)
Browse files Browse the repository at this point in the history
* add some example of good/bad code to ViewComponents in Practice

* add changelog

* mdlint
  • Loading branch information
joelhawksley authored Jan 14, 2022
1 parent e702e60 commit 8e027ee
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
4 changes: 4 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
46 changes: 44 additions & 2 deletions docs/viewcomponents-in-practice.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 8e027ee

Please sign in to comment.