Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

at_timestamp: refactoring with rubocop

Sebastian Fiedlschuster3d390a8d7676
diff --git a/app/models/journable/historic_active_record_relation.rb b/app/models/journable/historic_active_record_relation.rb
index e47d58ad7a0..8c43c24a6ac 100644
--- a/app/models/journable/historic_active_record_relation.rb
+++ b/app/models/journable/historic_active_record_relation.rb
@@ -26,6 +26,13 @@
# See COPYRIGHT and LICENSE files for more details.
#++
+# rubocop:disable Style/ClassCheck
+# Prefer `kind_of?` over `is_a?` because it reads well before vowel and consonant sounds.
+# E.g.: `relation.kind_of? ActiveRecord::Relation`
+
+# rubocop:disable Metrics/AbcSize
+# rubocop:disable Metrics/PerceivedComplexity
+
class Journable::HistoricActiveRecordRelation < ActiveRecord::Relation
# See: https://github.com/opf/openproject/pull/11243
@@ -35,15 +42,15 @@ class Journable::HistoricActiveRecordRelation < ActiveRecord::Relation
def initialize(relation, timestamp:)
raise ArgumentError, "Expected ActiveRecord::Relation" unless relation.kind_of? ActiveRecord::Relation
+
+ super(relation.klass)
relation.instance_variables.each do |key|
- self.instance_variable_set key, relation.instance_variable_get(key)
+ instance_variable_set key, relation.instance_variable_get(key)
end
self.timestamp = timestamp
- self.readonly!
- self.instance_variable_set :@table, model.journal_class.arel_table
-
- return self
+ readonly!
+ instance_variable_set :@table, model.journal_class.arel_table
end
# We need to patch the `pluck` method of an active-record relation that
@@ -59,86 +66,150 @@ class Journable::HistoricActiveRecordRelation < ActiveRecord::Relation
super
end
+ alias_method :original_build_arel, :build_arel
+
# Patch the arel object, which is used to construct the sql query, in order
# to modify the query to search for historic data.
#
- alias_method :original_build_arel, :build_arel
- def call_original_build_arel
- original_build_arel
- end
def build_arel(aliases = nil)
relation = self
- # Switch the database table from `work_packages` to `work_package_journals`.
+ relation = switch_to_journals_database_table(relation)
+ relation = substitute_database_table_in_where_clause(relation)
+ relation = add_timestamp_condition(relation)
+ relation = add_join_on_journables_table_with_created_at_column(relation)
+ relation = select_columns_from_the_appropriate_tables(relation)
+
+ # Based on the previous modifications, build the algebra object.
+ @arel = relation.call_original_build_arel(aliases)
+ @arel = modify_order_clauses(@arel)
+ @arel = move_journals_join_up(@arel)
+ @arel = modify_joins(@arel)
+
+ @arel
+ end
+
+ def call_original_build_arel(aliases = nil)
+ original_build_arel(aliases)
+ end
+
+ private
+
+ # Switch the database table, e.g. from `work_packages` to `work_package_journals`.
+ #
+ def switch_to_journals_database_table(relation)
relation.instance_variable_set :@table, model.journal_class.arel_table
+ relation
+ end
- # Modify there where clauses such that the work-packages table is substituted
- # with the work-package-journals table.
+ # Modify there where clauses such that e.g. the work-packages table is substituted
+ # with the work-package-journals table.
+ #
+ # When the where clause contains the `id` column, use `journals.journable_id` instead.
+ #
+ def substitute_database_table_in_where_clause(relation)
relation.where_clause.instance_variable_get(:@predicates).each do |predicate|
if predicate.kind_of? String
predicate.gsub! "#{model.table_name}.", "#{model.journal_class.table_name}."
- elsif predicate.left.relation == self.arel_table
+ elsif predicate.left.relation == arel_table
if predicate.right.respond_to? :name and predicate.right.name == "id"
predicate.right.instance_variable_set(:@name, "journable_id")
predicate.left.relation = Journal.arel_table
else
- predicate.left.relation = self.journal_class.arel_table
+ predicate.left.relation = journal_class.arel_table
end
end
end
+ relation
+ end
- # Add a timestamp condition: Select the work package journals that are the
- # current ones at the given timestamp.
- relation = relation \
- .joins("INNER JOIN \"journals\" ON \"journals\".\"data_type\" = '#{model.journal_class.name}' AND \"journals\".\"data_id\" = \"#{model.journal_class.table_name}\".\"id\"") \
+ # Add a timestamp condition: Select the work package journals that are the
+ # current ones at the given timestamp.
+ #
+ def add_timestamp_condition(relation)
+ relation \
+ .joins("INNER JOIN \"journals\" ON \"journals\".\"data_type\" = '#{model.journal_class.name}'
+ AND \"journals\".\"data_id\" = \"#{model.journal_class.table_name}\".\"id\"") \
.merge(Journal.at_timestamp(timestamp))
+ end
- # Join the journables table itself because we need to take the 'created_at' attribute from that.
- relation = relation \
- .joins("INNER JOIN (SELECT id, created_at FROM \"#{model.table_name}\") AS journables ON \"journables\".\"id\" = \"journals\".\"journable_id\"")
+ # Join the journables table itself because we need to take the `created_at` attribute from that.
+ # The `created_at` column is not present in the `work_package_journals` table.
+ #
+ def add_join_on_journables_table_with_created_at_column(relation)
+ relation \
+ .joins("INNER JOIN (SELECT id, created_at FROM \"#{model.table_name}\") AS journables
+ ON \"journables\".\"id\" = \"journals\".\"journable_id\"")
+ end
- # At this point, the id is wrong. The sql statement returns the id of the work package journal,
- # but active record instantiates this into the WorkPackage model. Because the resulting model
- # will be a WorkPackage, we need a work-package id, which we take from the journals table.
+ # Gather the columns we need in our model from the different tables in the sql query:
+ #
+ # - the `work_packages` table (journables)
+ # - the `work_package_journals` table (data)
+ # - the `journals` table
+ #
+ # Also, add the `timestamp` as column so that we have it as attribute in our model.
+ #
+ def select_columns_from_the_appropriate_tables(relation)
if relation.select_values.count == 0
- relation = relation.select("'#{timestamp}' as timestamp, #{model.journal_class.table_name}.*, journals.journable_id as id, journables.created_at as created_at, journals.created_at as updated_at")
- elsif relation.select_values.count == 1
+ relation = relation.select("'#{timestamp}' as timestamp,
+ #{model.journal_class.table_name}.*,
+ journals.journable_id as id,
+ journables.created_at as created_at,
+ journals.created_at as updated_at")
+ elsif relation.select_values.count == 1 and
+ relation.select_values.first.respond_to? :relation and
+ relation.select_values.first.relation.name == model.journal_class.table_name and
+ relation.select_values.first.name == "id"
# For sub queries, we need to use the journals.journable_id as well.
# See https://github.com/fiedl/openproject/issues/3.
- if relation.select_values.first.respond_to? :relation and relation.select_values.first.relation.name == model.journal_class.table_name and relation.select_values.first.name == "id"
- relation.instance_variable_get(:@values)[:select] = []
- relation = relation.select("journals.journable_id as id")
- end
+ relation.instance_variable_get(:@values)[:select] = []
+ relation = relation.select("journals.journable_id as id")
end
+ relation
+ end
- # Based on the previous modifications, build the algebra object.
- @arel = relation.call_original_build_arel
-
- # Modify order clauses to use the work-pacakge-journals table.
- @arel.instance_variable_get(:@ast).instance_variable_get(:@orders).each do |order_clause|
+ # Modify order clauses to use the work-pacakge-journals table.
+ #
+ def modify_order_clauses(arel)
+ arel.instance_variable_get(:@ast).instance_variable_get(:@orders).each do |order_clause|
if order_clause.kind_of? Arel::Nodes::SqlLiteral
order_clause.gsub! "#{model.table_name}.", "#{model.journal_class.table_name}."
elsif order_clause.expr.relation == model.arel_table
order_clause.expr.relation = model.journal_class.arel_table
end
end
+ arel
+ end
- # Move the journals join to the beginning because other joins depend on it.
- @arel.instance_variable_get(:@ast).instance_variable_get(:@cores).each do |core|
+ # Move the journals join to the beginning because other joins depend on it.
+ #
+ def move_journals_join_up(arel)
+ arel.instance_variable_get(:@ast).instance_variable_get(:@cores).each do |core|
array_of_joins = core.instance_variable_get(:@source).right
- if journals_join_index = array_of_joins.find_index { |join| join.kind_of?(Arel::Nodes::StringJoin) && join.left.include?("INNER JOIN \"journals\" ON \"journals\".\"data_type\"") }
+ journals_join_index = array_of_joins.find_index do |join|
+ join.kind_of?(Arel::Nodes::StringJoin) and
+ join.left.include?("INNER JOIN \"journals\" ON \"journals\".\"data_type\"")
+ end
+ if journals_join_index
journals_join = array_of_joins[journals_join_index]
array_of_joins.delete_at(journals_join_index)
array_of_joins.insert(0, journals_join)
end
end
+ arel
+ end
- # Modify the joins to point to the journable_id.
- @arel.instance_variable_get(:@ast).instance_variable_get(:@cores).each do |core|
+ # Modify the joins to point to the journable_id.
+ #
+ def modify_joins(arel)
+ arel.instance_variable_get(:@ast).instance_variable_get(:@cores).each do |core|
core.instance_variable_get(:@source).right.each do |node|
if node.kind_of?(Arel::Nodes::Join) and node.right.kind_of?(Arel::Nodes::On)
[node.right.expr.left, node.right.expr.right].each do |attribute|
- if attribute.respond_to? :relation and (attribute.relation == journal_class.arel_table) and (attribute.name == "id")
+ if attribute.respond_to? :relation and
+ (attribute.relation == journal_class.arel_table) and
+ (attribute.name == "id")
attribute.relation = Journal.arel_table
attribute.name = "journable_id"
end
@@ -146,10 +217,10 @@ class Journable::HistoricActiveRecordRelation < ActiveRecord::Relation
end
end
end
-
- return @arel
+ arel
end
+end
- # TODO: Add tests when having several work packages
-
-end
\ No newline at end of file
+# rubocop:enable Style/ClassCheck
+# rubocop:enable Metrics/AbcSize
+# rubocop:enable Metrics/PerceivedComplexity
diff --git a/app/models/journable/timestamps.rb b/app/models/journable/timestamps.rb
index 5846ebb699f..2ed3e7f0b6c 100644
--- a/app/models/journable/timestamps.rb
+++ b/app/models/journable/timestamps.rb
@@ -32,7 +32,6 @@ module Journable::Timestamps
extend ActiveSupport::Concern
class_methods do
-
# Allows to query historic data of journables.
#
# For example, to check which work packages were assigned to a
@@ -41,11 +40,8 @@ module Journable::Timestamps
# WorkPackage.where(assigned_to_id: 123).at_timestamp(1.year.ago)
#
def at_timestamp(timestamp)
- relation = self.all
- relation = Journable::HistoricActiveRecordRelation.new(relation, timestamp:)
- return relation
+ Journable::HistoricActiveRecordRelation.new(all, timestamp:)
end
-
end
# Instantiates a journable with historic data from the given timestap.
@@ -53,23 +49,26 @@ module Journable::Timestamps
# WorkPackage.find(1).at_timestamp(1.year.ago)
#
def at_timestamp(timestamp)
- if journal = self.journals.at_timestamp(timestamp).first
- attributes = journal.data.attributes.merge({
- "id" => self.id,
- "created_at" => self.created_at,
- "updated_at" => journal.updated_at,
- "timestamp" => timestamp,
- "position" => (self.position if self.respond_to? :position)
- })
+ if journal = journals.at_timestamp(timestamp).first
+ attributes = journal.data.attributes.merge(
+ {
+ "id" => id,
+ "created_at" => created_at,
+ "updated_at" => journal.updated_at,
+ "timestamp" => timestamp,
+ "position" => (position if respond_to? :position)
+ }
+ )
journable = self.class.instantiate(attributes)
journable.readonly!
- return journable
+ journable
end
end
def historic?
attributes["timestamp"].present?
end
+
def historical?
historic?
end
@@ -80,7 +79,7 @@ module Journable::Timestamps
#
def rollback!
raise ActiveRecord::RecordNotSaved, "This is no historic data. You can only revert to historic data." unless historic?
- self.class.find(id).update! self.attributes.except("id", "timestamp")
- end
-end
\ No newline at end of file
+ self.class.find(id).update! attributes.except("id", "timestamp")
+ end
+end
diff --git a/app/models/journal/timestamps.rb b/app/models/journal/timestamps.rb
index 46cd0ac67a3..8defbc2d004 100644
--- a/app/models/journal/timestamps.rb
+++ b/app/models/journal/timestamps.rb
@@ -26,13 +26,16 @@
# See COPYRIGHT and LICENSE files for more details.
#++
+# rubocop:disable Style/ClassCheck
+# Prefer `kind_of?` over `is_a?` because it reads well before vowel and consonant sounds.
+# E.g.: `relation.kind_of? ActiveRecord::Relation`
+
module Journal::Timestamps
# See: https://github.com/opf/openproject/pull/11243
extend ActiveSupport::Concern
class_methods do
-
# Select all journals that are the most current at the given timestamp
# for their respective journables.
#
@@ -50,15 +53,17 @@ module Journal::Timestamps
# a journable at a given timestamp.
#
def at_timestamp(timestamp)
- raise ArgumentError, "Expected timestamp to be an ActiveSupport::TimeWithZone or DateTime" unless timestamp.kind_of? ActiveSupport::TimeWithZone or timestamp.kind_of? DateTime
+ unless timestamp.kind_of? ActiveSupport::TimeWithZone or timestamp.kind_of? DateTime
+ raise ArgumentError, "Expected timestamp to be an ActiveSupport::TimeWithZone or DateTime"
+ end
+
timestamp = timestamp.in_time_zone if timestamp.kind_of? DateTime
- where(id:
- where(created_at: (..timestamp)) \
- .select("distinct on (journable_type, journable_id) id") \
- .reorder(:journable_type, :journable_id, created_at: :desc)
- )
+ where(id: where(created_at: (..timestamp)) \
+ .select("distinct on (journable_type, journable_id) id") \
+ .reorder(:journable_type, :journable_id, created_at: :desc))
end
-
end
end
+
+# rubocop:enable Style/ClassCheck
diff --git a/spec/models/journable/timestamps_spec.rb b/spec/models/journable/timestamps_spec.rb
index b6790ffda8c..ab578be9d0e 100644
--- a/spec/models/journable/timestamps_spec.rb
+++ b/spec/models/journable/timestamps_spec.rb
@@ -26,23 +26,25 @@
# See COPYRIGHT and LICENSE files for more details.
#++
+# rubocop:disable RSpec/ClassCheck
+# Prefer `kind_of?` over `is_a?` because it reads well before vowel and consonant sounds.
+# E.g.: `relation.kind_of? ActiveRecord::Relation`
+
require 'spec_helper'
-describe Journable::Timestamps, type: :model do
+describe Journable::Timestamps do
# See: https://github.com/opf/openproject/pull/11243
- before do
- @before_monday = "2022-01-01".to_datetime
- @monday = "2022-08-01".to_datetime
- @tuesday = "2022-08-02".to_datetime
- @wednesday = "2022-08-03".to_datetime
- @thursday = "2022-08-04".to_datetime
- @friday = "2022-08-05".to_datetime
- end
+ let(:before_monday) { "2022-01-01".to_datetime }
+ let(:monday) { "2022-08-01".to_datetime }
+ let(:tuesday) { "2022-08-02".to_datetime }
+ let(:wednesday) { "2022-08-03".to_datetime }
+ let(:thursday) { "2022-08-04".to_datetime }
+ let(:friday) { "2022-08-05".to_datetime }
let!(:work_package) do
- new_work_package = create :work_package, description: "The work package as it is since Friday", estimated_hours: 10
- new_work_package.update_columns created_at: @monday
+ new_work_package = create(:work_package, description: "The work package as it is since Friday", estimated_hours: 10)
+ new_work_package.update_columns created_at: monday
new_work_package
end
let(:journable) { work_package }
@@ -50,28 +52,39 @@ describe Journable::Timestamps, type: :model do
describe "when there are journals for Monday, Wednesday, and Friday" do
def create_journal(journable:, timestamp:, attributes: {})
work_package_attributes = work_package.attributes.except("id")
- journal_attributes = work_package_attributes.extract!(*Journal::WorkPackageJournal.attribute_names).symbolize_keys.merge(attributes)
- create :work_package_journal, journable:, created_at: timestamp, updated_at: timestamp,
- data: build(:journal_work_package_journal, journal_attributes)
+ journal_attributes = work_package_attributes \
+ .extract!(*Journal::WorkPackageJournal.attribute_names) \
+ .symbolize_keys.merge(attributes)
+ create(:work_package_journal,
+ journable:, created_at: timestamp, updated_at: timestamp,
+ data: build(:journal_work_package_journal, journal_attributes))
+ end
+
+ let(:monday_journal) do
+ create_journal(journable: work_package, timestamp: monday,
+ attributes: { description: "The work package as it has been on Monday", estimated_hours: 5 })
+ end
+ let(:wednesday_journal) do
+ create_journal(journable: work_package, timestamp: wednesday,
+ attributes: { description: "The work package as it has been on Wednesday", estimated_hours: 10 })
+ end
+ let(:friday_journal) do
+ create_journal(journable: work_package, timestamp: friday,
+ attributes: { description: "The work package as it is since Friday", estimated_hours: 10 })
end
before do
- @before_monday = "2022-01-01".to_datetime
- @monday = "2022-08-01".to_datetime
- @tuesday = "2022-08-02".to_datetime
- @wednesday = "2022-08-03".to_datetime
- @thursday = "2022-08-04".to_datetime
- @friday = "2022-08-05".to_datetime
work_package.journals.destroy_all
- @monday_journal = create_journal(journable: work_package, timestamp: @monday, attributes: {description: "The work package as it has been on Monday", estimated_hours: 5})
- @wednesday_journal = create_journal(journable: work_package, timestamp: @wednesday, attributes: {description: "The work package as it has been on Wednesday", estimated_hours: 10})
- @friday_journal = create_journal(journable: work_package, timestamp: @friday, attributes: {description: "The work package as it is since Friday", estimated_hours: 10})
+ monday_journal
+ wednesday_journal
+ friday_journal
work_package.reload
end
describe ".at_timestamp" do
- before { @timestamp = @monday }
- subject { WorkPackage.at_timestamp(@timestamp) }
+ let(:timestamp) { monday }
+
+ subject { WorkPackage.at_timestamp(timestamp) }
it "returns a historic active-record relation" do
expect(subject).to be_kind_of Journable::HistoricActiveRecordRelation
@@ -79,7 +92,8 @@ describe Journable::Timestamps, type: :model do
end
describe "chaining a where clause" do
- subject { WorkPackage.at_timestamp(@timestamp).where(assigned_to_id: 1) }
+ subject { WorkPackage.at_timestamp(timestamp).where(assigned_to_id: 1) }
+
it "still returns a historic active-record relation" do
expect(subject).to be_kind_of Journable::HistoricActiveRecordRelation
expect(subject).to be_kind_of ActiveRecord::Relation
@@ -87,7 +101,7 @@ describe Journable::Timestamps, type: :model do
end
it "returns readonly objects" do
- expect(subject.first.readonly?).to eq true
+ expect(subject.first.readonly?).to be true
end
it "returns the records with the journable id rather than the id of the journal record" do
@@ -96,41 +110,52 @@ describe Journable::Timestamps, type: :model do
end
describe ".at_timestamp(something before Monday)" do
- before { @timestamp = @before_monday }
+ let(:timestamp) { before_monday }
+
it "returns [] because before Monday, no journal exists" do
expect(subject).to eq []
end
end
+
describe ".at_timestamp(Monday)" do
- before { @timestamp = @monday }
+ let(:timestamp) { monday }
+
it "returns the work packages in their state of Monday" do
expect(subject.pluck(:description)).to eq ["The work package as it has been on Monday"]
expect(subject.pluck(:id)).to eq [work_package.id]
end
end
+
describe ".at_timestamp(Tuesday)" do
- before { @timestamp = @tuesday }
+ let(:timestamp) { tuesday }
+
it "returns the work packages in their state of Monday because this is the most current on Tuesday" do
expect(subject.pluck(:description)).to eq ["The work package as it has been on Monday"]
expect(subject.pluck(:id)).to eq [work_package.id]
end
end
+
describe ".at_timestamp(Wednesday)" do
- before { @timestamp = @wednesday }
+ let(:timestamp) { wednesday }
+
it "returns the work packages in their state of Wednesday" do
expect(subject.pluck(:description)).to eq ["The work package as it has been on Wednesday"]
expect(subject.pluck(:id)).to eq [work_package.id]
end
end
+
describe ".at_timestamp(Thursday)" do
- before { @timestamp = @thursday }
+ let(:timestamp) { thursday }
+
it "returns the work packages in their state of Wednesday because this is the most current on Thursday" do
expect(subject.pluck(:description)).to eq ["The work package as it has been on Wednesday"]
expect(subject.pluck(:id)).to eq [work_package.id]
end
end
+
describe ".at_timestamp(Friday)" do
- before { @timestamp = @friday }
+ let(:timestamp) { friday }
+
it "returns the work packages in their state of Friday" do
expect(subject.pluck(:description)).to eq ["The work package as it is since Friday"]
expect(subject.pluck(:id)).to eq [work_package.id]
@@ -138,22 +163,28 @@ describe Journable::Timestamps, type: :model do
end
describe "when filtering on a column that only matches in the past" do
- before { @relation = WorkPackage.where(description: "The work package as it has been on Monday") }
+ let(:relation) { WorkPackage.where(description: "The work package as it has been on Monday") }
+
describe "when querying the timestamp where the column matches" do
- subject { @relation.at_timestamp(@monday) }
+ subject { relation.at_timestamp(monday) }
+
it "returns the matching records in their historic states" do
expect(subject.pluck(:description)).to eq ["The work package as it has been on Monday"]
expect(subject.pluck(:id)).to eq [work_package.id]
end
end
+
describe "when querying the timestamp where the column does not match" do
- subject { @relation.at_timestamp(@wednesday) }
+ subject { relation.at_timestamp(wednesday) }
+
it "returns [] because nothing matches" do
expect(subject).to eq []
end
end
+
describe "when querying without at_timestamp" do
- subject { @relation }
+ subject { relation }
+
it "returns [] because nothing matches" do
expect(subject).to eq []
end
@@ -161,43 +192,53 @@ describe Journable::Timestamps, type: :model do
end
describe "when filtering on a column that only matches in the present" do
- before { @relation = WorkPackage.where(description: "The work package as it is since Friday") }
+ let(:relation) { WorkPackage.where(description: "The work package as it is since Friday") }
+
describe "when querying the timestamp where the column matches" do
- subject { @relation.at_timestamp(@friday) }
+ subject { relation.at_timestamp(friday) }
+
it "returns the matching records in their historic states" do
expect(subject.pluck(:description)).to eq ["The work package as it is since Friday"]
expect(subject.pluck(:id)).to eq [work_package.id]
- expect(subject.first.historic?).to eq true
+ expect(subject.first.historic?).to be true
end
end
+
describe "when querying the timestamp where the column does not match" do
- subject { @relation.at_timestamp(@wednesday) }
+ subject { relation.at_timestamp(wednesday) }
+
it "returns [] because nothing matches" do
expect(subject).to eq []
end
end
+
describe "when querying without at_timestamp" do
- subject { @relation }
+ subject { relation }
+
it "returns the matching records" do
expect(subject.pluck(:description)).to eq ["The work package as it is since Friday"]
expect(subject.pluck(:id)).to eq [work_package.id]
- expect(subject.first.historic?).to eq false
+ expect(subject.first.historic?).to be false
end
end
end
describe "when filtering with a negative condition" do
- before { @relation = WorkPackage.where.not(description: "The work package as it is since Friday") }
+ let(:relation) { WorkPackage.where.not(description: "The work package as it is since Friday") }
+
describe "when querying a timestamp where the column matches" do
- subject { @relation.at_timestamp(@tuesday) }
+ subject { relation.at_timestamp(tuesday) }
+
it "returns the matching records in their historic states" do
expect(subject.pluck(:description)).to eq ["The work package as it has been on Monday"]
expect(subject.pluck(:id)).to eq [work_package.id]
- expect(subject.first.historic?).to eq true
+ expect(subject.first.historic?).to be true
end
end
+
describe "when querying a timestamp where the column does not match" do
- subject { @relation.at_timestamp(@friday) }
+ subject { relation.at_timestamp(friday) }
+
it "returns [] because nothing matches" do
expect(subject).to eq []
end
@@ -205,70 +246,88 @@ describe Journable::Timestamps, type: :model do
end
describe "when filtering on a column of an associated table" do
- before do
- @time_entry = work_package.time_entries.create! user_id: User.first.id, hours: 1, activity_id: 1, project_id: create(:project).id, spent_on: @monday, logged_by_id: User.first.id
- @relation = WorkPackage.joins(:time_entries).where(time_entries: {id: @time_entry.id})
+ let(:time_entry) do
+ work_package.time_entries.create! user_id: User.first.id, hours: 1, activity_id: 1, project_id: create(:project).id,
+ spent_on: monday, logged_by_id: User.first.id
end
+ let(:relation) { WorkPackage.joins(:time_entries).where(time_entries: { id: time_entry.id }) }
+
describe "when querying with at_timestamp" do
- subject { @relation.at_timestamp(@friday) }
+ subject { relation.at_timestamp(friday) }
+
it "joins the journable table rather than the journal-data table" do
- expect(subject.to_sql).not_to include "INNER JOIN \"time_entries\" ON \"time_entries\".\"work_package_id\" = \"work_package_journals\".\"id\""
- expect(subject.to_sql).to include "INNER JOIN \"time_entries\" ON \"time_entries\".\"work_package_id\" = \"journals\".\"journable_id\""
+ expect(subject.to_sql).not_to include \
+ "INNER JOIN \"time_entries\" ON \"time_entries\".\"work_package_id\" = \"work_package_journals\".\"id\""
+ expect(subject.to_sql).to include \
+ "INNER JOIN \"time_entries\" ON \"time_entries\".\"work_package_id\" = \"journals\".\"journable_id\""
end
+
it "returns the matching records in their historic states" do
expect(subject.pluck(:description)).to eq ["The work package as it is since Friday"]
expect(subject.pluck(:id)).to eq [work_package.id]
- expect(subject.first.historic?).to eq true
+ expect(subject.first.historic?).to be true
end
end
+
describe "when querying with a past timestamp" do
# This is a case we have to watch out. Even if the association has been created later
# this still finds the historic record.
- subject { @relation.at_timestamp(@wednesday) }
+ subject { relation.at_timestamp(wednesday) }
+
it "returns still matches because at_timestamp only filters the journable journal and not the associated journal" do
expect(subject.pluck(:description)).to eq ["The work package as it has been on Wednesday"]
end
end
+
describe "when querying without at_timestamp" do
- subject { @relation }
+ subject { relation }
+
it "returns the matching records" do
expect(subject.pluck(:description)).to eq ["The work package as it is since Friday"]
expect(subject.pluck(:id)).to eq [work_package.id]
- expect(subject.first.historic?).to eq false
+ expect(subject.first.historic?).to be false
end
end
end
describe "when filtering on a historic relation" do
- subject { WorkPackage.at_timestamp(@monday).where(description: @description) }
+ subject { WorkPackage.at_timestamp(monday).where(description:) }
+
describe "when the data on that point in history has no matches" do
- before { @description = "The work package as it is since Friday" }
+ let(:description) { "The work package as it is since Friday" }
+
it "returns []" do
expect(subject).to eq []
end
end
+
describe "when the data on that point in history has matches" do
- before { @description = "The work package as it has been on Monday" }
+ let(:description) { "The work package as it has been on Monday" }
+
it "returns the matching records" do
expect(subject.pluck(:description)).to eq ["The work package as it has been on Monday"]
expect(subject.pluck(:id)).to eq [work_package.id]
- expect(subject.first.historic?).to eq true
+ expect(subject.first.historic?).to be true
end
end
end
describe "when filtering on a historic relation with a negative condition" do
- subject { WorkPackage.at_timestamp(@timestamp).where.not(description: "The work package as it is since Friday") }
+ subject { WorkPackage.at_timestamp(timestamp).where.not(description: "The work package as it is since Friday") }
+
describe "when querying a timestamp where the column matches" do
- before { @timestamp = @tuesday }
+ let(:timestamp) { tuesday }
+
it "returns the matching records in their historic states" do
expect(subject.pluck(:description)).to eq ["The work package as it has been on Monday"]
expect(subject.pluck(:id)).to eq [work_package.id]
- expect(subject.first.historic?).to eq true
+ expect(subject.first.historic?).to be true
end
end
+
describe "when querying a timestamp where the column does not match" do
- before { @timestamp = @friday }
+ let(:timestamp) { friday }
+
it "returns [] because nothing matches" do
expect(subject).to eq []
end
@@ -278,18 +337,23 @@ describe Journable::Timestamps, type: :model do
describe "when using the calculational function 'maximum'" do
describe "without at_timestamp" do
subject { WorkPackage.maximum(:estimated_hours) }
+
it "returns the correct result for today" do
expect(subject).to eq 10
end
end
+
describe "after at_timestamp" do
- subject { WorkPackage.at_timestamp(@monday).maximum(:estimated_hours) }
+ subject { WorkPackage.at_timestamp(monday).maximum(:estimated_hours) }
+
it "returns the correct result for that timestamp" do
expect(subject).to eq 5
end
end
+
describe "before at_timestamp" do
- subject { WorkPackage.maximum(:estimated_hours).at_timestamp(@monday) }
+ subject { WorkPackage.maximum(:estimated_hours).at_timestamp(monday) }
+
it "returns an error because maximum returns a float rather than a relation" do
expect { subject }.to raise_error NoMethodError
expect(WorkPackage.maximum(:estimated_hours)).to be_kind_of Float
@@ -300,14 +364,17 @@ describe Journable::Timestamps, type: :model do
describe "when using a GROUP BY COUNT query" do
describe "without at_timestamp" do
subject { WorkPackage.group(:estimated_hours).count }
+
it "returns the correct result for today" do
- expect(subject).to eq({10.0 => 1})
+ expect(subject).to eq({ 10.0 => 1 })
end
end
+
describe "after at_timestamp" do
- subject { WorkPackage.at_timestamp(@monday).group(:estimated_hours).count }
+ subject { WorkPackage.at_timestamp(monday).group(:estimated_hours).count }
+
it "returns the correct result for that timestamp" do
- expect(subject).to eq({5.0 => 1})
+ expect(subject).to eq({ 5.0 => 1 })
end
end
end
@@ -315,90 +382,114 @@ describe Journable::Timestamps, type: :model do
describe "when using a GROUP BY COUNT HAVING query" do
describe "without at_timestamp" do
subject { WorkPackage.group(:estimated_hours).having('estimated_hours > 3').count }
+
it "returns the correct result for today" do
- expect(subject).to eq({10.0 => 1})
+ expect(subject).to eq({ 10.0 => 1 })
end
end
+
describe "after at_timestamp" do
- subject { WorkPackage.at_timestamp(@monday).group(:estimated_hours).having('estimated_hours > 3').count }
+ subject { WorkPackage.at_timestamp(monday).group(:estimated_hours).having('estimated_hours > 3').count }
+
it "returns the correct result for that timestamp" do
- expect(subject).to eq({5.0 => 1})
+ expect(subject).to eq({ 5.0 => 1 })
end
end
end
describe "#created_at" do
- subject { WorkPackage.at_timestamp(@timestamp).first.created_at }
+ subject { WorkPackage.at_timestamp(timestamp).first.created_at }
+
describe "for at_timestamp(before monday)" do
- before { @timestamp = @before_monday }
+ let(:timestamp) { before_monday }
+
it "raises an error because no result exists for that timestamp" do
expect { subject }.to raise_error NoMethodError
end
end
+
describe "for at_timestamp(monday)" do
- before { @timestamp = @monday }
+ let(:timestamp) { monday }
+
it "returns the date the record itself has been created" do
expect(subject).to eq work_package.created_at
- expect(subject).to eq @monday
+ expect(subject).to eq monday
end
end
+
describe "for at_timestamp(tuesday)" do
- before { @timestamp = @tuesday }
+ let(:timestamp) { tuesday }
+
it "returns the date the record itself has been created" do
expect(subject).to eq work_package.created_at
- expect(subject).to eq @monday
+ expect(subject).to eq monday
end
end
+
describe "for at_timestamp(wednesday)" do
- before { @timestamp = @wednesday }
+ let(:timestamp) { wednesday }
+
it "returns the date the record itself has been created" do
expect(subject).to eq work_package.created_at
- expect(subject).to eq @monday
+ expect(subject).to eq monday
end
end
end
describe "#updated_at" do
- subject { WorkPackage.at_timestamp(@timestamp).first.updated_at }
+ subject { WorkPackage.at_timestamp(timestamp).first.updated_at }
+
describe "for at_timestamp(before monday)" do
- before { @timestamp = @before_monday }
+ let(:timestamp) { before_monday }
+
it "raises an error because no result exists for that timestamp" do
expect { subject }.to raise_error NoMethodError
end
end
+
describe "for at_timestamp(monday)" do
- before { @timestamp = @monday }
+ let(:timestamp) { monday }
+
it "returns the date of the monday journal entry" do
- expect(subject).to eq @monday
+ expect(subject).to eq monday
end
end
+
describe "for at_timestamp(tuesday)" do
- before { @timestamp = @tuesday }
+ let(:timestamp) { tuesday }
+
it "returns the date of the monday journal entry" do
- expect(subject).to eq @monday
+ expect(subject).to eq monday
end
end
+
describe "for at_timestamp(wednesday)" do
- before { @timestamp = @wednesday }
+ let(:timestamp) { wednesday }
+
it "returns the date of the wednesday journal entry" do
- expect(subject).to eq @wednesday
+ expect(subject).to eq wednesday
end
end
end
describe "when using historic queries as sub queries" do
subject do
- sub_query = WorkPackage.at_timestamp(@monday).where(description: "The work package as it has been on Monday")
+ sub_query = WorkPackage.at_timestamp(monday).where(description: "The work package as it has been on Monday")
WorkPackage.where(id: sub_query)
end
+
it "returns the current records that have matched the filter on monday" do
expect(subject.pluck(:description)).to eq ["The work package as it is since Friday"]
end
+
describe "when plucking the id as sub query (workaround)" do
subject do
- sub_query = WorkPackage.at_timestamp(@monday).where(description: "The work package as it has been on Monday").pluck(:id)
- WorkPackage.where(id: sub_query)
+ sub_query_ids = WorkPackage.at_timestamp(monday) \
+ .where(description: "The work package as it has been on Monday") \
+ .pluck(:id)
+ WorkPackage.where(id: sub_query_ids)
end
+
it "returns the current records that have matched the filter on monday" do
expect(subject.pluck(:description)).to eq ["The work package as it is since Friday"]
end
@@ -406,14 +497,14 @@ describe Journable::Timestamps, type: :model do
end
describe "when chaining where(id:) in order to request specific work packages at a specific point in time" do
- subject { WorkPackage.where(id: [work_package.id]).at_timestamp(@wednesday) }
+ subject { WorkPackage.where(id: [work_package.id]).at_timestamp(wednesday) }
it "returns the work packages in their state at the requested point in time" do
expect(subject.first.description).to eq "The work package as it has been on Wednesday"
end
describe "when the work package does not exist at the requested time" do
- subject { WorkPackage.where(id: [work_package.id]).at_timestamp(@before_monday) }
+ subject { WorkPackage.where(id: [work_package.id]).at_timestamp(before_monday) }
it "returns an empty result" do
expect(subject.count).to eq 0
@@ -422,7 +513,7 @@ describe Journable::Timestamps, type: :model do
end
describe "when chaining a sql where clause (as used by Query#statement)" do
- subject { WorkPackage.where("(work_packages.description ILIKE '%been on Wednesday%')").at_timestamp(@wednesday) }
+ subject { WorkPackage.where("(work_packages.description ILIKE '%been on Wednesday%')").at_timestamp(wednesday) }
it "transforms the table name" do
expect(subject.to_sql).to include "work_package_journals.description ILIKE"
@@ -434,7 +525,7 @@ describe Journable::Timestamps, type: :model do
end
describe "when chaining an order clause" do
- subject { WorkPackage.at_timestamp(@wednesday).order(description: :desc) }
+ subject { WorkPackage.at_timestamp(wednesday).order(description: :desc) }
it "transforms the table name" do
expect(subject.to_sql).to include "\"work_package_journals\".\"description\" DESC"
@@ -445,7 +536,7 @@ describe Journable::Timestamps, type: :model do
end
describe "when chaining a manual order clause" do
- subject { WorkPackage.order("work_packages.description DESC").at_timestamp(@wednesday) }
+ subject { WorkPackage.order("work_packages.description DESC").at_timestamp(wednesday) }
it "transforms the table name" do
expect(subject.to_sql).to include "work_package_journals.description DESC"
@@ -456,21 +547,21 @@ describe Journable::Timestamps, type: :model do
end
end
end
-
end
describe "#at_timestamp" do
- subject { work_package.at_timestamp(@timestamp) }
+ subject { work_package.at_timestamp(timestamp) }
describe "#at_timestamp(something before monday)" do
- before { @timestamp = @before_monday}
+ let(:timestamp) { before_monday }
+
it "returns nil because before Monday, no journal exists" do
- expect(subject).to eq nil
+ expect(subject).to be_nil
end
end
describe "#at_timestamp(Monday)" do
- before { @timestamp = @monday }
+ let(:timestamp) { monday }
it "returns a record of the same type as the journable" do
expect(subject.class).to eq journable.class
@@ -497,25 +588,28 @@ describe Journable::Timestamps, type: :model do
describe "#historic?" do
describe "when querying historic values of a journable" do
- subject { work_package.at_timestamp(@monday).historic? }
+ subject { work_package.at_timestamp(monday).historic? }
+
it "returns true" do
- expect(subject).to eq true
+ expect(subject).to be true
end
end
describe "for the current journable without querying historic data" do
subject { work_package.historic? }
+
it "returns false" do
- expect(subject).to eq false
+ expect(subject).to be false
end
end
end
describe "#valid?" do
describe "when querying historic values of a journable" do
- subject { work_package.at_timestamp(@monday).valid? }
+ subject { work_package.at_timestamp(monday).valid? }
+
it "returns true" do
- expect(subject).to eq true
+ expect(subject).to be true
end
end
end
@@ -523,10 +617,11 @@ describe Journable::Timestamps, type: :model do
describe "#save" do
describe "when trying to save a historic record" do
subject do
- @work_package = work_package.at_timestamp(@monday)
- @work_package.description = "New description"
- @work_package.save
+ historic_work_package = work_package.at_timestamp(monday)
+ historic_work_package.description = "New description"
+ historic_work_package.save
end
+
it "raises an error" do
expect { subject }.to raise_error ActiveRecord::ReadOnlyRecord
end
@@ -536,9 +631,10 @@ describe Journable::Timestamps, type: :model do
describe "#update" do
describe "when trying to update a historic record" do
subject do
- @work_package = work_package.at_timestamp(@monday)
- @work_package.update description: "New description"
+ historic_work_package = work_package.at_timestamp(monday)
+ historic_work_package.update description: "New description"
end
+
it "raises an error" do
expect { subject }.to raise_error ActiveRecord::ReadOnlyRecord
end
@@ -548,12 +644,15 @@ describe Journable::Timestamps, type: :model do
describe "#rollback!" do
describe "when trying to rollback to a current (non-historic) record" do
subject { work_package.rollback! }
+
it "raises an error" do
expect { subject }.to raise_error ActiveRecord::RecordNotSaved
end
end
+
describe "when rolling back to historic data" do
- subject { work_package.at_timestamp(@wednesday).rollback! }
+ subject { work_package.at_timestamp(wednesday).rollback! }
+
it "updates the journable records to its historic values" do
expect(work_package.reload.description).to eq "The work package as it is since Friday"
subject
@@ -561,6 +660,7 @@ describe Journable::Timestamps, type: :model do
end
end
end
-
end
-end
\ No newline at end of file
+end
+
+# rubocop:enable RSpec/ClassCheck
diff --git a/spec/models/journal/timestamps_spec.rb b/spec/models/journal/timestamps_spec.rb
index 2dcc07f3384..bd611611fb4 100644
--- a/spec/models/journal/timestamps_spec.rb
+++ b/spec/models/journal/timestamps_spec.rb
@@ -28,151 +28,188 @@
require 'spec_helper'
-describe Journal::Timestamps, type: :model do
+describe Journal::Timestamps do
# See: https://github.com/opf/openproject/pull/11243
- let!(:work_package) { create :work_package }
+ let!(:work_package) { create(:work_package) }
let(:journable) { work_package }
describe ".at_timestamp" do
- before { @timestamp = Time.zone.now }
- subject { Journal.at_timestamp(@timestamp) }
+ let(:timestamp) { Time.zone.now }
+
+ subject { Journal.at_timestamp(timestamp) }
it "returns an active-record relation" do
- expect(subject).to be_kind_of ActiveRecord::Relation
+ expect(subject).to be_a ActiveRecord::Relation
end
describe "when appended to a where clause" do
- subject { Journal.where(user_id: work_package.author_id).at_timestamp(@timestamp) }
+ subject { Journal.where(user_id: work_package.author_id).at_timestamp(timestamp) }
+
it "returns an active-record relation" do
- expect(subject).to be_kind_of ActiveRecord::Relation
+ expect(subject).to be_a ActiveRecord::Relation
end
end
+
describe "when prepended to a where clause" do
- subject { Journal.at_timestamp(@timestamp).where(user_id: work_package.author_id) }
+ subject { Journal.at_timestamp(timestamp).where(user_id: work_package.author_id) }
+
it "returns an active-record relation" do
- expect(subject).to be_kind_of ActiveRecord::Relation
+ expect(subject).to be_a ActiveRecord::Relation
end
end
describe "when the given timestamp is nil" do
- before { @timestamp = nil }
+ let(:timestamp) { nil }
+
it "raises an error" do
expect { subject }.to raise_error ArgumentError
end
end
+
describe "when the given timestamp is nonsense" do
- before { @timestamp = "FOO BAR" }
+ let(:timestamp) { "FOO BAR" }
+
it "raises an error" do
expect { subject }.to raise_error ArgumentError
end
end
+
describe "when the given timestamp is given as DateTime" do
- before { @timestamp = DateTime.current }
+ let(:timestamp) { DateTime.current }
+
it "raises no error" do
expect { subject }.not_to raise_error
end
end
+
describe "when the given timestamp is given as ActiveSupport::TimeWithZone" do
- before { @timestamp = Time.zone.now }
+ let(:timestamp) { Time.zone.now }
+
it "raises no error" do
- expect(@timestamp).to be_kind_of ActiveSupport::TimeWithZone
+ expect(timestamp).to be_a ActiveSupport::TimeWithZone
expect { subject }.not_to raise_error
end
end
describe "when there are journals for Monday, Wednesday, and Friday" do
+ let(:before_monday) { "2022-01-01".to_datetime }
+ let(:monday) { "2022-08-01".to_datetime }
+ let(:tuesday) { "2022-08-02".to_datetime }
+ let(:wednesday) { "2022-08-03".to_datetime }
+ let(:thursday) { "2022-08-04".to_datetime }
+ let(:friday) { "2022-08-05".to_datetime }
+
+ let(:monday_journal) { create(:work_package_journal, journable: work_package, created_at: monday) }
+ let(:wednesday_journal) { create(:work_package_journal, journable: work_package, created_at: wednesday) }
+ let(:friday_journal) { create(:work_package_journal, journable: work_package, created_at: friday) }
+
before do
- @before_monday = "2022-01-01".to_datetime
- @monday = "2022-08-01".to_datetime
- @tuesday = "2022-08-02".to_datetime
- @wednesday = "2022-08-03".to_datetime
- @thursday = "2022-08-04".to_datetime
- @friday = "2022-08-05".to_datetime
work_package.journals.destroy_all
- @monday_journal = create :work_package_journal, journable: work_package, created_at: @monday
- @wednesday_journal = create :work_package_journal, journable: work_package, created_at: @wednesday
- @friday_journal = create :work_package_journal, journable: work_package, created_at: @friday
+ monday_journal
+ wednesday_journal
+ friday_journal
end
describe ".at_timestamp(something before Monday)" do
- before { @timestamp = @before_monday }
+ let(:timestamp) { before_monday }
+
it "returns [] because before Monday, no journal exists" do
expect(subject).to eq []
end
end
+
describe ".at_timestamp(Monday)" do
- before { @timestamp = @monday }
+ let(:timestamp) { monday }
+
it "returns only the Monday journal because this is the most current on Monday" do
- expect(subject).to eq [@monday_journal]
+ expect(subject).to eq [monday_journal]
end
end
+
describe ".at_timestamp(Tuesday)" do
- before { @timestamp = @tuesday }
+ let(:timestamp) { tuesday }
+
it "returns only the Monday journal because this is the most current on Tuesday" do
- expect(subject).to eq [@monday_journal]
+ expect(subject).to eq [monday_journal]
end
end
+
describe ".at_timestamp(Wednesday)" do
- before { @timestamp = @wednesday }
+ let(:timestamp) { wednesday }
+
it "returns only the Wednesday journal because this is the most current on Wednesday" do
- expect(subject).to eq [@wednesday_journal]
+ expect(subject).to eq [wednesday_journal]
end
end
+
describe ".at_timestamp(Thursday)" do
- before { @timestamp = @thursday }
+ let(:timestamp) { thursday }
+
it "returns only the Wednesday journal because this is the most current on Thursday" do
- expect(subject).to eq [@wednesday_journal]
+ expect(subject).to eq [wednesday_journal]
end
end
+
describe ".at_timestamp(Friday)" do
- before { @timestamp = @friday }
+ let(:timestamp) { friday }
+
it "returns only the Friday journal because this is the most current on Friday" do
- expect(subject).to eq [@friday_journal]
+ expect(subject).to eq [friday_journal]
end
end
describe "when at_timestamp is called on an association" do
- subject { journable.journals.at_timestamp(@timestamp) }
+ subject { journable.journals.at_timestamp(timestamp) }
describe ".at_timestamp(something before Monday)" do
- before { @timestamp = @before_monday }
+ let(:timestamp) { before_monday }
+
it "returns [] because before Monday, no journal exists" do
expect(subject).to eq []
end
end
+
describe ".at_timestamp(Monday)" do
- before { @timestamp = @monday }
+ let(:timestamp) { monday }
+
it "returns only the Monday journal because this is the most current on Monday" do
- expect(subject).to eq [@monday_journal]
+ expect(subject).to eq [monday_journal]
end
end
+
describe ".at_timestamp(Tuesday)" do
- before { @timestamp = @tuesday }
+ let(:timestamp) { tuesday }
+
it "returns only the Monday journal because this is the most current on Tuesday" do
- expect(subject).to eq [@monday_journal]
+ expect(subject).to eq [monday_journal]
end
end
+
describe ".at_timestamp(Wednesday)" do
- before { @timestamp = @wednesday }
+ let(:timestamp) { wednesday }
+
it "returns only the Wednesday journal because this is the most current on Wednesday" do
- expect(subject).to eq [@wednesday_journal]
+ expect(subject).to eq [wednesday_journal]
end
end
+
describe ".at_timestamp(Thursday)" do
- before { @timestamp = @thursday }
+ let(:timestamp) { thursday }
+
it "returns only the Wednesday journal because this is the most current on Thursday" do
- expect(subject).to eq [@wednesday_journal]
+ expect(subject).to eq [wednesday_journal]
end
end
+
describe ".at_timestamp(Friday)" do
- before { @timestamp = @friday }
+ let(:timestamp) { friday }
+
it "returns only the Friday journal because this is the most current on Friday" do
- expect(subject).to eq [@friday_journal]
+ expect(subject).to eq [friday_journal]
end
end
end
end
-
end
end