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

Fix Person trying to serialize non-existing methods in User #10575

Merged
merged 4 commits into from
Jan 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion app/models/person.rb
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,14 @@ def self.fields_edit_requestable
methods: ["url", "country_iso2"],
}.freeze

USER_COMMON_SERIALIZE_OPTIONS = {
only: ["name", "gender"],
methods: ["country_iso2"],
# grrr… some tests (and apparently also API endpoints) rely on serializing this data _through_ person.
# Not a good code design decision, but very cumbersome to properly refactor. Signed GB 2025-01-09
include: User::DEFAULT_SERIALIZE_OPTIONS[:include],
}.freeze

def personal_records
[self.ranksAverage, self.ranksSingle].compact.flatten
end
Expand Down Expand Up @@ -306,8 +314,17 @@ def serializable_hash(options = nil)
json[:incorrect_wca_id_claim_count] = incorrect_wca_id_claim_count
end

# Passing down options from Person to User (which are completely different models in the DB!)
# is a horrible idea. Unfortunately, our external APIs have come to rely on it,
# so we need to hack around it.
# - `merge_union` makes sure that only values specified in USER_COMMON_SERIALIZE_OPTIONS kick in
# - `filter` makes sure that when the result of `merge_union` are empty, the defaults from
# User::DEFAULT_SERIALIZE_OPTIONS can override.
user_override_options = USER_COMMON_SERIALIZE_OPTIONS.merge_union(options&.stringify_keys)
.filter { |_, v| v.present? }

# If there's a user for this Person, merge in all their data,
# the Person's data takes priority, though.
(user || User.new).serializable_hash(options).merge(json)
(user || User.new).serializable_hash(user_override_options).merge(json)
end
end
8 changes: 8 additions & 0 deletions config/initializers/monkey_patches.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,14 @@ def xss_aware_join(delimiter = '')
end
end

Hash.class_eval do
def merge_union(other = nil)
self.to_h do |key, value|
[key, value & (other&.fetch(key.to_s, []) || [])]
end
end
end

ActiveSupport::Duration.class_eval do
def in_seconds
self.to_i
Expand Down
Loading