summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlex Kalderimis <alex.kalderimis@gmail.com>2019-08-03 22:29:30 +0100
committerAlex Kalderimis <alex.kalderimis@gmail.com>2019-08-03 22:29:30 +0100
commite6d18d605a380fc10b7b5692970a628debf41971 (patch)
tree941849a3f66de22e60f9236f6986ce1aae1cbd79
parentbce8b66d516e906f6131d8a6dcae797def5288b6 (diff)
downloadgitlab-ce-nil-safe-object_from_id.tar.gz
Support empty GIDsnil-safe-object_from_id
In places we use the pattern `gid ? object_from_id(gid) : nil`, which is a bit confusing to read. Such usages can be improved by providing a separate method which allows non-present arguments, returning nil when so called.
-rw-r--r--app/graphql/gitlab_schema.rb4
-rw-r--r--spec/graphql/gitlab_schema_spec.rb25
2 files changed, 29 insertions, 0 deletions
diff --git a/app/graphql/gitlab_schema.rb b/app/graphql/gitlab_schema.rb
index 7edd14e48f7..ac04eff44c1 100644
--- a/app/graphql/gitlab_schema.rb
+++ b/app/graphql/gitlab_schema.rb
@@ -57,6 +57,10 @@ class GitlabSchema < GraphQL::Schema
object.to_global_id
end
+ def object_from_id_when_present(global_id)
+ object_from_id(global_id) if global_id.present?
+ end
+
def object_from_id(global_id)
gid = GlobalID.parse(global_id)
diff --git a/spec/graphql/gitlab_schema_spec.rb b/spec/graphql/gitlab_schema_spec.rb
index dec6b23d72a..d101a3fd109 100644
--- a/spec/graphql/gitlab_schema_spec.rb
+++ b/spec/graphql/gitlab_schema_spec.rb
@@ -122,6 +122,31 @@ describe GitlabSchema do
end
end
+ describe '.object_from_id_when_present' do
+ context 'when the input is nil' do
+ it 'returns nil' do
+ expect(described_class.object_from_id_when_present(nil)).to be_nil
+ end
+ end
+
+ context 'when the input is an empty string' do
+ it 'returns nil' do
+ expect(described_class.object_from_id_when_present('')).to be_nil
+ end
+ end
+
+ context 'when the object is not nil' do
+ it 'behaves as object_from_id' do
+ user = create(:user)
+ gid = user.to_global_id.to_s
+
+ result = described_class.object_from_id_when_present(gid).__sync
+
+ expect(result).to eq(described_class.object_from_id(gid).__sync)
+ end
+ end
+ end
+
describe '.object_from_id' do
context 'for subclasses of `ApplicationRecord`' do
it 'returns the correct record' do