docbrown/app/models/sponsorship.rb
Jeremy Friesen b115b2d17e
Appeasing Rubocop as it sneaks some changes in (#16085)
I was working on another branch and as part of my commit, Rubocop
removed a validation (but not the spec that asserted the validation).

Below is the "non-updating" rubocop offense on the other branch.

```shell
❯ rubocop ./app/models/notification_subscription.rb
Inspecting 1 file
C

Offenses:

app/models/notification_subscription.rb:13:29: C: [Correctable]
Rails/RedundantPresenceValidationOnBelongsTo: Remove explicit presence
validation for notifiable_id.
  validates :notifiable_id, presence: true
                            ^^^^^^^^^^^^^^

1 file inspected, 1 offense detected, 1 offense auto-correctable
```

To remediate, I ran:

```shell
> rubocop --only "Rails/RedundantPresenceValidationOnBelongsTo" \
  --auto-correct
```

This resolved the `app/models`.  Then did some regex magic and removed
the assertions from `spec/models`.

For Forem folks, I wrote a [forem.team post][1] discuss if this is how
we want to proceed.

[1]:https://forem.team/jeremy/rubocop-auto-updating-mayhem-33a6
2022-01-13 07:48:01 -05:00

56 lines
1.8 KiB
Ruby

class Sponsorship < ApplicationRecord
LEVELS = %w[gold silver bronze tag media devrel].freeze
METAL_LEVELS = %w[gold silver bronze].freeze
STATUSES = %w[none pending live].freeze
SPONSORABLE_TYPES = %w[Tag ActsAsTaggableOn::Tag].freeze
# media has no fixed amount of credits
CREDITS = {
gold: 6_000,
silver: 500,
bronze: 100,
tag: 300,
devrel: 500
}.with_indifferent_access.freeze
belongs_to :user
belongs_to :organization, inverse_of: :sponsorships
belongs_to :sponsorable, polymorphic: true, optional: true
validates :level, presence: true, inclusion: { in: LEVELS }
validates :status, presence: true, inclusion: { in: STATUSES }
validates :url, url: { allow_blank: true, no_local: true, schemes: %w[http https] }
validates :featured_number, presence: true
validates :sponsorable_type, inclusion: {
in: SPONSORABLE_TYPES,
allow_blank: true,
message: "is not a sponsorable type"
}
validate :validate_tag_uniqueness, if: proc { level.to_s == "tag" }
validate :validate_level_uniqueness, if: proc { METAL_LEVELS.include?(level) }
LEVELS.each do |level|
scope level, -> { where(level: level) }
end
scope :live, -> { where(status: :live) }
scope :pending, -> { where(status: :pending) }
scope :unexpired, -> { where("expires_at > ?", Time.current) }
private
def validate_tag_uniqueness
return unless self.class.where(sponsorable: sponsorable, level: :tag)
.exists?(["expires_at > ? AND id != ?", Time.current, id.to_i])
errors.add(:level, "The tag is already sponsored")
end
def validate_level_uniqueness
return unless self.class.where(organization: organization)
.exists?(["level IN (?) AND expires_at > ? AND id != ?", METAL_LEVELS, Time.current, id.to_i])
errors.add(:level, "You can have only one sponsorship of #{METAL_LEVELS.join(', ')}")
end
end