Skip to content
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 array and hash literal offenders to AttributeDefaultBlockValue #369

Merged
merged 1 commit into from
Oct 14, 2020
Merged

Add array and hash literal offenders to AttributeDefaultBlockValue #369

merged 1 commit into from
Oct 14, 2020

Conversation

cilim
Copy link
Contributor

@cilim cilim commented Oct 12, 2020

The Attributes API also allows defining attributes that are arrays or hashes.

#   # bad
#   class User < ApplicationRecord
#     attribute :roles, :string, array: true, default: []
#   end
#
#   # good
#   class User < ActiveRecord::Base
#     attribute :roles, :string, array: true, default: -> { [] }
#   end
# 
#   bad
#   class User < ApplicationRecord
#     attribute :configuration, default: {}
#   end
#
#   # good
#   class User < ActiveRecord::Base
#     attribute :configuration, default: -> { {} }
#   end

This PR patches up the AttributeDefaultBlockValue cop accordingly.

Reason why array and hash literals should also be passed as a block is the fact that defining them without one creates a class attribute, not instance.

class Simple < ActiveType::Object
  attribute :mutable_attribute, default: {}
end
[1] pry(main)> first = Simple.new
=> #<Simple mutable_attribute: {}>
[2] pry(main)> first.mutable_attribute.merge!(a: 3)
=> {:a=>3}
[3] pry(main)> second = Simple.new
=> #<Simple mutable_attribute: {:a=>3}>
[4] pry(main)> second.mutable_attribute
=> {:a=>3}
[5] pry(main)> Simple.new.mutable_attribute.object_id
=> 70340537951880
[6] pry(main)> Simple.new.mutable_attribute.object_id
=> 70340537951880

which is probably not what you want.

@koic koic merged commit 5c7ff67 into rubocop:master Oct 14, 2020
@koic
Copy link
Member

koic commented Oct 14, 2020

Thank you for improving and explaining!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants