-
Notifications
You must be signed in to change notification settings - Fork 129
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add InstanceVariable linter #241
Open
emilong
wants to merge
2
commits into
Shopify:main
Choose a base branch
from
binti-family:instance-everywhere
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -98,7 +98,8 @@ linters: | |
| [FinalNewline](#FinalNewline) | Yes | warns about missing newline at the end of a ERB template | | ||
| [NoJavascriptTagHelper](#NoJavascriptTagHelper) | Yes | prevents the usage of Rails' `javascript_tag` | | ||
| ParserErrors | Yes | | | ||
| PartialInstanceVariable | No | detects instance variables in partials | | ||
| [InstanceVariable](#InstanceVariable) | No | detects instance variables | | ||
| PartialInstanceVariable | No | detects instance variables in partials (deprecated in favor of [InstanceVariable](#InstanceVariable))| | ||
| [RequireInputAutocomplete](#RequireInputAutocomplete) | Yes | warns about missing autocomplete attributes in input tags | | ||
| [RightTrim](#RightTrim) | Yes | enforces trimming at the right of an ERB tag | | ||
| [SelfClosingTag](#SelfClosingTag) | Yes | enforces self closing tag styles for void elements | | ||
|
@@ -355,15 +356,15 @@ Linter-Specific Option | Description | |
`correction_style` | When configured with `cdata`, adds CDATA markers. When configured with `plain`, don't add makers. Defaults to `cdata`. | ||
|
||
### RequireScriptNonce | ||
This linter prevents the usage of HTML `<script>`, Rails `javascript_tag`, `javascript_include_tag` and `javascript_pack_tag` without a `nonce` argument. The purpose of such a check is to ensure that when [content securty policy](https://edgeguides.rubyonrails.org/security.html#content-security-policy) is implemented in an application, there is a means of discovering tags that need to be updated with a `nonce` argument to enable script execution at application runtime. | ||
This linter prevents the usage of HTML `<script>`, Rails `javascript_tag`, `javascript_include_tag` and `javascript_pack_tag` without a `nonce` argument. The purpose of such a check is to ensure that when [content securty policy](https://edgeguides.rubyonrails.org/security.html#content-security-policy) is implemented in an application, there is a means of discovering tags that need to be updated with a `nonce` argument to enable script execution at application runtime. | ||
|
||
``` | ||
Bad ❌ | ||
<script> | ||
<script> | ||
alert(1) | ||
</script> | ||
Good ✅ | ||
<script nonce="<%= request.content_security_policy_nonce %>" > | ||
<script nonce="<%= request.content_security_policy_nonce %>" > | ||
alert(1) | ||
</script> | ||
``` | ||
|
@@ -486,6 +487,75 @@ Linter-Specific Option | Description | |
`allow_blank` | True or false, depending on whether or not the `type` attribute may be omitted entirely from a `<script>` tag. Defaults to `true`. | ||
`disallow_inline_scripts` | Do not allow inline `<script>` tags anywhere in ERB templates. Defaults to `false`. | ||
|
||
### InstanceVariables | ||
|
||
This linter prevents instance variables from being referenced in templates. | ||
|
||
```erb | ||
Bad ❌ | ||
<%= @instance_variable %> | ||
|
||
Good ✅ | ||
<%= local_variable %> | ||
``` | ||
|
||
Instance variables in templates, if not declared (for example because of | ||
changes or even misspellings), will evaluate to `nil`. Using locals offers better | ||
protection against inadvertently referencing an undefined instance variable. | ||
|
||
Locals also offer more explicit specification of the dependencies of a template, | ||
which you may prefer for your project. | ||
|
||
While locals may be used in any template (see below), they have often been | ||
limited to use in partials. To restrict this linter to checking partials, | ||
specify the option `partials_only` to `true`. This configuration can replace the | ||
usage of the deprecated `PartialInstanceVariable` linter. | ||
|
||
To use locals in non-partials in Rails controller actions, you can use an | ||
explicit `render` method call, e.g. | ||
|
||
```ruby | ||
class MyController < ApplicationController | ||
def my_action | ||
render locals: { local1: 5, local2: "local 2" } | ||
end | ||
end | ||
``` | ||
|
||
To use locals in non-partials in Rails mailers, you can use an explicit `render` | ||
method call in a `format` block, e.g. | ||
|
||
```ruby | ||
class MyMailer < ApplicationMailer | ||
def send_my_mail | ||
mail(to: "[email protected]", subject: "Partials in mailer") do |format| | ||
format.html do | ||
render locals: { local1: 5, local2: "local 2" } | ||
end | ||
end | ||
end | ||
end | ||
``` | ||
|
||
Locals need not be required in templates either. Either of the following techniques | ||
will allow use of optional locals, including setting defaults within the template: | ||
|
||
```erb | ||
<% | ||
optional_variable ||= nil | ||
optional_variable_with_default ||= "some default" | ||
%> | ||
|
||
<% if defined?(other_optional_variable) %> | ||
<span><%= other_optional_variable %></span> | ||
<% end %> | ||
%> | ||
``` | ||
|
||
Linter-Specific Option | Description | ||
--------------------------|--------------------------------------------------------- | ||
`partials_only` | Boolean to limit linting to partial templates only. | ||
|
||
## Custom Linters | ||
|
||
`erb-lint` allows you to create custom linters specific to your project. It will load linters from the `.erb-linters` directory in the root of your | ||
|
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
# frozen_string_literal: true | ||
|
||
module ERBLint | ||
module Linters | ||
# Checks for instance variables in partials. | ||
class InstanceVariable < Linter | ||
include LinterRegistry | ||
|
||
class ConfigSchema < LinterConfig | ||
property :partials_only, accepts: [true, false], default: false, reader: :partials_only? | ||
end | ||
self.config_schema = ConfigSchema | ||
|
||
INSTANCE_VARIABLE_REGEX = /[^@]?(@?@[a-z_][a-zA-Z_0-9]*)/.freeze | ||
PARTIAL_FILE_REGEX = %r{(\A|.*/)_[^/\s]*\.html\.erb\z}.freeze | ||
|
||
def run(processed_source) | ||
return unless process_file?(processed_source) | ||
|
||
matches = processed_source | ||
.file_content | ||
.to_enum(:scan, INSTANCE_VARIABLE_REGEX) | ||
.map { Regexp.last_match } | ||
return if matches.empty? | ||
|
||
matches.each do |match| | ||
range = match.begin(1)...match.end(1) | ||
add_offense(processed_source.to_source_range(range), offense_message) | ||
end | ||
end | ||
|
||
private | ||
|
||
def process_file?(processed_source) | ||
return true unless @config.partials_only? | ||
|
||
processed_source.filename.match?(PARTIAL_FILE_REGEX) | ||
end | ||
|
||
def offense_message | ||
"Instance variable detected." | ||
end | ||
end | ||
end | ||
end |
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
# frozen_string_literal: true | ||
|
||
require "spec_helper" | ||
|
||
describe ERBLint::Linters::InstanceVariable do | ||
let(:linter_config) { described_class.config_schema.new } | ||
let(:file_loader) { ERBLint::FileLoader.new(".") } | ||
let(:linter) { described_class.new(file_loader, linter_config) } | ||
let(:processed_source_one) { ERBLint::ProcessedSource.new("_file.html.erb", file) } | ||
let(:processed_source_two) { ERBLint::ProcessedSource.new("app/views/_a_model/a_view.html.erb", file) } | ||
let(:offenses) { linter.offenses } | ||
before do | ||
linter_config[:partials_only] = partials_only | ||
linter.run(processed_source_one) | ||
linter.run(processed_source_two) | ||
end | ||
|
||
describe "offenses" do | ||
subject { offenses } | ||
|
||
context "with partials_only=true" do | ||
let(:partials_only) { true } | ||
|
||
context "when an instance variable is not present" do | ||
let(:file) { "<%= user.first_name %>" } | ||
it { expect(subject).to(eq([])) } | ||
end | ||
|
||
context "when an instance variable is present" do | ||
let(:file) { "<h2><%= @user.first_name %></h2>" } | ||
it do | ||
expect(subject).to(eq([ | ||
build_offense(processed_source_one, 8...13, "Instance variable detected."), | ||
])) | ||
end | ||
end | ||
|
||
context "when a class instance variable is present" do | ||
let(:file) { "<h2><%= @@user.first_name %></h2>" } | ||
it do | ||
expect(subject).to(eq([ | ||
build_offense(processed_source_one, 8...14, "Instance variable detected."), | ||
])) | ||
end | ||
end | ||
|
||
context "when multiple instance variables are present" do | ||
let(:file) { "<h2><%= @user.first_name %> <%= @user.last_name %></h2>" } | ||
it do | ||
expect(subject).to(eq([ | ||
build_offense(processed_source_one, 8...13, "Instance variable detected."), | ||
build_offense(processed_source_one, 32...37, "Instance variable detected."), | ||
])) | ||
end | ||
end | ||
end | ||
|
||
context "with partials_only=true" do | ||
let(:partials_only) { false } | ||
|
||
context "when an instance variable is not present" do | ||
let(:file) { "<%= user.first_name %>" } | ||
it { expect(subject).to(eq([])) } | ||
end | ||
|
||
context "when an instance variable is present" do | ||
let(:file) { "<h2><%= @user.first_name %></h2>" } | ||
it do | ||
expect(subject).to(eq([ | ||
build_offense(processed_source_one, 8...13, "Instance variable detected."), | ||
build_offense(processed_source_two, 8...13, "Instance variable detected."), | ||
])) | ||
end | ||
end | ||
|
||
context "when a class instance variable is present" do | ||
let(:file) { "<h2><%= @@user.first_name %></h2>" } | ||
it do | ||
expect(subject).to(eq([ | ||
build_offense(processed_source_one, 8...14, "Instance variable detected."), | ||
build_offense(processed_source_two, 8...14, "Instance variable detected."), | ||
])) | ||
end | ||
end | ||
|
||
context "when multiple instance variables are present" do | ||
let(:file) { "<h2><%= @user.first_name %> <%= @user.last_name %></h2>" } | ||
it do | ||
expect(subject).to(eq([ | ||
build_offense(processed_source_one, 8...13, "Instance variable detected."), | ||
build_offense(processed_source_one, 32...37, "Instance variable detected."), | ||
build_offense(processed_source_two, 8...13, "Instance variable detected."), | ||
build_offense(processed_source_two, 32...37, "Instance variable detected."), | ||
])) | ||
end | ||
end | ||
end | ||
end | ||
|
||
private | ||
|
||
def build_offense(processed_source, range, message) | ||
ERBLint::Offense.new( | ||
linter, | ||
processed_source.to_source_range(range), | ||
message | ||
) | ||
end | ||
end |
This file contains 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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Instance variables in templates is the Rails default and those linters should follow Rails defaults.