Skip to content

Commit

Permalink
Add oldest_authored_at scope to Version
Browse files Browse the repository at this point in the history
Replicate `Version#authored_at` logic in a SQL case statement and call
SQL `minimum` on that to get the oldest `authored_at`

Add tests for the model using similar structure as tests for `authored_at`
  • Loading branch information
albertchae committed Feb 20, 2024
1 parent 3a0630f commit d286515
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 9 deletions.
10 changes: 1 addition & 9 deletions app/controllers/versions_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ class VersionsController < ApplicationController

def index
set_page
set_oldest_version_date
@oldest_version_date = @rubygem.versions.oldest_authored_at
@versions = @rubygem.versions.by_position.page(@page).per(Gemcutter::VERSIONS_PER_PAGE)
end

Expand All @@ -15,12 +15,4 @@ def show
@on_version_page = true
render "rubygems/show"
end

private

def set_oldest_version_date
oldest_created_at = @rubygem.versions.order(:created_at).first
oldest_built_at = @rubygem.versions.order(:built_at).first
@oldest_version_date = [oldest_created_at, oldest_built_at].compact.map(&:authored_at).min
end
end
13 changes: 13 additions & 0 deletions app/models/version.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,19 @@ class Version < ApplicationRecord # rubocop:disable Metrics/ClassLength
validate :metadata_attribute_length
validate :no_dashes_in_version_number, on: :create

scope :oldest_authored_at, lambda {
minimum(
<<~SQL.squish
CASE WHEN DATE(created_at) = '#{RUBYGEMS_IMPORT_DATE}'
AND built_at <= created_at THEN
built_at
ELSE
created_at
END
SQL
)&.in_time_zone
}

class AuthorType < ActiveModel::Type::String
def cast_value(value)
if value.is_a?(Array)
Expand Down
19 changes: 19 additions & 0 deletions test/models/version_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,25 @@ class VersionTest < ActiveSupport::TestCase
end
end

context ".oldest_authored_at scope" do
setup do
@built_at = Version::RUBYGEMS_IMPORT_DATE - 60.days
@version.update(built_at: @built_at, created_at: Version::RUBYGEMS_IMPORT_DATE)
_newer_version = create(:version, rubygem: @version.rubygem)
end

should "return the built_at of the oldest version when created_at is the same as RUBYGEMS_IMPORT_DATE" do
assert_equal @built_at, Version.oldest_authored_at
end

should "return the created_at of the oldest version when created_at is not the same as RUBYGEMS_IMPORT_DATE" do
created_at = Version::RUBYGEMS_IMPORT_DATE + 1.day
@version.update(created_at: created_at)

assert_equal created_at, Version.oldest_authored_at
end
end

should "have a rubygems version" do
@version.update(required_rubygems_version: @required_rubygems_version)
new_version = Version.find(@version.id)
Expand Down

0 comments on commit d286515

Please sign in to comment.