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

PoC: Optimize predicate methods with attr_reader #5082

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
37 changes: 28 additions & 9 deletions lib/graphql/type_kinds.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,41 @@ def initialize(name, abstract: false, leaf: false, fields: false, wraps: false,
@description = description
end

# Is this TypeKind abstract?
attr_reader :abstract
alias_method :abstract?, :abstract
remove_method :abstract
Comment on lines +20 to +22
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's also possible to make a helper to automate these, but then IDEs won't know about the presence of the generated methods.

module PredicateHelper # This can be mixed into Module, if you're into monkey-patching
  # Given `"foo?"`, this method generates an optimized method that reads from `@foo`.
  def attr_predicate(predicate_name)
    raise ArgumentError unless predicate_name.end_with?("?")
    
    attr_method_name = predicate_name.to_s.delete_suffix("?")
    attr_reader(attr_method_name)
    alias_method(predicate_name, attr_method_name)
    remove_method(attr_method_name)
  end
end


# Does this TypeKind have multiple possible implementers?
# @deprecated Use `abstract?` instead of `resolves?`.
def resolves?; @abstract; end
# Is this TypeKind abstract?
def abstract?; @abstract; end
alias_method :resolves?, :abstract?

# Does this TypeKind have queryable fields?
def fields?; @fields; end
attr_reader :fields
alias_method :fields?, :fields
remove_method :fields

# Does this TypeKind modify another type?
def wraps?; @wraps; end
attr_reader :wraps
alias_method :wraps?, :wraps
remove_method :wraps

# Is this TypeKind a valid query input?
def input?; @input; end
def to_s; @name; end
attr_reader :input
alias_method :input?, :input
remove_method :input

# Is this TypeKind a primitive value?
def leaf?; @leaf; end
attr_reader :leaf
alias_method :leaf?, :leaf
remove_method :leaf

# Is this TypeKind composed of many values?
def composite?; @composite; end
attr_reader :composite
alias_method :composite?, :composite
remove_method :composite

alias_method :to_s, :name

def scalar?
self == TypeKinds::SCALAR
Expand Down