Add type_of? #70

Merged
merged 1 commit into from Feb 3, 2017

Projects

None yet

3 participants

@josh
Member
josh commented Feb 3, 2017 edited

Using typename comparisons should generally be avoided as its limited to base types and doesn't support interfaces or unions. This adds a preferred client side type checker that doesn't need to make any additional queries to check the type hierarchy.

comment.type_of?(:Comment)
comment.type_of?(:IssueComment)
comment.type_of?(:Reactable)
!comment.type_of?(:User)

Closes #69

CC: @mclark @tma @rmosolgo @aroben

@josh josh Add type_of?
dc48f57
@josh
Member
josh commented Feb 3, 2017

Hmm, should === be implemented as well so case statements would work?

case comment
when :IssueComment
   # ...
when :Comment
  # ...
else
end
@mclark

This looks great, and I strongly agree with your idea to implement the === method for case equality.

@josh
Member
josh commented Feb 3, 2017

Hmm, should === be implemented as well so case statements would work?

I forgot, the left and right hand are switched when case calls ===. So it attempts to send === on Symbol not the GraphQL wrapper class: :IssueComment.===(comment).

@josh
Member
josh commented Feb 3, 2017

@mclark I'll merge this for now to unblock your internal changes.

@josh josh merged commit 011bc1a into master Feb 3, 2017

2 checks passed

continuous-integration/travis-ci/pr The Travis CI build passed
Details
continuous-integration/travis-ci/push The Travis CI build passed
Details
@josh josh deleted the type-of branch Feb 3, 2017
@tma

Looks like a great addition to the public API of query results 👍 .

+ else
+ false
+ end
+ end
@tma
tma Feb 6, 2017 Member

My only suggestion would be to convert this use a guard clause instead of an else statement:

def type_of?(type)
  type = self.class.schema.types.fetch(type.to_s, nil)
  return false unless type

  self.class.schema.possible_types(type).any? { |t| __typename == t.name }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment