repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/relay_classic_mutation.rb | lib/graphql/schema/relay_classic_mutation.rb | # frozen_string_literal: true
module GraphQL
class Schema
# Mutations that extend this base class get some conventions added for free:
#
# - An argument called `clientMutationId` is _always_ added, but it's not passed
# to the resolve method. The value is re-inserted to the response. (It's for
# client libraries to manage optimistic updates.)
# - The returned object type always has a field called `clientMutationId` to support that.
# - The mutation accepts one argument called `input`, `argument`s defined in the mutation
# class are added to that input object, which is generated by the mutation.
#
# These conventions were first specified by Relay Classic, but they come in handy:
#
# - `clientMutationId` supports optimistic updates and cache rollbacks on the client
# - using a single `input:` argument makes it easy to post whole JSON objects to the mutation
# using one GraphQL variable (`$input`) instead of making a separate variable for each argument.
#
# @see {GraphQL::Schema::Mutation} for an example, it's basically the same.
#
class RelayClassicMutation < GraphQL::Schema::Mutation
include GraphQL::Schema::HasSingleInputArgument
argument :client_mutation_id, String, "A unique identifier for the client performing the mutation.", required: false
# The payload should always include this field
field(:client_mutation_id, String, "A unique identifier for the client performing the mutation.")
# Relay classic default:
null(true)
# Override {GraphQL::Schema::Resolver#resolve_with_support} to
# delete `client_mutation_id` from the kwargs.
def resolve_with_support(**inputs)
input = inputs[:input].to_kwargs
if input
# This is handled by Relay::Mutation::Resolve, a bit hacky, but here we are.
input_kwargs = input.to_h
client_mutation_id = input_kwargs.delete(:client_mutation_id)
inputs[:input] = input_kwargs
end
return_value = super(**inputs)
context.query.after_lazy(return_value) do |return_hash|
# It might be an error
if return_hash.is_a?(Hash)
return_hash[:client_mutation_id] = client_mutation_id
end
return_hash
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/has_single_input_argument.rb | lib/graphql/schema/has_single_input_argument.rb | # frozen_string_literal: true
module GraphQL
class Schema
module HasSingleInputArgument
def resolve_with_support(**inputs)
if inputs[:input].is_a?(InputObject)
input = inputs[:input].to_kwargs
else
input = inputs[:input]
end
new_extras = field ? field.extras : []
all_extras = self.class.extras + new_extras
# Transfer these from the top-level hash to the
# shortcutted `input:` object
all_extras.each do |ext|
# It's possible that the `extra` was not passed along by this point,
# don't re-add it if it wasn't given here.
if inputs.key?(ext)
input[ext] = inputs[ext]
end
end
if input
# This is handled by Relay::Mutation::Resolve, a bit hacky, but here we are.
input_kwargs = input.to_h
else
# Relay Classic Mutations with no `argument`s
# don't require `input:`
input_kwargs = {}
end
if !input_kwargs.empty?
super(**input_kwargs)
else
super()
end
end
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def dummy
@dummy ||= begin
d = Class.new(GraphQL::Schema::Resolver)
d.graphql_name "#{self.graphql_name}DummyResolver"
d.argument_class(self.argument_class)
# TODO make this lazier?
d.argument(:input, input_type, description: "Parameters for #{self.graphql_name}")
d
end
end
def field_arguments(context = GraphQL::Query::NullContext.instance)
dummy.arguments(context)
end
def get_field_argument(name, context = GraphQL::Query::NullContext.instance)
dummy.get_argument(name, context)
end
def own_field_arguments
dummy.own_arguments
end
def any_field_arguments?
dummy.any_arguments?
end
def all_field_argument_definitions
dummy.all_argument_definitions
end
# Also apply this argument to the input type:
def argument(*args, own_argument: false, **kwargs, &block)
it = input_type # make sure any inherited arguments are already added to it
arg = super(*args, **kwargs, &block)
# This definition might be overriding something inherited;
# if it is, remove the inherited definition so it's not confused at runtime as having multiple definitions
prev_args = it.own_arguments[arg.graphql_name]
case prev_args
when GraphQL::Schema::Argument
if prev_args.owner != self
it.own_arguments.delete(arg.graphql_name)
end
when Array
prev_args.reject! { |a| a.owner != self }
if prev_args.empty?
it.own_arguments.delete(arg.graphql_name)
end
end
it.add_argument(arg)
arg
end
# The base class for generated input object types
# @param new_class [Class] The base class to use for generating input object definitions
# @return [Class] The base class for this mutation's generated input object (default is {GraphQL::Schema::InputObject})
def input_object_class(new_class = nil)
if new_class
@input_object_class = new_class
end
@input_object_class || (superclass.respond_to?(:input_object_class) ? superclass.input_object_class : GraphQL::Schema::InputObject)
end
# @param new_input_type [Class, nil] If provided, it configures this mutation to accept `new_input_type` instead of generating an input type
# @return [Class] The generated {Schema::InputObject} class for this mutation's `input`
def input_type(new_input_type = nil)
if new_input_type
@input_type = new_input_type
end
@input_type ||= generate_input_type
end
private
# Generate the input type for the `input:` argument
# To customize how input objects are generated, override this method
# @return [Class] a subclass of {.input_object_class}
def generate_input_type
mutation_args = all_argument_definitions
mutation_class = self
Class.new(input_object_class) do
class << self
def default_graphql_name
"#{self.mutation.graphql_name}Input"
end
def description(new_desc = nil)
super || "Autogenerated input type of #{self.mutation.graphql_name}"
end
end
# For compatibility, in case no arguments are defined:
has_no_arguments(true)
mutation(mutation_class)
# these might be inherited:
mutation_args.each do |arg|
add_argument(arg)
end
end
end
end
private
def authorize_arguments(args, values)
# remove the `input` wrapper to match values
input_type = args.find { |a| a.graphql_name == "input" }.type.unwrap
input_args = context.types.arguments(input_type)
super(input_args, values)
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/wrapper.rb | lib/graphql/schema/wrapper.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Wrapper
include GraphQL::Schema::Member::TypeSystemHelpers
# @return [Class, Module] The inner type of this wrapping type, the type of which one or more objects may be present.
attr_reader :of_type
def initialize(of_type)
@of_type = of_type
end
def unwrap
@of_type.unwrap
end
def ==(other)
self.class == other.class && of_type == other.of_type
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/late_bound_type.rb | lib/graphql/schema/late_bound_type.rb | # frozen_string_literal: true
module GraphQL
class Schema
# A stand-in for a type which will be resolved in a given schema, by name.
# TODO: support argument types too, make this a public API somehow
# @api Private
class LateBoundType
attr_reader :name
alias :graphql_name :name
def initialize(local_name)
@name = local_name
@to_non_null_type = nil
@to_list_type = nil
end
def unwrap
self
end
def to_non_null_type
@to_non_null_type ||= GraphQL::Schema::NonNull.new(self)
end
def to_list_type
@to_list_type ||= GraphQL::Schema::List.new(self)
end
def to_type_signature
name
end
def inspect
"#<LateBoundType @name=#{name}>"
end
def non_null?
false
end
alias :to_s :inspect
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/input_object.rb | lib/graphql/schema/input_object.rb | # frozen_string_literal: true
module GraphQL
class Schema
class InputObject < GraphQL::Schema::Member
extend Forwardable
extend GraphQL::Schema::Member::HasArguments
extend GraphQL::Schema::Member::HasArguments::ArgumentObjectLoader
extend GraphQL::Schema::Member::ValidatesInput
extend GraphQL::Schema::Member::HasValidators
include GraphQL::Dig
# Raised when an InputObject doesn't have any arguments defined and hasn't explicitly opted out of this requirement
class ArgumentsAreRequiredError < GraphQL::Error
def initialize(input_object_type)
message = "Input Object types must have arguments, but #{input_object_type.graphql_name} doesn't have any. Define an argument for this type, remove it from your schema, or add `has_no_arguments(true)` to its definition."
super(message)
end
end
# @return [GraphQL::Query::Context] The context for this query
attr_reader :context
# @return [GraphQL::Execution::Interpereter::Arguments] The underlying arguments instance
attr_reader :arguments
# Ruby-like hash behaviors, read-only
def_delegators :@ruby_style_hash, :keys, :values, :each, :map, :any?, :empty?
def initialize(arguments, ruby_kwargs:, context:, defaults_used:)
@context = context
@ruby_style_hash = ruby_kwargs
@arguments = arguments
# Apply prepares, not great to have it duplicated here.
arg_defns = context ? context.types.arguments(self.class) : self.class.arguments(context).each_value
arg_defns.each do |arg_defn|
ruby_kwargs_key = arg_defn.keyword
if @ruby_style_hash.key?(ruby_kwargs_key)
# Weirdly, procs are applied during coercion, but not methods.
# Probably because these methods require a `self`.
if arg_defn.prepare.is_a?(Symbol) || context.nil?
prepared_value = arg_defn.prepare_value(self, @ruby_style_hash[ruby_kwargs_key], context: context)
overwrite_argument(ruby_kwargs_key, prepared_value)
end
end
end
end
def to_h
unwrap_value(@ruby_style_hash)
end
def to_hash
to_h
end
def deconstruct_keys(keys = nil)
if keys.nil?
@ruby_style_hash
else
new_h = {}
keys.each { |k| @ruby_style_hash.key?(k) && new_h[k] = @ruby_style_hash[k] }
new_h
end
end
def prepare
self
end
def unwrap_value(value)
case value
when Array
value.map { |item| unwrap_value(item) }
when Hash
value.reduce({}) do |h, (key, value)|
h.merge!(key => unwrap_value(value))
end
when InputObject
value.to_h
else
value
end
end
# Lookup a key on this object, it accepts new-style underscored symbols
# Or old-style camelized identifiers.
# @param key [Symbol, String]
def [](key)
if @ruby_style_hash.key?(key)
@ruby_style_hash[key]
elsif @arguments
@arguments[key]
else
nil
end
end
def key?(key)
@ruby_style_hash.key?(key) || (@arguments && @arguments.key?(key)) || false
end
# A copy of the Ruby-style hash
def to_kwargs
@ruby_style_hash.dup
end
# @api private
def validate_for(context)
object = context[:current_object]
# Pass this object's class with `as` so that messages are rendered correctly from inherited validators
Schema::Validator.validate!(self.class.validators, object, context, @ruby_style_hash, as: self.class)
nil
end
class << self
def authorized?(obj, value, ctx)
# Authorize each argument (but this doesn't apply if `prepare` is implemented):
if value.respond_to?(:key?)
ctx.types.arguments(self).each do |input_obj_arg|
if value.key?(input_obj_arg.keyword) &&
!input_obj_arg.authorized?(obj, value[input_obj_arg.keyword], ctx)
return false
end
end
end
# It didn't early-return false:
true
end
def one_of
if !one_of?
if all_argument_definitions.any? { |arg| arg.type.non_null? }
raise ArgumentError, "`one_of` may not be used with required arguments -- add `required: false` to argument definitions to use `one_of`"
end
directive(GraphQL::Schema::Directive::OneOf)
end
end
def one_of?
false # Re-defined when `OneOf` is added
end
def argument(*args, **kwargs, &block)
argument_defn = super(*args, **kwargs, &block)
if one_of?
if argument_defn.type.non_null?
raise ArgumentError, "Argument '#{argument_defn.path}' must be nullable because it is part of a OneOf type, add `required: false`."
end
if argument_defn.default_value?
raise ArgumentError, "Argument '#{argument_defn.path}' cannot have a default value because it is part of a OneOf type, remove `default_value: ...`."
end
end
# Add a method access
suppress_redefinition_warning do
define_accessor_method(argument_defn.keyword)
end
argument_defn
end
def kind
GraphQL::TypeKinds::INPUT_OBJECT
end
# @api private
INVALID_OBJECT_MESSAGE = "Expected %{object} to be a key-value object."
def validate_non_null_input(input, ctx, max_errors: nil)
types = ctx.types
if input.is_a?(Array)
return GraphQL::Query::InputValidationResult.from_problem(INVALID_OBJECT_MESSAGE % { object: JSON.generate(input, quirks_mode: true) })
end
if !(input.respond_to?(:to_h) || input.respond_to?(:to_unsafe_h))
# We're not sure it'll act like a hash, so reject it:
return GraphQL::Query::InputValidationResult.from_problem(INVALID_OBJECT_MESSAGE % { object: JSON.generate(input, quirks_mode: true) })
end
result = nil
input.each do |argument_name, value|
argument = types.argument(self, argument_name)
if argument.nil? && ctx.is_a?(Query::NullContext) && argument_name.is_a?(Symbol)
# Validating definition directive arguments which come in as Symbols
argument = types.arguments(self).find { |arg| arg.keyword == argument_name }
end
# Items in the input that are unexpected
if argument.nil?
result ||= Query::InputValidationResult.new
result.add_problem("Field is not defined on #{self.graphql_name}", [argument_name])
else
# Items in the input that are expected, but have invalid values
argument_result = argument.type.validate_input(value, ctx)
if !argument_result.valid?
result ||= Query::InputValidationResult.new
result.merge_result!(argument_name, argument_result)
end
end
end
# Check for missing non-null arguments
ctx.types.arguments(self).each do |argument|
if !input.key?(argument.graphql_name) && argument.type.non_null? && !argument.default_value?
result ||= Query::InputValidationResult.new
argument_result = argument.type.validate_input(nil, ctx)
if !argument_result.valid?
result.merge_result!(argument.graphql_name, argument_result)
end
end
end
if one_of?
if input.size == 1
input.each do |name, value|
if value.nil?
result ||= Query::InputValidationResult.new
result.add_problem("'#{graphql_name}' requires exactly one argument, but '#{name}' was `null`.")
end
end
else
result ||= Query::InputValidationResult.new
result.add_problem("'#{graphql_name}' requires exactly one argument, but #{input.size} were provided.")
end
end
result
end
def coerce_input(value, ctx)
if value.nil?
return nil
end
arguments = coerce_arguments(nil, value, ctx)
ctx.query.after_lazy(arguments) do |resolved_arguments|
if resolved_arguments.is_a?(GraphQL::Error)
raise resolved_arguments
else
self.new(resolved_arguments, ruby_kwargs: resolved_arguments.keyword_arguments, context: ctx, defaults_used: nil)
end
end
end
# It's funny to think of a _result_ of an input object.
# This is used for rendering the default value in introspection responses.
def coerce_result(value, ctx)
# Allow the application to provide values as :snake_symbols, and convert them to the camelStrings
value = value.reduce({}) { |memo, (k, v)| memo[Member::BuildType.camelize(k.to_s)] = v; memo }
result = {}
arguments(ctx).each do |input_key, input_field_defn|
input_value = value[input_key]
if value.key?(input_key)
result[input_key] = if input_value.nil?
nil
else
input_field_defn.type.coerce_result(input_value, ctx)
end
end
end
result
end
# @param new_has_no_arguments [Boolean] Call with `true` to make this InputObject type ignore the requirement to have any defined arguments.
# @return [void]
def has_no_arguments(new_has_no_arguments)
@has_no_arguments = new_has_no_arguments
nil
end
# @return [Boolean] `true` if `has_no_arguments(true)` was configued
def has_no_arguments?
@has_no_arguments
end
def arguments(context = GraphQL::Query::NullContext.instance, require_defined_arguments = true)
if require_defined_arguments && !has_no_arguments? && !any_arguments?
warn(GraphQL::Schema::InputObject::ArgumentsAreRequiredError.new(self).message + "\n\nThis will raise an error in a future GraphQL-Ruby version.")
end
super(context, false)
end
private
# Suppress redefinition warning for objectId arguments
def suppress_redefinition_warning
verbose = $VERBOSE
$VERBOSE = nil
yield
ensure
$VERBOSE = verbose
end
def define_accessor_method(method_name)
define_method(method_name) { self[method_name] }
alias_method(method_name, method_name)
end
end
private
def overwrite_argument(key, value)
# Argument keywords come in frozen from the interpreter, dup them before modifying them.
if @ruby_style_hash.frozen?
@ruby_style_hash = @ruby_style_hash.dup
end
@ruby_style_hash[key] = value
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/argument.rb | lib/graphql/schema/argument.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Argument
include GraphQL::Schema::Member::HasPath
include GraphQL::Schema::Member::HasAstNode
include GraphQL::Schema::Member::HasDirectives
include GraphQL::Schema::Member::HasDeprecationReason
include GraphQL::Schema::Member::HasValidators
include GraphQL::EmptyObjects
# @return [String] the GraphQL name for this argument, camelized unless `camelize: false` is provided
attr_reader :name
alias :graphql_name :name
# @return [GraphQL::Schema::Field, Class] The field or input object this argument belongs to
attr_reader :owner
# @param new_prepare [Method, Proc]
# @return [Symbol] A method or proc to call to transform this value before sending it to field resolution method
def prepare(new_prepare = NOT_CONFIGURED)
if new_prepare != NOT_CONFIGURED
@prepare = new_prepare
end
@prepare
end
# @return [Symbol] This argument's name in Ruby keyword arguments
attr_reader :keyword
# @return [Class, Module, nil] If this argument should load an application object, this is the type of object to load
attr_reader :loads
# @return [Boolean] true if a resolver defined this argument
def from_resolver?
@from_resolver
end
# @param arg_name [Symbol]
# @param type_expr
# @param desc [String]
# @param required [Boolean, :nullable] if true, this argument is non-null; if false, this argument is nullable. If `:nullable`, then the argument must be provided, though it may be `null`.
# @param description [String]
# @param default_value [Object]
# @param as [Symbol] Override the keyword name when passed to a method
# @param prepare [Symbol] A method to call to transform this argument's valuebefore sending it to field resolution
# @param camelize [Boolean] if true, the name will be camelized when building the schema
# @param from_resolver [Boolean] if true, a Resolver class defined this argument
# @param directives [Hash{Class => Hash}]
# @param deprecation_reason [String]
# @param validates [Hash, nil] Options for building validators, if any should be applied
# @param replace_null_with_default [Boolean] if `true`, incoming values of `null` will be replaced with the configured `default_value`
def initialize(arg_name = nil, type_expr = nil, desc = nil, required: true, type: nil, name: nil, loads: nil, description: nil, comment: nil, ast_node: nil, default_value: NOT_CONFIGURED, as: nil, from_resolver: false, camelize: true, prepare: nil, owner:, validates: nil, directives: nil, deprecation_reason: nil, replace_null_with_default: false, &definition_block)
arg_name ||= name
@name = -(camelize ? Member::BuildType.camelize(arg_name.to_s) : arg_name.to_s)
NameValidator.validate!(@name)
@type_expr = type_expr || type
@description = desc || description
@comment = comment
@null = required != true
@default_value = default_value
if replace_null_with_default
if !default_value?
raise ArgumentError, "`replace_null_with_default: true` requires a default value, please provide one with `default_value: ...`"
end
@replace_null_with_default = true
end
@owner = owner
@as = as
@loads = loads
@keyword = as || (arg_name.is_a?(Symbol) ? arg_name : Schema::Member::BuildType.underscore(@name).to_sym)
@prepare = prepare
@ast_node = ast_node
@from_resolver = from_resolver
self.deprecation_reason = deprecation_reason
if directives
directives.each do |dir_class, dir_options|
directive(dir_class, **dir_options)
end
end
if validates && !validates.empty?
self.validates(validates)
end
if required == :nullable
self.owner.validates(required: { argument: arg_name })
end
if definition_block
# `self` will still be self, it will also be the first argument to the block:
instance_exec(self, &definition_block)
end
end
def inspect
"#<#{self.class} #{path}: #{type.to_type_signature}#{description ? " @description=#{description.inspect}" : ""}>"
end
# @param default_value [Object] The value to use when the client doesn't provide one
# @return [Object] the value used when the client doesn't provide a value for this argument
def default_value(new_default_value = NOT_CONFIGURED)
if new_default_value != NOT_CONFIGURED
@default_value = new_default_value
end
@default_value
end
# @return [Boolean] True if this argument has a default value
def default_value?
@default_value != NOT_CONFIGURED
end
def replace_null_with_default?
@replace_null_with_default
end
attr_writer :description
# @return [String] Documentation for this argument
def description(text = nil)
if text
@description = text
else
@description
end
end
attr_writer :comment
# @return [String] Comment for this argument
def comment(text = nil)
if text
@comment = text
else
@comment
end
end
# @return [String] Deprecation reason for this argument
def deprecation_reason(text = nil)
if text
self.deprecation_reason = text
else
super()
end
end
def deprecation_reason=(new_reason)
validate_deprecated_or_optional(null: @null, deprecation_reason: new_reason)
super
end
def visible?(context)
true
end
def authorized?(obj, value, ctx)
authorized_as_type?(obj, value, ctx, as_type: type)
end
def authorized_as_type?(obj, value, ctx, as_type:)
if value.nil?
return true
end
if as_type.kind.non_null?
as_type = as_type.of_type
end
if as_type.kind.list?
value.each do |v|
if !authorized_as_type?(obj, v, ctx, as_type: as_type.of_type)
return false
end
end
elsif as_type.kind.input_object?
return as_type.authorized?(obj, value, ctx)
end
# None of the early-return conditions were activated,
# so this is authorized.
true
end
def type=(new_type)
validate_input_type(new_type)
# This isn't true for LateBoundTypes, but we can assume those will
# be updated via this codepath later in schema setup.
if new_type.respond_to?(:non_null?)
validate_deprecated_or_optional(null: !new_type.non_null?, deprecation_reason: deprecation_reason)
end
@type = new_type
end
def type
@type ||= begin
parsed_type = begin
Member::BuildType.parse_type(@type_expr, null: @null)
rescue StandardError => err
raise ArgumentError, "Couldn't build type for Argument #{@owner.name}.#{name}: #{err.class.name}: #{err.message}", err.backtrace
end
# Use the setter method to get validations
self.type = parsed_type
end
end
def statically_coercible?
return @statically_coercible if defined?(@statically_coercible)
requires_parent_object = @prepare.is_a?(String) || @prepare.is_a?(Symbol) || @own_validators
@statically_coercible = !requires_parent_object
end
def freeze
statically_coercible?
super
end
# Apply the {prepare} configuration to `value`, using methods from `obj`.
# Used by the runtime.
# @api private
def prepare_value(obj, value, context: nil)
if type.unwrap.kind.input_object?
value = recursively_prepare_input_object(value, type, context)
end
Schema::Validator.validate!(validators, obj, context, value)
if @prepare.nil?
value
elsif @prepare.is_a?(String) || @prepare.is_a?(Symbol)
if obj.nil?
# The problem here is, we _used to_ prepare while building variables.
# But now we don't have the runtime object there.
#
# This will have to be called later, when the runtime object _is_ available.
value
elsif obj.respond_to?(@prepare)
obj.public_send(@prepare, value)
elsif owner.respond_to?(@prepare)
owner.public_send(@prepare, value, context || obj.context)
else
raise "Invalid prepare for #{@owner.name}.name: #{@prepare.inspect}. "\
"Could not find prepare method #{@prepare} on #{obj.class} or #{owner}."
end
elsif @prepare.respond_to?(:call)
@prepare.call(value, context || obj.context)
else
raise "Invalid prepare for #{@owner.name}.name: #{@prepare.inspect}"
end
end
# @api private
def coerce_into_values(parent_object, values, context, argument_values)
arg_name = graphql_name
arg_key = keyword
default_used = false
if values.key?(arg_name)
value = values[arg_name]
elsif values.key?(arg_key)
value = values[arg_key]
elsif default_value?
value = default_value
default_used = true
else
# no value at all
owner.validate_directive_argument(self, nil)
return
end
if value.nil? && replace_null_with_default?
value = default_value
default_used = true
end
loaded_value = nil
coerced_value = begin
type.coerce_input(value, context)
rescue StandardError => err
context.schema.handle_or_reraise(context, err)
end
# If this isn't lazy, then the block returns eagerly and assigns the result here
# If it _is_ lazy, then we write the lazy to the hash, then update it later
argument_values[arg_key] = context.query.after_lazy(coerced_value) do |resolved_coerced_value|
owner.validate_directive_argument(self, resolved_coerced_value)
prepared_value = begin
prepare_value(parent_object, resolved_coerced_value, context: context)
rescue StandardError => err
context.schema.handle_or_reraise(context, err)
end
if loads && !from_resolver?
loaded_value = begin
load_and_authorize_value(owner, prepared_value, context)
rescue StandardError => err
context.schema.handle_or_reraise(context, err)
end
end
maybe_loaded_value = loaded_value || prepared_value
context.query.after_lazy(maybe_loaded_value) do |resolved_loaded_value|
# TODO code smell to access such a deeply-nested constant in a distant module
argument_values[arg_key] = GraphQL::Execution::Interpreter::ArgumentValue.new(
value: resolved_loaded_value,
original_value: resolved_coerced_value,
definition: self,
default_used: default_used,
)
end
end
end
def load_and_authorize_value(load_method_owner, coerced_value, context)
if coerced_value.nil?
return nil
end
arg_load_method = "load_#{keyword}"
if load_method_owner.respond_to?(arg_load_method)
custom_loaded_value = if load_method_owner.is_a?(Class)
load_method_owner.public_send(arg_load_method, coerced_value, context)
else
load_method_owner.public_send(arg_load_method, coerced_value)
end
context.query.after_lazy(custom_loaded_value) do |custom_value|
if loads
if type.list?
loaded_values = []
context.dataloader.run_isolated do
custom_value.each_with_index.map { |custom_val, idx|
id = coerced_value[idx]
context.dataloader.append_job do
loaded_values[idx] = load_method_owner.authorize_application_object(self, id, context, custom_val)
end
}
end
context.schema.after_any_lazies(loaded_values, &:itself)
else
load_method_owner.authorize_application_object(self, coerced_value, context, custom_loaded_value)
end
else
custom_value
end
end
elsif loads
if type.list?
loaded_values = []
# We want to run these list items all together,
# but we also need to wait for the result so we can return it :S
context.dataloader.run_isolated do
coerced_value.each_with_index { |val, idx|
context.dataloader.append_job do
loaded_values[idx] = load_method_owner.load_and_authorize_application_object(self, val, context)
end
}
end
context.schema.after_any_lazies(loaded_values, &:itself)
else
load_method_owner.load_and_authorize_application_object(self, coerced_value, context)
end
else
coerced_value
end
end
# @api private
def validate_default_value
return unless default_value?
coerced_default_value = begin
# This is weird, but we should accept single-item default values for list-type arguments.
# If we used `coerce_isolated_input` below, it would do this for us, but it's not really
# the right thing here because we expect default values in application format (Ruby values)
# not GraphQL format (scalar values).
#
# But I don't think Schema::List#coerce_result should apply wrapping to single-item lists.
prepped_default_value = if default_value.nil?
nil
elsif (type.kind.list? || (type.kind.non_null? && type.of_type.list?)) && !default_value.respond_to?(:map)
[default_value]
else
default_value
end
type.coerce_isolated_result(prepped_default_value) unless prepped_default_value.nil?
rescue GraphQL::Schema::Enum::UnresolvedValueError
# It raises this, which is helpful at runtime, but not here...
default_value
end
res = type.valid_isolated_input?(coerced_default_value)
if !res
raise InvalidDefaultValueError.new(self)
end
end
class InvalidDefaultValueError < GraphQL::Error
def initialize(argument)
message = "`#{argument.path}` has an invalid default value: `#{argument.default_value.inspect}` isn't accepted by `#{argument.type.to_type_signature}`; update the default value or the argument type."
super(message)
end
end
private
def recursively_prepare_input_object(value, type, context)
if type.non_null?
type = type.of_type
end
if type.list? && !value.nil?
inner_type = type.of_type
value.map { |v| recursively_prepare_input_object(v, inner_type, context) }
elsif value.is_a?(GraphQL::Schema::InputObject)
value.validate_for(context)
value.prepare
else
value
end
end
def validate_input_type(input_type)
if input_type.is_a?(String) || input_type.is_a?(GraphQL::Schema::LateBoundType)
# Do nothing; assume this will be validated later
elsif input_type.kind.non_null? || input_type.kind.list?
validate_input_type(input_type.unwrap)
elsif !input_type.kind.input?
raise ArgumentError, "Invalid input type for #{path}: #{input_type.graphql_name}. Must be scalar, enum, or input object, not #{input_type.kind.name}."
else
# It's an input type, we're OK
end
end
def validate_deprecated_or_optional(null:, deprecation_reason:)
if deprecation_reason && !null
raise ArgumentError, "Required arguments cannot be deprecated: #{path}."
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/scalar.rb | lib/graphql/schema/scalar.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Scalar < GraphQL::Schema::Member
extend GraphQL::Schema::Member::ValidatesInput
class << self
def coerce_input(val, ctx)
val
end
def coerce_result(val, ctx)
val
end
def kind
GraphQL::TypeKinds::SCALAR
end
def specified_by_url(new_url = nil)
if new_url
directive(GraphQL::Schema::Directive::SpecifiedBy, url: new_url)
elsif (directive = directives.find { |dir| dir.graphql_name == "specifiedBy" })
directive.arguments[:url] # rubocop:disable Development/ContextIsPassedCop
elsif superclass.respond_to?(:specified_by_url)
superclass.specified_by_url
else
nil
end
end
def default_scalar(is_default = nil)
if !is_default.nil?
@default_scalar = is_default
end
@default_scalar
end
def default_scalar?
@default_scalar ||= false
end
def validate_non_null_input(value, ctx, max_errors: nil)
coerced_result = begin
coerce_input(value, ctx)
rescue GraphQL::CoercionError => err
err
rescue StandardError => err
ctx.query.handle_or_reraise(err)
end
if coerced_result.nil?
Query::InputValidationResult.from_problem("Could not coerce value #{GraphQL::Language.serialize(value)} to #{graphql_name}")
elsif coerced_result.is_a?(GraphQL::CoercionError)
Query::InputValidationResult.from_problem(coerced_result.message, message: coerced_result.message, extensions: coerced_result.extensions)
else
nil
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/type_expression.rb | lib/graphql/schema/type_expression.rb | # frozen_string_literal: true
module GraphQL
class Schema
# @api private
module TypeExpression
# Fetch a type from a type map by its AST specification.
# Return `nil` if not found.
# @param type_owner [#type] A thing for looking up types by name
# @param ast_node [GraphQL::Language::Nodes::AbstractNode]
# @return [Class, GraphQL::Schema::NonNull, GraphQL::Schema:List]
def self.build_type(type_owner, ast_node)
case ast_node
when GraphQL::Language::Nodes::TypeName
type_owner.type(ast_node.name) # rubocop:disable Development/ContextIsPassedCop -- this is a `context` or `warden`, it's already query-aware
when GraphQL::Language::Nodes::NonNullType
ast_inner_type = ast_node.of_type
inner_type = build_type(type_owner, ast_inner_type)
wrap_type(inner_type, :to_non_null_type)
when GraphQL::Language::Nodes::ListType
ast_inner_type = ast_node.of_type
inner_type = build_type(type_owner, ast_inner_type)
wrap_type(inner_type, :to_list_type)
else
raise "Invariant: unexpected type from ast: #{ast_node.inspect}"
end
end
class << self
private
def wrap_type(type, wrapper_method)
if type.nil?
nil
elsif wrapper_method == :to_list_type || wrapper_method == :to_non_null_type
type.public_send(wrapper_method)
else
raise ArgumentError, "Unexpected wrapper method: #{wrapper_method.inspect}"
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/base_64_encoder.rb | lib/graphql/schema/base_64_encoder.rb | # frozen_string_literal: true
require "base64"
module GraphQL
class Schema
# @api private
module Base64Encoder
def self.encode(unencoded_text, nonce: false)
Base64.urlsafe_encode64(unencoded_text, padding: false)
end
def self.decode(encoded_text, nonce: false)
# urlsafe_decode64 is for forward compatibility
Base64.urlsafe_decode64(encoded_text)
rescue ArgumentError
raise GraphQL::ExecutionError, "Invalid input: #{encoded_text.inspect}"
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/always_visible.rb | lib/graphql/schema/always_visible.rb | # frozen_string_literal: true
module GraphQL
class Schema
module AlwaysVisible
def self.use(schema, **opts)
schema.use(GraphQL::Schema::Visibility, profiles: { nil => {} })
schema.extend(self)
end
def visible?(_member, _context)
true
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/build_from_definition/resolve_map.rb | lib/graphql/schema/build_from_definition/resolve_map.rb | # frozen_string_literal: true
require "graphql/schema/build_from_definition/resolve_map/default_resolve"
module GraphQL
class Schema
module BuildFromDefinition
# Wrap a user-provided hash of resolution behavior for easy access at runtime.
#
# Coerce scalar values by:
# - Checking for a function in the map like `{ Date: { coerce_input: ->(val, ctx) { ... }, coerce_result: ->(val, ctx) { ... } } }`
# - Falling back to a passthrough
#
# Interface/union resolution can be provided as a `resolve_type:` key.
#
# @api private
class ResolveMap
module NullScalarCoerce
def self.call(val, _ctx)
val
end
end
def initialize(user_resolve_hash)
@resolve_hash = Hash.new do |h, k|
# For each type name, provide a new hash if one wasn't given:
h[k] = Hash.new do |h2, k2|
if k2 == "coerce_input" || k2 == "coerce_result"
# This isn't an object field, it's a scalar coerce function.
# Use a passthrough
NullScalarCoerce
else
# For each field, provide a resolver that will
# make runtime checks & replace itself
h2[k2] = DefaultResolve.new(h2, k2)
end
end
end
@user_resolve_hash = user_resolve_hash
# User-provided resolve functions take priority over the default:
@user_resolve_hash.each do |type_name, fields|
type_name_s = type_name.to_s
case fields
when Hash
fields.each do |field_name, resolve_fn|
@resolve_hash[type_name_s][field_name.to_s] = resolve_fn
end
when Proc
# for example, "resolve_type"
@resolve_hash[type_name_s] = fields
else
raise ArgumentError, "Unexpected resolve hash value for #{type_name.inspect}: #{fields.inspect} (#{fields.class})"
end
end
# Check the normalized hash, not the user input:
if @resolve_hash.key?("resolve_type")
define_singleton_method :resolve_type do |type, obj, ctx|
@resolve_hash.fetch("resolve_type").call(type, obj, ctx)
end
end
end
def call(type, field, obj, args, ctx)
resolver = @resolve_hash[type.graphql_name][field.graphql_name]
resolver.call(obj, args, ctx)
end
def coerce_input(type, value, ctx)
@resolve_hash[type.graphql_name]["coerce_input"].call(value, ctx)
end
def coerce_result(type, value, ctx)
@resolve_hash[type.graphql_name]["coerce_result"].call(value, ctx)
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/build_from_definition/resolve_map/default_resolve.rb | lib/graphql/schema/build_from_definition/resolve_map/default_resolve.rb | # frozen_string_literal: true
module GraphQL
class Schema
module BuildFromDefinition
class ResolveMap
class DefaultResolve
def initialize(field_map, field_name)
@field_map = field_map
@field_name = field_name
end
# Make some runtime checks about
# how `obj` implements the `field_name`.
#
# Create a new resolve function according to that implementation, then:
# - update `field_map` with this implementation
# - call the implementation now (to satisfy this field execution)
#
# If `obj` doesn't implement `field_name`, raise an error.
def call(obj, args, ctx)
method_name = @field_name
if !obj.respond_to?(method_name)
raise KeyError, "Can't resolve field #{method_name} on #{obj.inspect}"
else
method_arity = obj.method(method_name).arity
resolver = case method_arity
when 0, -1
# -1 Handles method_missing, eg openstruct
->(o, a, c) { o.public_send(method_name) }
when 1
->(o, a, c) { o.public_send(method_name, a) }
when 2
->(o, a, c) { o.public_send(method_name, a, c) }
else
raise "Unexpected resolve arity: #{method_arity}. Must be 0, 1, 2"
end
# Call the resolver directly next time
@field_map[method_name] = resolver
# Call through this time
resolver.call(obj, args, ctx)
end
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/member/has_deprecation_reason.rb | lib/graphql/schema/member/has_deprecation_reason.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Member
module HasDeprecationReason
# @return [String, nil] Explains why this member was deprecated (if present, this will be marked deprecated in introspection)
attr_reader :deprecation_reason
# Set the deprecation reason for this member, or remove it by assigning `nil`
# @param text [String, nil]
def deprecation_reason=(text)
@deprecation_reason = text
if text.nil?
remove_directive(GraphQL::Schema::Directive::Deprecated)
else
# This removes a previously-attached directive, if there is one:
directive(GraphQL::Schema::Directive::Deprecated, reason: text)
end
end
def self.extended(child_class)
super
child_class.extend(ClassMethods)
end
module ClassMethods
def deprecation_reason(new_reason = NOT_CONFIGURED)
if NOT_CONFIGURED.equal?(new_reason)
super()
else
self.deprecation_reason = new_reason
end
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/member/relay_shortcuts.rb | lib/graphql/schema/member/relay_shortcuts.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Member
module RelayShortcuts
def edge_type_class(new_edge_type_class = nil)
if new_edge_type_class
initialize_relay_metadata
@edge_type_class = new_edge_type_class
else
# Don't call `ancestor.edge_type_class`
# because we don't want a fallback from any ancestors --
# only apply the fallback if _no_ ancestor has a configured value!
for ancestor in self.ancestors
if ancestor.respond_to?(:configured_edge_type_class, true) && (etc = ancestor.configured_edge_type_class)
return etc
end
end
Types::Relay::BaseEdge
end
end
def connection_type_class(new_connection_type_class = nil)
if new_connection_type_class
initialize_relay_metadata
@connection_type_class = new_connection_type_class
else
# Don't call `ancestor.connection_type_class`
# because we don't want a fallback from any ancestors --
# only apply the fallback if _no_ ancestor has a configured value!
for ancestor in self.ancestors
if ancestor.respond_to?(:configured_connection_type_class, true) && (ctc = ancestor.configured_connection_type_class)
return ctc
end
end
Types::Relay::BaseConnection
end
end
def edge_type
initialize_relay_metadata
@edge_type ||= begin
edge_name = self.graphql_name + "Edge"
node_type_class = self
Class.new(edge_type_class) do
graphql_name(edge_name)
node_type(node_type_class)
end
end
end
def connection_type
initialize_relay_metadata
@connection_type ||= begin
conn_name = self.graphql_name + "Connection"
edge_type_class = self.edge_type
Class.new(connection_type_class) do
graphql_name(conn_name)
edge_type(edge_type_class)
end
end
end
protected
def configured_connection_type_class
@connection_type_class
end
def configured_edge_type_class
@edge_type_class
end
attr_writer :edge_type, :connection_type, :connection_type_class, :edge_type_class
private
# If one of these values is accessed, initialize all the instance variables to retain
# a consistent object shape.
def initialize_relay_metadata
if !defined?(@connection_type)
@connection_type = nil
@edge_type = nil
@connection_type_class = nil
@edge_type_class = nil
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/member/has_interfaces.rb | lib/graphql/schema/member/has_interfaces.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Member
module HasInterfaces
def implements(*new_interfaces, **options)
new_memberships = []
new_interfaces.each do |int|
if int.is_a?(Module)
unless int.include?(GraphQL::Schema::Interface) && !int.is_a?(Class)
raise "#{int.respond_to?(:graphql_name) ? "#{int.graphql_name} (#{int})" : int.inspect} cannot be implemented since it's not a GraphQL Interface. Use `include` for plain Ruby modules."
end
new_memberships << int.type_membership_class.new(int, self, **options)
# Include the methods here,
# `.fields` will use the inheritance chain
# to find inherited fields
include(int)
# If this interface has interfaces of its own, add those, too
int.interfaces.each do |next_interface|
implements(next_interface)
end
elsif int.is_a?(String) || int.is_a?(GraphQL::Schema::LateBoundType)
if !options.empty?
raise ArgumentError, "`implements(...)` doesn't support options with late-loaded types yet. Remove #{options} and open an issue to request this feature."
end
new_memberships << int
else
raise ArgumentError, "Unexpected interface definition (expected module): #{int} (#{int.class})"
end
end
# Remove any String or late-bound interfaces which are being replaced
own_interface_type_memberships.reject! { |old_i_m|
if !(old_i_m.respond_to?(:abstract_type) && old_i_m.abstract_type.is_a?(Module))
old_int_type = old_i_m.respond_to?(:abstract_type) ? old_i_m.abstract_type : old_i_m
old_name = Schema::Member::BuildType.to_type_name(old_int_type)
new_memberships.any? { |new_i_m|
new_int_type = new_i_m.respond_to?(:abstract_type) ? new_i_m.abstract_type : new_i_m
new_name = Schema::Member::BuildType.to_type_name(new_int_type)
new_name == old_name
}
end
}
own_interface_type_memberships.concat(new_memberships)
end
def own_interface_type_memberships
@own_interface_type_memberships ||= []
end
def interface_type_memberships
own_interface_type_memberships
end
module ClassConfigured
# This combination of extended -> inherited -> extended
# means that the base class (`Schema::Object`) *won't*
# have the superclass-related code in `InheritedInterfaces`,
# but child classes of `Schema::Object` will have it.
# That way, we don't need a `superclass.respond_to?(...)` check.
def inherited(child_class)
super
child_class.extend(InheritedInterfaces)
end
module InheritedInterfaces
def interfaces(context = GraphQL::Query::NullContext.instance)
visible_interfaces = super
inherited_interfaces = superclass.interfaces(context)
if !visible_interfaces.empty?
if !inherited_interfaces.empty?
visible_interfaces.concat(inherited_interfaces)
visible_interfaces.uniq!
end
visible_interfaces
elsif !inherited_interfaces.empty?
inherited_interfaces
else
EmptyObjects::EMPTY_ARRAY
end
end
def interface_type_memberships
own_tms = super
inherited_tms = superclass.interface_type_memberships
if inherited_tms.size > 0
own_tms + inherited_tms
else
own_tms
end
end
end
end
# param context [Query::Context] If omitted, skip filtering.
def interfaces(context = GraphQL::Query::NullContext.instance)
warden = Warden.from_context(context)
visible_interfaces = nil
own_interface_type_memberships.each do |type_membership|
case type_membership
when Schema::TypeMembership
if warden.visible_type_membership?(type_membership, context)
visible_interfaces ||= []
visible_interfaces << type_membership.abstract_type
end
when String, Schema::LateBoundType
# During initialization, `type_memberships` can hold late-bound types
visible_interfaces ||= []
visible_interfaces << type_membership
else
raise "Invariant: Unexpected type_membership #{type_membership.class}: #{type_membership.inspect}"
end
end
if visible_interfaces
visible_interfaces.uniq!
visible_interfaces
else
EmptyObjects::EMPTY_ARRAY
end
end
private
def self.extended(child_class)
child_class.extend(ClassConfigured)
end
def inherited(subclass)
super
subclass.class_exec do
@own_interface_type_memberships ||= nil
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/member/has_validators.rb | lib/graphql/schema/member/has_validators.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Member
module HasValidators
include GraphQL::EmptyObjects
# Build {GraphQL::Schema::Validator}s based on the given configuration
# and use them for this schema member
# @param validation_config [Hash{Symbol => Hash}]
# @return [void]
def validates(validation_config)
new_validators = GraphQL::Schema::Validator.from_config(self, validation_config)
@own_validators ||= []
@own_validators.concat(new_validators)
nil
end
# @return [Array<GraphQL::Schema::Validator>]
def validators
@own_validators || EMPTY_ARRAY
end
module ClassConfigured
def inherited(child_cls)
super
child_cls.extend(ClassValidators)
end
module ClassValidators
include GraphQL::EmptyObjects
def validators
inherited_validators = superclass.validators
if !inherited_validators.empty?
if @own_validators.nil?
inherited_validators
else
inherited_validators + @own_validators
end
elsif @own_validators.nil?
EMPTY_ARRAY
else
@own_validators
end
end
end
end
def self.extended(child_cls)
super
child_cls.extend(ClassConfigured)
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/member/scoped.rb | lib/graphql/schema/member/scoped.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Member
module Scoped
# This is called when a field has `scope: true`.
# The field's return type class receives this call.
#
# By default, it's a no-op. Override it to scope your objects.
#
# @param items [Object] Some list-like object (eg, Array, ActiveRecord::Relation)
# @param context [GraphQL::Query::Context]
# @return [Object] Another list-like object, scoped to the current context
def scope_items(items, context)
items
end
def reauthorize_scoped_objects(new_value = nil)
if new_value.nil?
if @reauthorize_scoped_objects != nil
@reauthorize_scoped_objects
else
find_inherited_value(:reauthorize_scoped_objects, true)
end
else
@reauthorize_scoped_objects = new_value
end
end
def inherited(subclass)
super
subclass.class_exec do
@reauthorize_scoped_objects = nil
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/member/has_path.rb | lib/graphql/schema/member/has_path.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Member
module HasPath
# @return [String] A description of this member's place in the GraphQL schema
def path
path_str = if self.respond_to?(:graphql_name)
self.graphql_name
elsif self.class.respond_to?(:graphql_name)
# Instances of resolvers
self.class.graphql_name
end
if self.respond_to?(:owner) && owner.respond_to?(:path)
path_str = "#{owner.path}.#{path_str}"
end
path_str
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/member/has_ast_node.rb | lib/graphql/schema/member/has_ast_node.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Member
module HasAstNode
def self.extended(child_cls)
super
child_cls.ast_node = nil
end
def inherited(child_cls)
super
child_cls.ast_node = nil
end
# If this schema was parsed from a `.graphql` file (or other SDL),
# this is the AST node that defined this part of the schema.
def ast_node(new_ast_node = nil)
if new_ast_node
@ast_node = new_ast_node
elsif defined?(@ast_node)
@ast_node
else
nil
end
end
attr_writer :ast_node
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/member/has_unresolved_type_error.rb | lib/graphql/schema/member/has_unresolved_type_error.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Member
# Set up a type-specific error to make debugging & bug tracker integration better
module HasUnresolvedTypeError
private
def add_unresolved_type_error(child_class)
if child_class.name # Don't set this for anonymous classes
child_class.const_set(:UnresolvedTypeError, Class.new(GraphQL::UnresolvedTypeError))
else
child_class.const_set(:UnresolvedTypeError, UnresolvedTypeError)
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/member/has_fields.rb | lib/graphql/schema/member/has_fields.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Member
# Shared code for Objects, Interfaces, Mutations, Subscriptions
module HasFields
# Add a field to this object or interface with the given definition
# @see {GraphQL::Schema::Field#initialize} for method signature
# @return [GraphQL::Schema::Field]
def field(*args, **kwargs, &block)
field_defn = field_class.from_options(*args, owner: self, **kwargs, &block)
add_field(field_defn)
field_defn
end
# A list of Ruby keywords.
#
# @api private
RUBY_KEYWORDS = [:class, :module, :def, :undef, :begin, :rescue, :ensure, :end, :if, :unless, :then, :elsif, :else, :case, :when, :while, :until, :for, :break, :next, :redo, :retry, :in, :do, :return, :yield, :super, :self, :nil, :true, :false, :and, :or, :not, :alias, :defined?, :BEGIN, :END, :__LINE__, :__FILE__]
# A list of GraphQL-Ruby keywords.
#
# @api private
GRAPHQL_RUBY_KEYWORDS = [:context, :object, :raw_value]
# A list of field names that we should advise users to pick a different
# resolve method name.
#
# @api private
CONFLICT_FIELD_NAMES = Set.new(GRAPHQL_RUBY_KEYWORDS + RUBY_KEYWORDS + Object.instance_methods)
# Register this field with the class, overriding a previous one if needed.
# @param field_defn [GraphQL::Schema::Field]
# @return [void]
def add_field(field_defn, method_conflict_warning: field_defn.method_conflict_warning?)
# Check that `field_defn.original_name` equals `resolver_method` and `method_sym` --
# that shows that no override value was given manually.
if method_conflict_warning &&
CONFLICT_FIELD_NAMES.include?(field_defn.resolver_method) &&
field_defn.original_name == field_defn.resolver_method &&
field_defn.original_name == field_defn.method_sym &&
field_defn.hash_key == NOT_CONFIGURED &&
field_defn.dig_keys.nil?
warn(conflict_field_name_warning(field_defn))
end
prev_defn = own_fields[field_defn.name]
case prev_defn
when nil
own_fields[field_defn.name] = field_defn
when Array
prev_defn << field_defn
when GraphQL::Schema::Field
own_fields[field_defn.name] = [prev_defn, field_defn]
else
raise "Invariant: unexpected previous field definition for #{field_defn.name.inspect}: #{prev_defn.inspect}"
end
nil
end
# @return [Class] The class to initialize when adding fields to this kind of schema member
def field_class(new_field_class = nil)
if new_field_class
@field_class = new_field_class
elsif defined?(@field_class) && @field_class
@field_class
else
find_inherited_value(:field_class, GraphQL::Schema::Field)
end
end
def global_id_field(field_name, **kwargs)
type = self
field field_name, "ID", **kwargs, null: false
define_method(field_name) do
context.schema.id_from_object(object, type, context)
end
end
# @param new_has_no_fields [Boolean] Call with `true` to make this Object type ignore the requirement to have any defined fields.
# @return [void]
def has_no_fields(new_has_no_fields)
@has_no_fields = new_has_no_fields
nil
end
# @return [Boolean] `true` if `has_no_fields(true)` was configued
def has_no_fields?
@has_no_fields
end
# @return [Hash<String => GraphQL::Schema::Field, Array<GraphQL::Schema::Field>>] Fields defined on this class _specifically_, not parent classes
def own_fields
@own_fields ||= {}
end
def all_field_definitions
all_fields = {}
ancestors.reverse_each do |ancestor|
if ancestor.respond_to?(:own_fields)
all_fields.merge!(ancestor.own_fields)
end
end
all_fields = all_fields.values
all_fields.flatten!
all_fields
end
module InterfaceMethods
def get_field(field_name, context = GraphQL::Query::NullContext.instance)
warden = Warden.from_context(context)
skip_visible = context.respond_to?(:types) && context.types.is_a?(GraphQL::Schema::Visibility::Profile)
for ancestor in ancestors
if ancestor.respond_to?(:own_fields) &&
(f_entry = ancestor.own_fields[field_name]) &&
(skip_visible || (f_entry = Warden.visible_entry?(:visible_field?, f_entry, context, warden)))
return f_entry
end
end
nil
end
# @return [Hash<String => GraphQL::Schema::Field>] Fields on this object, keyed by name, including inherited fields
def fields(context = GraphQL::Query::NullContext.instance)
warden = Warden.from_context(context)
# Local overrides take precedence over inherited fields
visible_fields = {}
for ancestor in ancestors
if ancestor.respond_to?(:own_fields)
ancestor.own_fields.each do |field_name, fields_entry|
# Choose the most local definition that passes `.visible?` --
# stop checking for fields by name once one has been found.
if !visible_fields.key?(field_name) && (f = Warden.visible_entry?(:visible_field?, fields_entry, context, warden))
visible_fields[field_name] = f.ensure_loaded
end
end
end
end
visible_fields
end
end
module ObjectMethods
def get_field(field_name, context = GraphQL::Query::NullContext.instance)
# Objects need to check that the interface implementation is visible, too
warden = Warden.from_context(context)
ancs = ancestors
skip_visible = context.respond_to?(:types) && context.types.is_a?(GraphQL::Schema::Visibility::Profile)
i = 0
while (ancestor = ancs[i])
if ancestor.respond_to?(:own_fields) &&
visible_interface_implementation?(ancestor, context, warden) &&
(f_entry = ancestor.own_fields[field_name]) &&
(skip_visible || (f_entry = Warden.visible_entry?(:visible_field?, f_entry, context, warden)))
return (skip_visible ? f_entry : f_entry.ensure_loaded)
end
i += 1
end
nil
end
# @return [Hash<String => GraphQL::Schema::Field>] Fields on this object, keyed by name, including inherited fields
def fields(context = GraphQL::Query::NullContext.instance)
# Objects need to check that the interface implementation is visible, too
warden = Warden.from_context(context)
# Local overrides take precedence over inherited fields
visible_fields = {}
had_any_fields_at_all = false
for ancestor in ancestors
if ancestor.respond_to?(:own_fields) && visible_interface_implementation?(ancestor, context, warden)
ancestor.own_fields.each do |field_name, fields_entry|
had_any_fields_at_all = true
# Choose the most local definition that passes `.visible?` --
# stop checking for fields by name once one has been found.
if !visible_fields.key?(field_name) && (f = Warden.visible_entry?(:visible_field?, fields_entry, context, warden))
visible_fields[field_name] = f.ensure_loaded
end
end
end
end
if !had_any_fields_at_all && !has_no_fields?
warn(GraphQL::Schema::Object::FieldsAreRequiredError.new(self).message + "\n\nThis will raise an error in a future GraphQL-Ruby version.")
end
visible_fields
end
end
def self.included(child_class)
# Included in an interface definition methods module
child_class.include(InterfaceMethods)
super
end
def self.extended(child_class)
child_class.extend(ObjectMethods)
super
end
private
def inherited(subclass)
super
subclass.class_exec do
@own_fields ||= nil
@field_class ||= nil
@has_no_fields ||= false
end
end
# If `type` is an interface, and `self` has a type membership for `type`, then make sure it's visible.
def visible_interface_implementation?(type, context, warden)
if type.respond_to?(:kind) && type.kind.interface?
implements_this_interface = false
implementation_is_visible = false
warden.interface_type_memberships(self, context).each do |tm|
if tm.abstract_type == type
implements_this_interface ||= true
if warden.visible_type_membership?(tm, context)
implementation_is_visible = true
break
end
end
end
# It's possible this interface came by way of `include` in another interface which this
# object type _does_ implement, and that's ok
implements_this_interface ? implementation_is_visible : true
else
# If there's no implementation, then we're looking at Ruby-style inheritance instead
true
end
end
# @param [GraphQL::Schema::Field]
# @return [String] A warning to give when this field definition might conflict with a built-in method
def conflict_field_name_warning(field_defn)
"#{self.graphql_name}'s `field :#{field_defn.original_name}` conflicts with a built-in method, use `resolver_method:` to pick a different resolver method for this field (for example, `resolver_method: :resolve_#{field_defn.resolver_method}` and `def resolve_#{field_defn.resolver_method}`). Or use `method_conflict_warning: false` to suppress this warning."
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/member/build_type.rb | lib/graphql/schema/member/build_type.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Member
# @api private
module BuildType
LIST_TYPE_ERROR = "Use an array of [T] or [T, null: true] for list types; other arrays are not supported"
module_function
# @param type_expr [String, Class, GraphQL::BaseType]
# @return [GraphQL::BaseType]
def parse_type(type_expr, null:)
list_type = false
return_type = case type_expr
when String
case type_expr
when "String"
GraphQL::Types::String
when "Int", "Integer"
GraphQL::Types::Int
when "Float"
GraphQL::Types::Float
when "Boolean"
GraphQL::Types::Boolean
when "ID"
GraphQL::Types::ID
when /\A\[.*\]\Z/
list_type = true
# List members are required by default
parse_type(type_expr[1..-2], null: false)
when /.*!\Z/
null = false
parse_type(type_expr[0..-2], null: true)
else
maybe_type = constantize(type_expr)
case maybe_type
when Module
# This is a way to check that it's the right kind of module:
if maybe_type.respond_to?(:kind)
maybe_type
else
raise ArgumentError, "Unexpected class/module found for GraphQL type: #{type_expr} (must be type definition class/module)"
end
end
end
when GraphQL::Schema::LateBoundType
type_expr
when Array
case type_expr.length
when 1
list_type = true
# List members are required by default
parse_type(type_expr.first, null: false)
when 2
inner_type, nullable_option = type_expr
if nullable_option.keys != [:null] || (nullable_option[:null] != true && nullable_option[:null] != false)
raise ArgumentError, LIST_TYPE_ERROR
end
list_type = true
parse_type(inner_type, null: nullable_option[:null])
else
raise ArgumentError, LIST_TYPE_ERROR
end
when GraphQL::Schema::NonNull, GraphQL::Schema::List
type_expr
when Module
# This is a way to check that it's the right kind of module:
if type_expr.respond_to?(:kind)
type_expr
else
# Eg `String` => GraphQL::Types::String
parse_type(type_expr.name, null: true)
end
when Proc
parse_type(type_expr.call, null: true)
when false
raise ArgumentError, "Received `false` instead of a type, maybe a `!` should be replaced with `null: true` (for fields) or `required: true` (for arguments)"
end
if return_type.nil?
raise "Unexpected type input: #{type_expr.inspect} (#{type_expr.class})"
end
# Apply list_type first, that way the
# .to_non_null_type applies to the list type, not the inner type
if list_type
return_type = return_type.to_list_type
end
if !null
return_type = return_type.to_non_null_type
end
return_type
end
def to_type_name(something)
case something
when GraphQL::Schema::LateBoundType
something.unwrap.name
when Array
to_type_name(something.first)
when Module
if something.respond_to?(:graphql_name)
something.graphql_name
else
to_type_name(something.name)
end
when String
if something.include?("]") ||
something.include?("[") ||
something.include?("!") ||
something.include?("::")
something.gsub(/\]\[\!/, "").split("::").last
else
something
end
when GraphQL::Schema::NonNull, GraphQL::Schema::List
to_type_name(something.unwrap)
else
raise "Unhandled to_type_name input: #{something} (#{something.class})"
end
end
def camelize(string)
return string if string == '_'
return string unless string.include?("_")
camelized = string.split('_').each(&:capitalize!).join
camelized[0] = camelized[0].downcase
if string.start_with?("_")
match_data = string.match(/\A(_+)/)
camelized = "#{match_data[0]}#{camelized}"
end
camelized
end
# Resolves constant from string (based on Rails `ActiveSupport::Inflector.constantize`)
def constantize(string)
names = string.split('::')
# Trigger a built-in NameError exception including the ill-formed constant in the message.
Object.const_get(string) if names.empty?
# Remove the first blank element in case of '::ClassName' notation.
names.shift if names.size > 1 && names.first.empty?
names.inject(Object) do |constant, name|
if constant == Object
constant.const_get(name)
else
candidate = constant.const_get(name)
next candidate if constant.const_defined?(name, false)
next candidate unless Object.const_defined?(name)
# Go down the ancestors to check if it is owned directly. The check
# stops when we reach Object or the end of ancestors tree.
constant = constant.ancestors.inject do |const, ancestor|
break const if ancestor == Object
break ancestor if ancestor.const_defined?(name, false)
const
end
# Owner is in Object, so raise.
constant.const_get(name, false)
end
end
end
def underscore(string)
if string.match?(/\A[a-z_]+\Z/)
return string
end
string2 = string.dup
string2.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2') # URLDecoder -> URL_Decoder
string2.gsub!(/([a-z\d])([A-Z])/,'\1_\2') # someThing -> some_Thing
string2.downcase!
string2
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/member/has_dataloader.rb | lib/graphql/schema/member/has_dataloader.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Member
# @api public
# Shared methods for working with {Dataloader} inside GraphQL runtime objects.
module HasDataloader
# @return [GraphQL::Dataloader] The dataloader for the currently-running query
def dataloader
context.dataloader
end
# A shortcut method for loading a key from a source.
# Identical to `dataloader.with(source_class, *source_args).load(load_key)`
# @param source_class [Class<GraphQL::Dataloader::Source>]
# @param source_args [Array<Object>] Any extra parameters defined in `source_class`'s `initialize` method
# @param load_key [Object] The key to look up using `def fetch`
def dataload(source_class, *source_args, load_key)
dataloader.with(source_class, *source_args).load(load_key)
end
# Find an object with ActiveRecord via {Dataloader::ActiveRecordSource}.
# @param model [Class<ActiveRecord::Base>]
# @param find_by_value [Object] Usually an `id`, might be another value if `find_by:` is also provided
# @param find_by [Symbol, String] A column name to look the record up by. (Defaults to the model's primary key.)
# @return [ActiveRecord::Base, nil]
# @example Finding a record by ID
# dataload_record(Post, 5) # Like `Post.find(5)`, but dataloaded
# @example Finding a record by another attribute
# dataload_record(User, "matz", find_by: :handle) # Like `User.find_by(handle: "matz")`, but dataloaded
def dataload_record(model, find_by_value, find_by: nil)
source = if find_by
dataloader.with(Dataloader::ActiveRecordSource, model, find_by: find_by)
else
dataloader.with(Dataloader::ActiveRecordSource, model)
end
source.load(find_by_value)
end
# Look up an associated record using a Rails association (via {Dataloader::ActiveRecordAssociationSource})
# @param association_name [Symbol] A `belongs_to` or `has_one` association. (If a `has_many` association is named here, it will be selected without pagination.)
# @param record [ActiveRecord::Base] The object that the association belongs to.
# @param scope [ActiveRecord::Relation] A scope to look up the associated record in
# @return [ActiveRecord::Base, nil] The associated record, if there is one
# @example Looking up a belongs_to on the current object
# dataload_association(:parent) # Equivalent to `object.parent`, but dataloaded
# @example Looking up an associated record on some other object
# dataload_association(comment, :post) # Equivalent to `comment.post`, but dataloaded
def dataload_association(record = object, association_name, scope: nil)
source = if scope
dataloader.with(Dataloader::ActiveRecordAssociationSource, association_name, scope)
else
dataloader.with(Dataloader::ActiveRecordAssociationSource, association_name)
end
source.load(record)
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/member/base_dsl_methods.rb | lib/graphql/schema/member/base_dsl_methods.rb | # frozen_string_literal: true
require "graphql/schema/find_inherited_value"
module GraphQL
class Schema
class Member
# DSL methods shared by lots of things in the GraphQL Schema.
# @api private
# @see Classes that extend this, eg {GraphQL::Schema::Object}
module BaseDSLMethods
include GraphQL::Schema::FindInheritedValue
# Call this with a new name to override the default name for this schema member; OR
# call it without an argument to get the name of this schema member
#
# The default name is implemented in default_graphql_name
# @param new_name [String]
# @return [String]
def graphql_name(new_name = nil)
if new_name
GraphQL::NameValidator.validate!(new_name)
@graphql_name = new_name
else
@graphql_name ||= default_graphql_name
end
end
# Just a convenience method to point out that people should use graphql_name instead
def name(new_name = nil)
return super() if new_name.nil?
fail(
"The new name override method is `graphql_name`, not `name`. Usage: "\
"graphql_name \"#{new_name}\""
)
end
# Call this method to provide a new description; OR
# call it without an argument to get the description
# @param new_description [String]
# @return [String]
def description(new_description = nil)
if new_description
@description = new_description
elsif defined?(@description)
@description
else
@description = nil
end
end
# Call this method to provide a new comment; OR
# call it without an argument to get the comment
# @param new_comment [String]
# @return [String, nil]
def comment(new_comment = NOT_CONFIGURED)
if !NOT_CONFIGURED.equal?(new_comment)
@comment = new_comment
elsif defined?(@comment)
@comment
else
nil
end
end
# This pushes some configurations _down_ the inheritance tree,
# in order to prevent repetitive lookups at runtime.
module ConfigurationExtension
def inherited(child_class)
child_class.introspection(introspection)
child_class.description(description)
child_class.comment(nil)
child_class.default_graphql_name = nil
if defined?(@graphql_name) && @graphql_name && (self.name.nil? || graphql_name != default_graphql_name)
child_class.graphql_name(graphql_name)
else
child_class.graphql_name = nil
end
super
end
end
# @return [Boolean] If true, this object is part of the introspection system
def introspection(new_introspection = nil)
if !new_introspection.nil?
@introspection = new_introspection
elsif defined?(@introspection)
@introspection
else
false
end
end
def introspection?
!!@introspection
end
# The mutation this type was derived from, if it was derived from a mutation
# @return [Class]
def mutation(mutation_class = nil)
if mutation_class
@mutation = mutation_class
elsif defined?(@mutation)
@mutation
else
nil
end
end
alias :unwrap :itself
# Creates the default name for a schema member.
# The default name is the Ruby constant name,
# without any namespaces and with any `-Type` suffix removed
def default_graphql_name
@default_graphql_name ||= begin
raise GraphQL::RequiredImplementationMissingError, 'Anonymous class should declare a `graphql_name`' if name.nil?
g_name = -name.split("::").last
g_name.end_with?("Type") ? g_name.sub(/Type\Z/, "") : g_name
end
end
def visible?(context)
true
end
def authorized?(object, context)
true
end
def default_relay
false
end
protected
attr_writer :default_graphql_name, :graphql_name
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/member/has_arguments.rb | lib/graphql/schema/member/has_arguments.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Member
module HasArguments
def self.included(cls)
cls.extend(ArgumentClassAccessor)
cls.include(ArgumentObjectLoader)
end
def self.extended(cls)
cls.extend(ArgumentClassAccessor)
cls.include(ArgumentObjectLoader)
cls.extend(ClassConfigured)
end
# @see {GraphQL::Schema::Argument#initialize} for parameters
# @return [GraphQL::Schema::Argument] An instance of {argument_class}, created from `*args`
def argument(*args, **kwargs, &block)
kwargs[:owner] = self
loads = kwargs[:loads]
if loads
name = args[0]
name_as_string = name.to_s
inferred_arg_name = case name_as_string
when /_id$/
name_as_string.sub(/_id$/, "").to_sym
when /_ids$/
name_as_string.sub(/_ids$/, "")
.sub(/([^s])$/, "\\1s")
.to_sym
else
name
end
kwargs[:as] ||= inferred_arg_name
end
arg_defn = self.argument_class.new(*args, **kwargs, &block)
add_argument(arg_defn)
arg_defn
end
# Register this argument with the class.
# @param arg_defn [GraphQL::Schema::Argument]
# @return [GraphQL::Schema::Argument]
def add_argument(arg_defn)
@own_arguments ||= {}
prev_defn = @own_arguments[arg_defn.name]
case prev_defn
when nil
@own_arguments[arg_defn.name] = arg_defn
when Array
prev_defn << arg_defn
when GraphQL::Schema::Argument
@own_arguments[arg_defn.name] = [prev_defn, arg_defn]
else
raise "Invariant: unexpected `@own_arguments[#{arg_defn.name.inspect}]`: #{prev_defn.inspect}"
end
arg_defn
end
def remove_argument(arg_defn)
prev_defn = @own_arguments[arg_defn.name]
case prev_defn
when nil
# done
when Array
prev_defn.delete(arg_defn)
when GraphQL::Schema::Argument
@own_arguments.delete(arg_defn.name)
else
raise "Invariant: unexpected `@own_arguments[#{arg_defn.name.inspect}]`: #{prev_defn.inspect}"
end
nil
end
# @return [Hash<String => GraphQL::Schema::Argument] Arguments defined on this thing, keyed by name. Includes inherited definitions
def arguments(context = GraphQL::Query::NullContext.instance, _require_defined_arguments = nil)
if !own_arguments.empty?
own_arguments_that_apply = {}
own_arguments.each do |name, args_entry|
if (visible_defn = Warden.visible_entry?(:visible_argument?, args_entry, context))
own_arguments_that_apply[visible_defn.graphql_name] = visible_defn
end
end
end
# might be nil if there are actually no arguments
own_arguments_that_apply || own_arguments
end
def any_arguments?
!own_arguments.empty?
end
module ClassConfigured
def inherited(child_class)
super
child_class.extend(InheritedArguments)
end
module InheritedArguments
def arguments(context = GraphQL::Query::NullContext.instance, require_defined_arguments = true)
own_arguments = super(context, require_defined_arguments)
inherited_arguments = superclass.arguments(context, false)
if !own_arguments.empty?
if !inherited_arguments.empty?
# Local definitions override inherited ones
inherited_arguments.merge(own_arguments)
else
own_arguments
end
else
inherited_arguments
end
end
def any_arguments?
super || superclass.any_arguments?
end
def all_argument_definitions
all_defns = {}
ancestors.reverse_each do |ancestor|
if ancestor.respond_to?(:own_arguments)
all_defns.merge!(ancestor.own_arguments)
end
end
all_defns = all_defns.values
all_defns.flatten!
all_defns
end
def get_argument(argument_name, context = GraphQL::Query::NullContext.instance)
warden = Warden.from_context(context)
skip_visible = context.respond_to?(:types) && context.types.is_a?(GraphQL::Schema::Visibility::Profile)
for ancestor in ancestors
if ancestor.respond_to?(:own_arguments) &&
(a = ancestor.own_arguments[argument_name]) &&
(skip_visible || (a = Warden.visible_entry?(:visible_argument?, a, context, warden)))
return a
end
end
nil
end
end
end
module FieldConfigured
def arguments(context = GraphQL::Query::NullContext.instance, _require_defined_arguments = nil)
own_arguments = super
if @resolver_class
inherited_arguments = @resolver_class.field_arguments(context)
if !own_arguments.empty?
if !inherited_arguments.empty?
inherited_arguments.merge(own_arguments)
else
own_arguments
end
else
inherited_arguments
end
else
own_arguments
end
end
def any_arguments?
super || (@resolver_class && @resolver_class.any_field_arguments?)
end
def all_argument_definitions
if @resolver_class
all_defns = {}
@resolver_class.all_field_argument_definitions.each do |arg_defn|
key = arg_defn.graphql_name
case (current_value = all_defns[key])
when nil
all_defns[key] = arg_defn
when Array
current_value << arg_defn
when GraphQL::Schema::Argument
all_defns[key] = [current_value, arg_defn]
else
raise "Invariant: Unexpected argument definition, #{current_value.class}: #{current_value.inspect}"
end
end
all_defns.merge!(own_arguments)
all_defns = all_defns.values
all_defns.flatten!
all_defns
else
super
end
end
end
def all_argument_definitions
if !own_arguments.empty?
all_defns = own_arguments.values
all_defns.flatten!
all_defns
else
EmptyObjects::EMPTY_ARRAY
end
end
# @return [GraphQL::Schema::Argument, nil] Argument defined on this thing, fetched by name.
def get_argument(argument_name, context = GraphQL::Query::NullContext.instance)
warden = Warden.from_context(context)
if (arg_config = own_arguments[argument_name]) && ((context.respond_to?(:types) && context.types.is_a?(GraphQL::Schema::Visibility::Profile)) || (visible_arg = Warden.visible_entry?(:visible_argument?, arg_config, context, warden)))
visible_arg || arg_config
elsif defined?(@resolver_class) && @resolver_class
@resolver_class.get_field_argument(argument_name, context)
else
nil
end
end
# @param new_arg_class [Class] A class to use for building argument definitions
def argument_class(new_arg_class = nil)
self.class.argument_class(new_arg_class)
end
# @api private
# If given a block, it will eventually yield the loaded args to the block.
#
# If no block is given, it will immediately dataload (but might return a Lazy).
#
# @param values [Hash<String, Object>]
# @param context [GraphQL::Query::Context]
# @yield [Interpreter::Arguments, Execution::Lazy<Interpreter::Arguments>]
# @return [Interpreter::Arguments, Execution::Lazy<Interpreter::Arguments>]
def coerce_arguments(parent_object, values, context, &block)
# Cache this hash to avoid re-merging it
arg_defns = context.types.arguments(self)
total_args_count = arg_defns.size
finished_args = nil
prepare_finished_args = -> {
if total_args_count == 0
finished_args = GraphQL::Execution::Interpreter::Arguments::EMPTY
if block_given?
block.call(finished_args)
end
else
argument_values = {}
resolved_args_count = 0
raised_error = false
arg_defns.each do |arg_defn|
context.dataloader.append_job do
begin
arg_defn.coerce_into_values(parent_object, values, context, argument_values)
rescue GraphQL::ExecutionError, GraphQL::UnauthorizedError => err
raised_error = true
finished_args = err
if block_given?
block.call(finished_args)
end
end
resolved_args_count += 1
if resolved_args_count == total_args_count && !raised_error
finished_args = context.schema.after_any_lazies(argument_values.values) {
GraphQL::Execution::Interpreter::Arguments.new(
argument_values: argument_values,
)
}
if block_given?
block.call(finished_args)
end
end
end
end
end
}
if block_given?
prepare_finished_args.call
nil
else
# This API returns eagerly, gotta run it now
context.dataloader.run_isolated(&prepare_finished_args)
finished_args
end
end
# Usually, this is validated statically by RequiredArgumentsArePresent,
# but not for directives.
# TODO apply static validations on schema definitions?
def validate_directive_argument(arg_defn, value)
# this is only implemented on directives.
nil
end
module HasDirectiveArguments
def validate_directive_argument(arg_defn, value)
if value.nil? && arg_defn.type.non_null?
raise ArgumentError, "#{arg_defn.path} is required, but no value was given"
end
end
end
def arguments_statically_coercible?
if defined?(@arguments_statically_coercible) && !@arguments_statically_coercible.nil?
@arguments_statically_coercible
else
@arguments_statically_coercible = all_argument_definitions.all?(&:statically_coercible?)
end
end
module ArgumentClassAccessor
def argument_class(new_arg_class = nil)
if new_arg_class
@argument_class = new_arg_class
elsif defined?(@argument_class) && @argument_class
@argument_class
else
superclass.respond_to?(:argument_class) ? superclass.argument_class : GraphQL::Schema::Argument
end
end
end
module ArgumentObjectLoader
# Look up the corresponding object for a provided ID.
# By default, it uses Relay-style {Schema.object_from_id},
# override this to find objects another way.
#
# @param type [Class, Module] A GraphQL type definition
# @param id [String] A client-provided to look up
# @param context [GraphQL::Query::Context] the current context
def object_from_id(type, id, context)
context.schema.object_from_id(id, context)
end
def load_application_object(argument, id, context)
# See if any object can be found for this ID
if id.nil?
return nil
end
object_from_id(argument.loads, id, context)
end
def load_and_authorize_application_object(argument, id, context)
loaded_application_object = load_application_object(argument, id, context)
authorize_application_object(argument, id, context, loaded_application_object)
end
def authorize_application_object(argument, id, context, loaded_application_object)
context.query.after_lazy(loaded_application_object) do |application_object|
if application_object.nil?
err = GraphQL::LoadApplicationObjectFailedError.new(context: context, argument: argument, id: id, object: application_object)
application_object = load_application_object_failed(err)
end
# Double-check that the located object is actually of this type
# (Don't want to allow arbitrary access to objects this way)
if application_object.nil?
nil
else
arg_loads_type = argument.loads
maybe_lazy_resolve_type = context.schema.resolve_type(arg_loads_type, application_object, context)
context.query.after_lazy(maybe_lazy_resolve_type) do |resolve_type_result|
if resolve_type_result.is_a?(Array) && resolve_type_result.size == 2
application_object_type, application_object = resolve_type_result
else
application_object_type = resolve_type_result
# application_object is already assigned
end
passes_possible_types_check = if context.types.loadable?(arg_loads_type, context)
if arg_loads_type.kind.abstract?
# This union/interface is used in `loads:` but not otherwise visible to this query
context.types.loadable_possible_types(arg_loads_type, context).include?(application_object_type)
else
true
end
else
context.types.possible_types(arg_loads_type).include?(application_object_type)
end
if !passes_possible_types_check
err = GraphQL::LoadApplicationObjectFailedError.new(context: context, argument: argument, id: id, object: application_object)
application_object = load_application_object_failed(err)
end
if application_object.nil?
nil
else
# This object was loaded successfully
# and resolved to the right type,
# now apply the `.authorized?` class method if there is one
context.query.after_lazy(application_object_type.authorized?(application_object, context)) do |authed|
if authed
application_object
else
err = GraphQL::UnauthorizedError.new(
object: application_object,
type: application_object_type,
context: context,
)
if self.respond_to?(:unauthorized_object)
err.set_backtrace(caller)
unauthorized_object(err)
else
raise err
end
end
end
end
end
end
end
end
# Called when an argument's `loads:` configuration fails to fetch an application object.
# By default, this method raises the given error, but you can override it to handle failures differently.
#
# @param err [GraphQL::LoadApplicationObjectFailedError] The error that occurred
# @return [Object, nil] If a value is returned, it will be used instead of the failed load
# @api public
def load_application_object_failed(err)
raise err
end
end
NO_ARGUMENTS = GraphQL::EmptyObjects::EMPTY_HASH
def own_arguments
@own_arguments || NO_ARGUMENTS
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/member/has_directives.rb | lib/graphql/schema/member/has_directives.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Member
module HasDirectives
def self.extended(child_cls)
super
child_cls.module_exec { self.own_directives = nil }
end
def inherited(child_cls)
super
child_cls.own_directives = nil
end
# Create an instance of `dir_class` for `self`, using `options`.
#
# It removes a previously-attached instance of `dir_class`, if there is one.
#
# @return [void]
def directive(dir_class, **options)
@own_directives ||= []
HasDirectives.add_directive(self, @own_directives, dir_class, options)
nil
end
# Remove an attached instance of `dir_class`, if there is one
# @param dir_class [Class<GraphQL::Schema::Directive>]
# @return [viod]
def remove_directive(dir_class)
HasDirectives.remove_directive(@own_directives, dir_class)
nil
end
def directives
HasDirectives.get_directives(self, @own_directives, :directives)
end
class << self
def add_directive(schema_member, directives, directive_class, directive_options)
remove_directive(directives, directive_class) unless directive_class.repeatable?
directives << directive_class.new(schema_member, **directive_options)
end
def remove_directive(directives, directive_class)
directives && directives.reject! { |d| d.is_a?(directive_class) }
end
def get_directives(schema_member, directives, directives_method)
case schema_member
when Class
inherited_directives = if schema_member.superclass.respond_to?(directives_method)
get_directives(schema_member.superclass, schema_member.superclass.public_send(directives_method), directives_method)
else
GraphQL::EmptyObjects::EMPTY_ARRAY
end
if !inherited_directives.empty? && directives
dirs = []
merge_directives(dirs, inherited_directives)
merge_directives(dirs, directives)
dirs
elsif directives
directives
elsif !inherited_directives.empty?
inherited_directives
else
GraphQL::EmptyObjects::EMPTY_ARRAY
end
when Module
dirs = nil
schema_member.ancestors.reverse_each do |ancestor|
if ancestor.respond_to?(:own_directives) &&
!(anc_dirs = ancestor.own_directives).empty?
dirs ||= []
merge_directives(dirs, anc_dirs)
end
end
if directives
dirs ||= []
merge_directives(dirs, directives)
end
dirs || GraphQL::EmptyObjects::EMPTY_ARRAY
when HasDirectives
directives || GraphQL::EmptyObjects::EMPTY_ARRAY
else
raise "Invariant: how could #{schema_member} not be a Class, Module, or instance of HasDirectives?"
end
end
private
# Modify `target` by adding items from `dirs` such that:
# - Any name conflict is overridden by the incoming member of `dirs`
# - Any other member of `dirs` is appended
# @param target [Array<GraphQL::Schema::Directive>]
# @param dirs [Array<GraphQL::Schema::Directive>]
# @return [void]
def merge_directives(target, dirs)
dirs.each do |dir|
if (idx = target.find_index { |d| d.graphql_name == dir.graphql_name })
target.slice!(idx)
target.insert(idx, dir)
else
target << dir
end
end
nil
end
end
protected
attr_accessor :own_directives
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/member/validates_input.rb | lib/graphql/schema/member/validates_input.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Member
module ValidatesInput
def valid_input?(val, ctx)
validate_input(val, ctx).valid?
end
def validate_input(val, ctx, max_errors: nil)
if val.nil?
Query::InputValidationResult::VALID
else
validate_non_null_input(val, ctx, max_errors: max_errors) || Query::InputValidationResult::VALID
end
end
def valid_isolated_input?(v)
valid_input?(v, GraphQL::Query::NullContext.instance)
end
def coerce_isolated_input(v)
coerce_input(v, GraphQL::Query::NullContext.instance)
end
def coerce_isolated_result(v)
coerce_result(v, GraphQL::Query::NullContext.instance)
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/member/graphql_type_names.rb | lib/graphql/schema/member/graphql_type_names.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Member
# These constants are interpreted as GraphQL types when defining fields or arguments
#
# @example
# field :is_draft, Boolean, null: false
# field :id, ID, null: false
# field :score, Int, null: false
#
# @api private
module GraphQLTypeNames
Boolean = "Boolean"
ID = "ID"
Int = "Int"
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/member/type_system_helpers.rb | lib/graphql/schema/member/type_system_helpers.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Member
module TypeSystemHelpers
def initialize(...)
super
@to_non_null_type ||= nil
@to_list_type ||= nil
end
# @return [Schema::NonNull] Make a non-null-type representation of this type
def to_non_null_type
@to_non_null_type || begin
t = GraphQL::Schema::NonNull.new(self)
if frozen?
t
else
@to_non_null_type = t
end
end
end
# @return [Schema::List] Make a list-type representation of this type
def to_list_type
@to_list_type || begin
t = GraphQL::Schema::List.new(self)
if frozen?
t
else
@to_list_type = t
end
end
end
# @return [Boolean] true if this is a non-nullable type. A nullable list of non-nullables is considered nullable.
def non_null?
false
end
# @return [Boolean] true if this is a list type. A non-nullable list is considered a list.
def list?
false
end
def to_type_signature
graphql_name
end
# @return [GraphQL::TypeKinds::TypeKind]
def kind
raise GraphQL::RequiredImplementationMissingError, "No `.kind` defined for #{self}"
end
private
def inherited(subclass)
subclass.class_exec do
@to_non_null_type ||= nil
@to_list_type ||= nil
end
super
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/resolver/has_payload_type.rb | lib/graphql/schema/resolver/has_payload_type.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Resolver
# Adds `field(...)` helper to resolvers so that they can
# generate payload types.
#
# Or, an already-defined one can be attached with `payload_type(...)`.
module HasPayloadType
# Call this method to get the derived return type of the mutation,
# or use it as a configuration method to assign a return type
# instead of generating one.
# @param new_payload_type [Class, nil] If a type definition class is provided, it will be used as the return type of the mutation field
# @return [Class] The object type which this mutation returns.
def payload_type(new_payload_type = nil)
if new_payload_type
@payload_type = new_payload_type
end
@payload_type ||= generate_payload_type
end
def type(new_type = nil, null: nil)
if new_type
payload_type(new_type)
if !null.nil?
self.null(null)
end
else
super()
end
end
alias :type_expr :payload_type
def field_class(new_class = nil)
if new_class
@field_class = new_class
elsif defined?(@field_class) && @field_class
@field_class
else
find_inherited_value(:field_class, GraphQL::Schema::Field)
end
end
# An object class to use for deriving return types
# @param new_class [Class, nil] Defaults to {GraphQL::Schema::Object}
# @return [Class]
def object_class(new_class = nil)
if new_class
if defined?(@payload_type)
raise "Can't configure `object_class(...)` after the payload type has already been initialized. Move this configuration higher up the class definition."
end
@object_class = new_class
else
@object_class || find_inherited_value(:object_class, GraphQL::Schema::Object)
end
end
NO_INTERFACES = [].freeze
def field(*args, **kwargs, &block)
pt = payload_type # make sure it's initialized with any inherited fields
field_defn = super
# Remove any inherited fields to avoid false conflicts at runtime
prev_fields = pt.own_fields[field_defn.graphql_name]
case prev_fields
when GraphQL::Schema::Field
if prev_fields.owner != self
pt.own_fields.delete(field_defn.graphql_name)
end
when Array
prev_fields.reject! { |f| f.owner != self }
if prev_fields.empty?
pt.own_fields.delete(field_defn.graphql_name)
end
end
pt.add_field(field_defn, method_conflict_warning: false)
field_defn
end
private
# Build a subclass of {.object_class} based on `self`.
# This value will be cached as `{.payload_type}`.
# Override this hook to customize return type generation.
def generate_payload_type
resolver_name = graphql_name
resolver_fields = all_field_definitions
pt = Class.new(object_class)
pt.graphql_name("#{resolver_name}Payload")
pt.description("Autogenerated return type of #{resolver_name}.")
resolver_fields.each do |f|
# Reattach the already-defined field here
# (The field's `.owner` will still point to the mutation, not the object type, I think)
# Don't re-warn about a method conflict. Since this type is generated, it should be fixed in the resolver instead.
pt.add_field(f, method_conflict_warning: false)
end
pt
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/visibility/visit.rb | lib/graphql/schema/visibility/visit.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Visibility
class Visit
def initialize(schema, &visit_block)
@schema = schema
@late_bound_types = nil
@unvisited_types = nil
# These accumulate between calls to prevent re-visiting the same types
@visited_types = Set.new.compare_by_identity
@visited_directives = Set.new.compare_by_identity
@visit_block = visit_block
end
def entry_point_types
ept = [
@schema.query,
@schema.mutation,
@schema.subscription,
*@schema.introspection_system.types.values,
*@schema.orphan_types,
]
ept.compact!
ept
end
def entry_point_directives
@schema.directives.values
end
def visit_each(types: entry_point_types, directives: entry_point_directives)
@unvisited_types && raise("Can't re-enter `visit_each` on this Visit (another visit is already in progress)")
@unvisited_types = types
@late_bound_types = []
directives_to_visit = directives
while !@unvisited_types.empty? || !@late_bound_types.empty?
while (type = @unvisited_types.pop)
if @visited_types.add?(type) && @visit_block.call(type)
directives_to_visit.concat(type.directives)
case type.kind.name
when "OBJECT", "INTERFACE"
type.interface_type_memberships.each do |itm|
append_unvisited_type(type, itm.abstract_type)
end
if type.kind.interface?
type.orphan_types.each do |orphan_type|
append_unvisited_type(type, orphan_type)
end
end
type.all_field_definitions.each do |field|
field.ensure_loaded
if @visit_block.call(field)
directives_to_visit.concat(field.directives)
append_unvisited_type(type, field.type.unwrap)
field.all_argument_definitions.each do |argument|
if @visit_block.call(argument)
directives_to_visit.concat(argument.directives)
append_unvisited_type(field, argument.type.unwrap)
end
end
end
end
when "INPUT_OBJECT"
type.all_argument_definitions.each do |argument|
if @visit_block.call(argument)
directives_to_visit.concat(argument.directives)
append_unvisited_type(type, argument.type.unwrap)
end
end
when "UNION"
type.type_memberships.each do |tm|
append_unvisited_type(type, tm.object_type)
end
when "ENUM"
type.all_enum_value_definitions.each do |val|
if @visit_block.call(val)
directives_to_visit.concat(val.directives)
end
end
when "SCALAR"
# pass -- nothing else to visit
else
raise "Invariant: unhandled type kind: #{type.kind.inspect}"
end
end
end
directives_to_visit.each do |dir|
dir_class = dir.is_a?(Class) ? dir : dir.class
if @visited_directives.add?(dir_class) && @visit_block.call(dir_class)
dir_class.all_argument_definitions.each do |arg_defn|
if @visit_block.call(arg_defn)
directives_to_visit.concat(arg_defn.directives)
append_unvisited_type(dir_class, arg_defn.type.unwrap)
end
end
end
end
missed_late_types_streak = 0
while (owner, late_type = @late_bound_types.shift)
if (late_type.is_a?(String) && (type = Member::BuildType.constantize(type))) ||
(late_type.is_a?(LateBoundType) && (type = @visited_types.find { |t| t.graphql_name == late_type.graphql_name }))
missed_late_types_streak = 0 # might succeed next round
update_type_owner(owner, type)
append_unvisited_type(owner, type)
else
# Didn't find it -- keep trying
missed_late_types_streak += 1
@late_bound_types << [owner, late_type]
if missed_late_types_streak == @late_bound_types.size
raise UnresolvedLateBoundTypeError.new(type: late_type)
end
end
end
end
@unvisited_types = nil
nil
end
private
def append_unvisited_type(owner, type)
if type.is_a?(LateBoundType) || type.is_a?(String)
@late_bound_types << [owner, type]
else
@unvisited_types << type
end
end
def update_type_owner(owner, type)
case owner
when Module
if owner.kind.union?
owner.assign_type_membership_object_type(type)
elsif type.kind.interface?
new_interfaces = []
owner.interfaces.each do |int_t|
if int_t.is_a?(String) && int_t == type.graphql_name
new_interfaces << type
elsif int_t.is_a?(LateBoundType) && int_t.graphql_name == type.graphql_name
new_interfaces << type
else
# Don't re-add proper interface definitions,
# they were probably already added, maybe with options.
end
end
owner.implements(*new_interfaces)
new_interfaces.each do |int|
pt = @possible_types[int] ||= []
if !pt.include?(owner) && owner.is_a?(Class)
pt << owner
end
int.interfaces.each do |indirect_int|
if indirect_int.is_a?(LateBoundType) && (indirect_int_type = get_type(indirect_int.graphql_name)) # rubocop:disable Development/ContextIsPassedCop
update_type_owner(owner, indirect_int_type)
end
end
end
end
when GraphQL::Schema::Argument, GraphQL::Schema::Field
orig_type = owner.type
# Apply list/non-null wrapper as needed
if orig_type.respond_to?(:of_type)
transforms = []
while (orig_type.respond_to?(:of_type))
if orig_type.kind.non_null?
transforms << :to_non_null_type
elsif orig_type.kind.list?
transforms << :to_list_type
else
raise "Invariant: :of_type isn't non-null or list"
end
orig_type = orig_type.of_type
end
transforms.reverse_each { |t| type = type.public_send(t) }
end
owner.type = type
else
raise "Unexpected update: #{owner.inspect} #{type.inspect}"
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/visibility/profile.rb | lib/graphql/schema/visibility/profile.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Visibility
# This class filters the types, fields, arguments, enum values, and directives in a schema
# based on the given `context`.
#
# It's like {Warden}, but has some differences:
#
# - It doesn't use {Schema}'s top-level caches (eg {Schema.references_to}, {Schema.possible_types}, {Schema.types})
# - It doesn't hide Interface or Union types when all their possible types are hidden. (Instead, those types should implement `.visible?` to hide in that case.)
# - It checks `.visible?` on root introspection types
# - It can be used to cache profiles by name for re-use across queries
class Profile
# @return [Schema::Visibility::Profile]
def self.from_context(ctx, schema)
if ctx.respond_to?(:types) && (types = ctx.types).is_a?(self)
types
else
schema.visibility.profile_for(ctx)
end
end
def self.null_profile(context:, schema:)
profile = self.new(name: "NullProfile", context: context, schema: schema)
profile.instance_variable_set(:@cached_visible, Hash.new { |k, v| k[v] = true }.compare_by_identity)
profile
end
# @return [Symbol, nil]
attr_reader :name
def freeze
@cached_visible.default_proc = nil
@cached_visible_fields.default_proc = nil
@cached_visible_fields.each do |type, fields|
fields.default_proc = nil
end
@cached_visible_arguments.default_proc = nil
@cached_visible_arguments.each do |type, fields|
fields.default_proc = nil
end
@cached_parent_fields.default_proc = nil
@cached_parent_fields.each do |type, fields|
fields.default_proc = nil
end
@cached_parent_arguments.default_proc = nil
@cached_parent_arguments.each do |type, args|
args.default_proc = nil
end
@cached_possible_types.default_proc = nil
@cached_enum_values.default_proc = nil
@cached_fields.default_proc = nil
@cached_arguments.default_proc = nil
@loadable_possible_types.default_proc = nil
super
end
def initialize(name: nil, context:, schema:, visibility:)
@name = name
@context = context
@schema = schema
@visibility = visibility
@all_types = {}
@all_types_loaded = false
@unvisited_types = []
@all_directives = nil
@cached_visible = Hash.new { |h, member| h[member] = @schema.visible?(member, @context) }.compare_by_identity
@cached_visible_fields = Hash.new { |h, owner|
h[owner] = Hash.new do |h2, field|
h2[field] = visible_field_for(owner, field)
end.compare_by_identity
}.compare_by_identity
@cached_visible_arguments = Hash.new do |h, owner|
h[owner] = Hash.new do |h2, arg|
h2[arg] = if @cached_visible[arg] && (arg_type = arg.type.unwrap) && @cached_visible[arg_type]
case owner
when GraphQL::Schema::Field
@cached_visible_fields[owner.owner][owner]
when Class
@cached_visible[owner]
else
raise "Unexpected argument owner for `#{arg.path}`: #{owner.inspect}"
end
else
false
end
end.compare_by_identity
end.compare_by_identity
@cached_parent_fields = Hash.new do |h, type|
h[type] = Hash.new do |h2, field_name|
h2[field_name] = type.get_field(field_name, @context)
end
end.compare_by_identity
@cached_parent_arguments = Hash.new do |h, arg_owner|
h[arg_owner] = Hash.new do |h2, arg_name|
h2[arg_name] = arg_owner.get_argument(arg_name, @context)
end
end.compare_by_identity
@cached_possible_types = Hash.new { |h, type| h[type] = possible_types_for(type) }.compare_by_identity
@cached_enum_values = Hash.new do |h, enum_t|
values = non_duplicate_items(enum_t.enum_values(@context), @cached_visible)
if values.size == 0
raise GraphQL::Schema::Enum::MissingValuesError.new(enum_t)
end
h[enum_t] = values
end.compare_by_identity
@cached_fields = Hash.new do |h, owner|
h[owner] = non_duplicate_items(owner.all_field_definitions.each(&:ensure_loaded), @cached_visible_fields[owner])
end.compare_by_identity
@cached_arguments = Hash.new do |h, owner|
h[owner] = non_duplicate_items(owner.all_argument_definitions, @cached_visible_arguments[owner])
end.compare_by_identity
@loadable_possible_types = Hash.new { |h, union_type| h[union_type] = union_type.possible_types }.compare_by_identity
end
def field_on_visible_interface?(field, owner)
ints = owner.interface_type_memberships.map(&:abstract_type)
field_name = field.graphql_name
filtered_ints = interfaces(owner)
any_interface_has_field = false
any_interface_has_visible_field = false
ints.each do |int_t|
if (_int_f_defn = @cached_parent_fields[int_t][field_name])
any_interface_has_field = true
if filtered_ints.include?(int_t) # TODO cycles, or maybe not necessary since previously checked? && @cached_visible_fields[owner][field]
any_interface_has_visible_field = true
break
end
end
end
if any_interface_has_field
any_interface_has_visible_field
else
true
end
end
def type(type_name)
t = @visibility.get_type(type_name) # rubocop:disable Development/ContextIsPassedCop
if t
if t.is_a?(Array)
vis_t = nil
t.each do |t_defn|
if @cached_visible[t_defn] && referenced?(t_defn)
if vis_t.nil?
vis_t = t_defn
else
raise_duplicate_definition(vis_t, t_defn)
end
end
end
vis_t
else
if t && @cached_visible[t] && referenced?(t)
t
else
nil
end
end
end
end
def field(owner, field_name)
f = if owner.kind.fields? && (field = @cached_parent_fields[owner][field_name])
field
elsif owner == query_root && (entry_point_field = @schema.introspection_system.entry_point(name: field_name))
entry_point_field
elsif (dynamic_field = @schema.introspection_system.dynamic_field(name: field_name))
dynamic_field
else
nil
end
if f.is_a?(Array)
visible_f = nil
f.each do |f_defn|
if @cached_visible_fields[owner][f_defn]
if visible_f.nil?
visible_f = f_defn
else
raise_duplicate_definition(visible_f, f_defn)
end
end
end
visible_f&.ensure_loaded
elsif f && @cached_visible_fields[owner][f.ensure_loaded]
f
else
nil
end
end
def fields(owner)
@cached_fields[owner]
end
def arguments(owner)
@cached_arguments[owner]
end
def argument(owner, arg_name)
arg = @cached_parent_arguments[owner][arg_name]
if arg.is_a?(Array)
visible_arg = nil
arg.each do |arg_defn|
if @cached_visible_arguments[owner][arg_defn]
if visible_arg.nil?
visible_arg = arg_defn
else
raise_duplicate_definition(visible_arg, arg_defn)
end
end
end
visible_arg
else
if arg && @cached_visible_arguments[owner][arg]
arg
else
nil
end
end
end
def possible_types(type)
@cached_possible_types[type]
end
def interfaces(obj_or_int_type)
ints = obj_or_int_type.interface_type_memberships
.select { |itm| @cached_visible[itm] && @cached_visible[itm.abstract_type] }
.map!(&:abstract_type)
ints.uniq! # Remove any duplicate interfaces implemented via other interfaces
ints
end
def query_root
((t = @schema.query) && @cached_visible[t]) ? t : nil
end
def mutation_root
((t = @schema.mutation) && @cached_visible[t]) ? t : nil
end
def subscription_root
((t = @schema.subscription) && @cached_visible[t]) ? t : nil
end
def all_types
load_all_types
@all_types.values
end
def all_types_h
load_all_types
@all_types
end
def enum_values(owner)
@cached_enum_values[owner]
end
def directive_exists?(dir_name)
directives.any? { |d| d.graphql_name == dir_name }
end
def directives
@all_directives ||= @visibility.all_directives.select { |dir|
@cached_visible[dir] && @visibility.all_references[dir].any? { |ref| ref == true || (@cached_visible[ref] && referenced?(ref)) }
}
end
def loadable?(t, _ctx)
@cached_visible[t] && !referenced?(t)
end
def loadable_possible_types(t, _ctx)
@loadable_possible_types[t]
end
def loaded_types
@all_types.values
end
def reachable_type?(type_name)
load_all_types
!!@all_types[type_name]
end
def visible_enum_value?(enum_value, _ctx = nil)
@cached_visible[enum_value]
end
def preload
load_all_types
@all_types.each do |type_name, type_defn|
if type_defn.kind.fields?
fields(type_defn).each do |f|
field(type_defn, f.graphql_name)
arguments(f).each do |arg|
argument(f, arg.graphql_name)
end
end
@schema.introspection_system.dynamic_fields.each do |f|
field(type_defn, f.graphql_name)
end
elsif type_defn.kind.input_object?
arguments(type_defn).each do |arg|
argument(type_defn, arg.graphql_name)
end
elsif type_defn.kind.enum?
enum_values(type_defn)
end
# Lots more to do here
end
@schema.introspection_system.entry_points.each do |f|
arguments(f).each do |arg|
argument(f, arg.graphql_name)
end
field(@schema.query, f.graphql_name)
end
@schema.introspection_system.dynamic_fields.each do |f|
arguments(f).each do |arg|
argument(f, arg.graphql_name)
end
end
end
private
def non_duplicate_items(definitions, visibility_cache)
non_dups = []
names = Set.new
definitions.each do |defn|
if visibility_cache[defn]
if !names.add?(defn.graphql_name)
dup_defn = non_dups.find { |d| d.graphql_name == defn.graphql_name }
raise_duplicate_definition(dup_defn, defn)
end
non_dups << defn
end
end
non_dups
end
def raise_duplicate_definition(first_defn, second_defn)
raise DuplicateNamesError.new(duplicated_name: first_defn.path, duplicated_definition_1: first_defn.inspect, duplicated_definition_2: second_defn.inspect)
end
def load_all_types
return if @all_types_loaded
@all_types_loaded = true
visit = Visibility::Visit.new(@schema) do |member|
if member.is_a?(Module) && member.respond_to?(:kind)
if @cached_visible[member] && referenced?(member)
type_name = member.graphql_name
if (prev_t = @all_types[type_name]) && !prev_t.equal?(member)
raise_duplicate_definition(member, prev_t)
end
@all_types[type_name] = member
true
else
false
end
else
@cached_visible[member]
end
end
visit.visit_each
@all_types.delete_if { |type_name, type_defn| !referenced?(type_defn) }
nil
end
def referenced?(type_defn)
@visibility.all_references[type_defn].any? do |ref|
case ref
when GraphQL::Schema::Argument
@cached_visible_arguments[ref.owner][ref]
when GraphQL::Schema::Field
@cached_visible_fields[ref.owner][ref]
when Module
@cached_visible[ref]
when true
true
end
end
end
def possible_types_for(type)
case type.kind.name
when "INTERFACE"
pts = []
@visibility.all_interface_type_memberships[type].each do |impl_type, type_memberships|
if impl_type.kind.object? && referenced?(impl_type) && @cached_visible[impl_type]
if type_memberships.any? { |itm| @cached_visible[itm] }
pts << impl_type
end
end
end
pts
when "UNION"
pts = []
type.type_memberships.each { |tm|
if @cached_visible[tm] &&
(ot = tm.object_type) &&
@cached_visible[ot] &&
referenced?(ot)
pts << ot
end
}
pts
when "OBJECT"
if @cached_visible[type]
[type]
else
EmptyObjects::EMPTY_ARRAY
end
else
GraphQL::EmptyObjects::EMPTY_ARRAY
end
end
def visible_field_for(owner, field)
@cached_visible[field] &&
(ret_type = field.type.unwrap) &&
@cached_visible[ret_type] &&
(owner == field.owner || (!owner.kind.object?) || field_on_visible_interface?(field, owner))
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/visibility/migration.rb | lib/graphql/schema/visibility/migration.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Visibility
# You can use this to see how {GraphQL::Schema::Warden} and {GraphQL::Schema::Visibility::Profile}
# handle `.visible?` differently in your schema.
#
# It runs the same method on both implementations and raises an error when the results diverge.
#
# To fix the error, modify your schema so that both implementations return the same thing.
# Or, open an issue on GitHub to discuss the difference.
#
# This plugin adds overhead to runtime and may cause unexpected crashes -- **don't** use it in production!
#
# This plugin adds two keys to `context` when running:
#
# - `visibility_migration_running: true`
# - For the {Schema::Warden} which it instantiates, it adds `visibility_migration_warden_running: true`.
#
# Use those keys to modify your `visible?` behavior as needed.
#
# Also, in a pinch, you can set `skip_visibility_migration_error: true` in context to turn off this behavior per-query.
# (In that case, it uses {Profile} directly.)
#
# @example Adding this plugin
#
# use GraphQL::Schema::Visibility, migration_errors: true
#
class Migration < GraphQL::Schema::Visibility::Profile
class RuntimeTypesMismatchError < GraphQL::Error
def initialize(method_called, warden_result, profile_result, method_args)
super(<<~ERR)
Mismatch in types for `##{method_called}(#{method_args.map(&:inspect).join(", ")})`:
#{compare_results(warden_result, profile_result)}
Update your `.visible?` implementation to make these implementations return the same value.
See: https://graphql-ruby.org/authorization/visibility_migration.html
ERR
end
private
def compare_results(warden_result, profile_result)
if warden_result.is_a?(Array) && profile_result.is_a?(Array)
all_results = warden_result | profile_result
all_results.sort_by!(&:graphql_name)
entries_text = all_results.map { |entry| "#{entry.graphql_name} (#{entry})"}
width = entries_text.map(&:size).max
yes = " ✔ "
no = " "
res = "".dup
res << "#{"Result".center(width)} Warden Profile \n"
all_results.each_with_index do |entry, idx|
res << "#{entries_text[idx].ljust(width)}#{warden_result.include?(entry) ? yes : no}#{profile_result.include?(entry) ? yes : no}\n"
end
res << "\n"
else
"- Warden returned: #{humanize(warden_result)}\n\n- Visibility::Profile returned: #{humanize(profile_result)}"
end
end
def humanize(val)
case val
when Array
"#{val.size}: #{val.map { |v| humanize(v) }.sort.inspect}"
when Module
if val.respond_to?(:graphql_name)
"#{val.graphql_name} (#{val.inspect})"
else
val.inspect
end
else
val.inspect
end
end
end
def initialize(context:, schema:, name: nil, visibility:)
@name = name
@skip_error = context[:skip_visibility_migration_error] || context.is_a?(Query::NullContext) || context.is_a?(Hash)
@profile_types = GraphQL::Schema::Visibility::Profile.new(context: context, schema: schema, visibility: visibility)
if !@skip_error
context[:visibility_migration_running] = true
warden_ctx_vals = context.to_h.dup
warden_ctx_vals[:visibility_migration_warden_running] = true
if schema.const_defined?(:WardenCompatSchema, false) # don't use a defn from a superclass
warden_schema = schema.const_get(:WardenCompatSchema, false)
else
warden_schema = Class.new(schema)
warden_schema.use_visibility_profile = false
# TODO public API
warden_schema.send(:add_type_and_traverse, [warden_schema.query, warden_schema.mutation, warden_schema.subscription].compact, root: true)
warden_schema.send(:add_type_and_traverse, warden_schema.directives.values + warden_schema.orphan_types, root: false)
schema.const_set(:WardenCompatSchema, warden_schema)
end
warden_ctx = GraphQL::Query::Context.new(query: context.query, values: warden_ctx_vals)
warden_ctx.warden = GraphQL::Schema::Warden.new(schema: warden_schema, context: warden_ctx)
warden_ctx.warden.skip_warning = true
warden_ctx.types = @warden_types = warden_ctx.warden.visibility_profile
end
end
def loaded_types
@profile_types.loaded_types
end
PUBLIC_PROFILE_METHODS = [
:enum_values,
:interfaces,
:all_types,
:all_types_h,
:fields,
:loadable?,
:loadable_possible_types,
:type,
:arguments,
:argument,
:directive_exists?,
:directives,
:field,
:query_root,
:mutation_root,
:possible_types,
:subscription_root,
:reachable_type?,
:visible_enum_value?,
]
PUBLIC_PROFILE_METHODS.each do |profile_method|
define_method(profile_method) do |*args|
call_method_and_compare(profile_method, args)
end
end
def call_method_and_compare(method, args)
res_1 = @profile_types.public_send(method, *args)
if @skip_error
return res_1
end
res_2 = @warden_types.public_send(method, *args)
normalized_res_1 = res_1.is_a?(Array) ? Set.new(res_1) : res_1
normalized_res_2 = res_2.is_a?(Array) ? Set.new(res_2) : res_2
if !equivalent_schema_members?(normalized_res_1, normalized_res_2)
# Raise the errors with the orignally returned values:
err = RuntimeTypesMismatchError.new(method, res_2, res_1, args)
raise err
else
res_1
end
end
def equivalent_schema_members?(member1, member2)
if member1.class != member2.class
return false
end
case member1
when Set
member1_array = member1.to_a.sort_by(&:graphql_name)
member2_array = member2.to_a.sort_by(&:graphql_name)
member1_array.each_with_index do |inner_member1, idx|
inner_member2 = member2_array[idx]
equivalent_schema_members?(inner_member1, inner_member2)
end
when GraphQL::Schema::Field
member1.ensure_loaded
member2.ensure_loaded
if member1.introspection? && member2.introspection?
member1.inspect == member2.inspect
else
member1 == member2
end
when Module
if member1.introspection? && member2.introspection?
member1.graphql_name == member2.graphql_name
else
member1 == member2
end
else
member1 == member2
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/field/scope_extension.rb | lib/graphql/schema/field/scope_extension.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Field
class ScopeExtension < GraphQL::Schema::FieldExtension
def after_resolve(object:, arguments:, context:, value:, memo:)
if value.nil?
value
else
ret_type = @field.type.unwrap
if ret_type.respond_to?(:scope_items)
scoped_items = ret_type.scope_items(value, context)
if !scoped_items.equal?(value) && !ret_type.reauthorize_scoped_objects
if (current_runtime_state = Fiber[:__graphql_runtime_info]) &&
(query_runtime_state = current_runtime_state[context.query])
query_runtime_state.was_authorized_by_scope_items = true
end
end
scoped_items
else
value
end
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/field/connection_extension.rb | lib/graphql/schema/field/connection_extension.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Field
class ConnectionExtension < GraphQL::Schema::FieldExtension
def apply
field.argument :after, "String", "Returns the elements in the list that come after the specified cursor.", required: false
field.argument :before, "String", "Returns the elements in the list that come before the specified cursor.", required: false
field.argument :first, "Int", "Returns the first _n_ elements from the list.", required: false
field.argument :last, "Int", "Returns the last _n_ elements from the list.", required: false
end
# Remove pagination args before passing it to a user method
def resolve(object:, arguments:, context:)
next_args = arguments.dup
next_args.delete(:first)
next_args.delete(:last)
next_args.delete(:before)
next_args.delete(:after)
yield(object, next_args, arguments)
end
def after_resolve(value:, object:, arguments:, context:, memo:)
original_arguments = memo
# rename some inputs to avoid conflicts inside the block
maybe_lazy = value
value = nil
context.query.after_lazy(maybe_lazy) do |resolved_value|
value = resolved_value
if value.is_a? GraphQL::ExecutionError
# This isn't even going to work because context doesn't have ast_node anymore
context.add_error(value)
nil
elsif value.nil?
nil
elsif value.is_a?(GraphQL::Pagination::Connection)
# update the connection with some things that may not have been provided
value.context ||= context
value.parent ||= object.object
value.first_value ||= original_arguments[:first]
value.after_value ||= original_arguments[:after]
value.last_value ||= original_arguments[:last]
value.before_value ||= original_arguments[:before]
value.arguments ||= original_arguments # rubocop:disable Development/ContextIsPassedCop -- unrelated .arguments method
value.field ||= field
if field.has_max_page_size? && !value.has_max_page_size_override?
value.max_page_size = field.max_page_size
end
if field.has_default_page_size? && !value.has_default_page_size_override?
value.default_page_size = field.default_page_size
end
if (custom_t = context.schema.connections.edge_class_for_field(@field))
value.edge_class = custom_t
end
value
else
context.namespace(:connections)[:all_wrappers] ||= context.schema.connections.all_wrappers
context.schema.connections.wrap(field, object.object, value, original_arguments, context)
end
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/validator/format_validator.rb | lib/graphql/schema/validator/format_validator.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Validator
# Use this to assert that string values match (or don't match) the given RegExp.
#
# @example requiring input to match a pattern
#
# argument :handle, String, required: true,
# validates: { format: { with: /\A[a-z0-9_]+\Z/ } }
#
# @example reject inputs that match a pattern
#
# argument :word_that_doesnt_begin_with_a_vowel, String, required: true,
# validates: { format: { without: /\A[aeiou]/ } }
#
# # It's pretty hard to come up with a legitimate use case for `without:`
#
class FormatValidator < Validator
# @param with [RegExp, nil]
# @param without [Regexp, nil]
# @param message [String]
def initialize(
with: nil,
without: nil,
message: "%{validated} is invalid",
**default_options
)
@with_pattern = with
@without_pattern = without
@message = message
super(**default_options)
end
def validate(_object, _context, value)
if permitted_empty_value?(value)
# Do nothing
elsif value.nil? ||
(@with_pattern && !value.match?(@with_pattern)) ||
(@without_pattern && value.match?(@without_pattern))
@message
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/validator/required_validator.rb | lib/graphql/schema/validator/required_validator.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Validator
# Use this validator to require _one_ of the named arguments to be present.
# Or, use Arrays of symbols to name a valid _set_ of arguments.
#
# (This is for specifying mutually exclusive sets of arguments.)
#
# If you use {GraphQL::Schema::Visibility} to hide all the arguments in a `one_of: [..]` set,
# then a developer-facing {GraphQL::Error} will be raised during execution. Pass `allow_all_hidden: true` to
# skip validation in this case instead.
#
# This validator also implements `argument ... required: :nullable`. If an argument has `required: :nullable`
# but it's hidden with {GraphQL::Schema::Visibility}, then this validator doesn't run.
#
# @example Require exactly one of these arguments
#
# field :update_amount, IngredientAmount, null: false do
# argument :ingredient_id, ID, required: true
# argument :cups, Integer, required: false
# argument :tablespoons, Integer, required: false
# argument :teaspoons, Integer, required: false
# validates required: { one_of: [:cups, :tablespoons, :teaspoons] }
# end
#
# @example Require one of these _sets_ of arguments
#
# field :find_object, Node, null: true do
# argument :node_id, ID, required: false
# argument :object_type, String, required: false
# argument :object_id, Integer, required: false
# # either a global `node_id` or an `object_type`/`object_id` pair is required:
# validates required: { one_of: [:node_id, [:object_type, :object_id]] }
# end
#
# @example require _some_ value for an argument, even if it's null
# field :update_settings, AccountSettings do
# # `required: :nullable` means this argument must be given, but may be `null`
# argument :age, Integer, required: :nullable
# end
#
class RequiredValidator < Validator
# @param one_of [Array<Symbol>] A list of arguments, exactly one of which is required for this field
# @param argument [Symbol] An argument that is required for this field
# @param allow_all_hidden [Boolean] If `true`, then this validator won't run if all the `one_of: ...` arguments have been hidden
# @param message [String]
def initialize(one_of: nil, argument: nil, allow_all_hidden: nil, message: nil, **default_options)
@one_of = if one_of
one_of
elsif argument
[ argument ]
else
raise ArgumentError, "`one_of:` or `argument:` must be given in `validates required: {...}`"
end
@allow_all_hidden = allow_all_hidden.nil? ? !!argument : allow_all_hidden
@message = message
super(**default_options)
end
def validate(_object, context, value)
fully_matched_conditions = 0
partially_matched_conditions = 0
visible_keywords = context.types.arguments(@validated).map(&:keyword)
no_visible_conditions = true
if !value.nil?
@one_of.each do |one_of_condition|
case one_of_condition
when Symbol
if no_visible_conditions && visible_keywords.include?(one_of_condition)
no_visible_conditions = false
end
if value.key?(one_of_condition)
fully_matched_conditions += 1
end
when Array
any_match = false
full_match = true
one_of_condition.each do |k|
if no_visible_conditions && visible_keywords.include?(k)
no_visible_conditions = false
end
if value.key?(k)
any_match = true
else
full_match = false
end
end
partial_match = !full_match && any_match
if full_match
fully_matched_conditions += 1
end
if partial_match
partially_matched_conditions += 1
end
else
raise ArgumentError, "Unknown one_of condition: #{one_of_condition.inspect}"
end
end
end
if no_visible_conditions
if @allow_all_hidden
return nil
else
raise GraphQL::Error, <<~ERR
#{@validated.path} validates `required: ...` but all required arguments were hidden.
Update your schema definition to allow the client to see some fields or skip validation by adding `required: { ..., allow_all_hidden: true }`
ERR
end
end
if fully_matched_conditions == 1 && partially_matched_conditions == 0
nil # OK
else
@message || build_message(context)
end
end
def build_message(context)
argument_definitions = context.types.arguments(@validated)
required_names = @one_of.map do |arg_keyword|
if arg_keyword.is_a?(Array)
names = arg_keyword.map { |arg| arg_keyword_to_graphql_name(argument_definitions, arg) }
names.compact! # hidden arguments are `nil`
"(" + names.join(" and ") + ")"
else
arg_keyword_to_graphql_name(argument_definitions, arg_keyword)
end
end
required_names.compact! # remove entries for hidden arguments
case required_names.size
when 0
# The required definitions were hidden from the client.
# Another option here would be to raise an error in the application....
"%{validated} is missing a required argument."
when 1
"%{validated} must include the following argument: #{required_names.first}."
else
"%{validated} must include exactly one of the following arguments: #{required_names.join(", ")}."
end
end
def arg_keyword_to_graphql_name(argument_definitions, arg_keyword)
argument_definition = argument_definitions.find { |defn| defn.keyword == arg_keyword }
argument_definition&.graphql_name
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/validator/numericality_validator.rb | lib/graphql/schema/validator/numericality_validator.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Validator
# Use this to assert numerical comparisons hold true for inputs.
#
# @example Require a number between 0 and 1
#
# argument :batting_average, Float, required: true, validates: { numericality: { within: 0..1 } }
#
# @example Require the number 42
#
# argument :the_answer, Integer, required: true, validates: { numericality: { equal_to: 42 } }
#
# @example Require a real number
#
# argument :items_count, Integer, required: true, validates: { numericality: { greater_than_or_equal_to: 0 } }
#
class NumericalityValidator < Validator
# @param greater_than [Integer]
# @param greater_than_or_equal_to [Integer]
# @param less_than [Integer]
# @param less_than_or_equal_to [Integer]
# @param equal_to [Integer]
# @param other_than [Integer]
# @param odd [Boolean]
# @param even [Boolean]
# @param within [Range]
# @param message [String] used for all validation failures
def initialize(
greater_than: nil, greater_than_or_equal_to: nil,
less_than: nil, less_than_or_equal_to: nil,
equal_to: nil, other_than: nil,
odd: nil, even: nil, within: nil,
message: "%{validated} must be %{comparison} %{target}",
null_message: Validator::AllowNullValidator::MESSAGE,
**default_options
)
@greater_than = greater_than
@greater_than_or_equal_to = greater_than_or_equal_to
@less_than = less_than
@less_than_or_equal_to = less_than_or_equal_to
@equal_to = equal_to
@other_than = other_than
@odd = odd
@even = even
@within = within
@message = message
@null_message = null_message
super(**default_options)
end
def validate(object, context, value)
if permitted_empty_value?(value)
# pass in this case
elsif value.nil? # @allow_null is handled in the parent class
@null_message
elsif @greater_than && value <= @greater_than
partial_format(@message, { comparison: "greater than", target: @greater_than })
elsif @greater_than_or_equal_to && value < @greater_than_or_equal_to
partial_format(@message, { comparison: "greater than or equal to", target: @greater_than_or_equal_to })
elsif @less_than && value >= @less_than
partial_format(@message, { comparison: "less than", target: @less_than })
elsif @less_than_or_equal_to && value > @less_than_or_equal_to
partial_format(@message, { comparison: "less than or equal to", target: @less_than_or_equal_to })
elsif @equal_to && value != @equal_to
partial_format(@message, { comparison: "equal to", target: @equal_to })
elsif @other_than && value == @other_than
partial_format(@message, { comparison: "something other than", target: @other_than })
elsif @even && !value.even?
(partial_format(@message, { comparison: "even", target: "" })).strip
elsif @odd && !value.odd?
(partial_format(@message, { comparison: "odd", target: "" })).strip
elsif @within && !@within.include?(value)
partial_format(@message, { comparison: "within", target: @within })
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/validator/allow_blank_validator.rb | lib/graphql/schema/validator/allow_blank_validator.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Validator
# Use this to specifically reject values that respond to `.blank?` and respond truthy for that method.
#
# @example Require a non-empty string for an argument
# argument :name, String, required: true, validate: { allow_blank: false }
class AllowBlankValidator < Validator
def initialize(allow_blank_positional, allow_blank: nil, message: "%{validated} can't be blank", **default_options)
@message = message
super(**default_options)
@allow_blank = allow_blank.nil? ? allow_blank_positional : allow_blank
end
def validate(_object, _context, value)
if value.respond_to?(:blank?) && value.blank?
if (value.nil? && @allow_null) || @allow_blank
# pass
else
@message
end
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/validator/allow_null_validator.rb | lib/graphql/schema/validator/allow_null_validator.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Validator
# Use this to specifically reject or permit `nil` values (given as `null` from GraphQL).
#
# @example require a non-null value for an argument if it is provided
# argument :name, String, required: false, validates: { allow_null: false }
class AllowNullValidator < Validator
MESSAGE = "%{validated} can't be null"
def initialize(allow_null_positional, allow_null: nil, message: MESSAGE, **default_options)
@message = message
super(**default_options)
@allow_null = allow_null.nil? ? allow_null_positional : allow_null
end
def validate(_object, _context, value)
if value.nil? && !@allow_null
@message
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/validator/inclusion_validator.rb | lib/graphql/schema/validator/inclusion_validator.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Validator
# You can use this to allow certain values for an argument.
#
# Usually, a {GraphQL::Schema::Enum} is better for this, because it's self-documenting.
#
# @example only allow certain values for an argument
#
# argument :favorite_prime, Integer, required: true,
# validates: { inclusion: { in: [2, 3, 5, 7, 11, ... ] } }
#
class InclusionValidator < Validator
# @param message [String]
# @param in [Array] The values to allow
def initialize(in:, message: "%{validated} is not included in the list", **default_options)
# `in` is a reserved word, so work around that
@in_list = binding.local_variable_get(:in)
@message = message
super(**default_options)
end
def validate(_object, _context, value)
if permitted_empty_value?(value)
# pass
elsif !@in_list.include?(value)
@message
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/validator/length_validator.rb | lib/graphql/schema/validator/length_validator.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Validator
# Use this to enforce a `.length` restriction on incoming values. It works for both Strings and Lists.
#
# @example Allow no more than 10 IDs
#
# argument :ids, [ID], required: true, validates: { length: { maximum: 10 } }
#
# @example Require three selections
#
# argument :ice_cream_preferences, [ICE_CREAM_FLAVOR], required: true, validates: { length: { is: 3 } }
#
class LengthValidator < Validator
# @param maximum [Integer]
# @param too_long [String] Used when `maximum` is exceeded or value is greater than `within`
# @param minimum [Integer]
# @param too_short [String] Used with value is less than `minimum` or less than `within`
# @param is [Integer] Exact length requirement
# @param wrong_length [String] Used when value doesn't match `is`
# @param within [Range] An allowed range (becomes `minimum:` and `maximum:` under the hood)
# @param message [String]
def initialize(
maximum: nil, too_long: "%{validated} is too long (maximum is %{count})",
minimum: nil, too_short: "%{validated} is too short (minimum is %{count})",
is: nil, within: nil, wrong_length: "%{validated} is the wrong length (should be %{count})",
message: nil,
**default_options
)
if within && (minimum || maximum)
raise ArgumentError, "`length: { ... }` may include `within:` _or_ `minimum:`/`maximum:`, but not both"
end
# Under the hood, `within` is decomposed into `minimum` and `maximum`
@maximum = maximum || (within && within.max)
@too_long = message || too_long
@minimum = minimum || (within && within.min)
@too_short = message || too_short
@is = is
@wrong_length = message || wrong_length
super(**default_options)
end
def validate(_object, _context, value)
return if permitted_empty_value?(value) # pass in this case
length = value.nil? ? 0 : value.length
if @maximum && length > @maximum
partial_format(@too_long, { count: @maximum })
elsif @minimum && length < @minimum
partial_format(@too_short, { count: @minimum })
elsif @is && length != @is
partial_format(@wrong_length, { count: @is })
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/validator/all_validator.rb | lib/graphql/schema/validator/all_validator.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Validator
# Use this to validate each member of an array value.
#
# @example validate format of all strings in an array
#
# argument :handles, [String],
# validates: { all: { format: { with: /\A[a-z0-9_]+\Z/ } } }
#
# @example multiple validators can be combined
#
# argument :handles, [String],
# validates: { all: { format: { with: /\A[a-z0-9_]+\Z/ }, length: { maximum: 32 } } }
#
# @example any type can be used
#
# argument :choices, [Integer],
# validates: { all: { inclusion: { in: 1..12 } } }
#
class AllValidator < Validator
def initialize(validated:, allow_blank: false, allow_null: false, **validators)
super(validated: validated, allow_blank: allow_blank, allow_null: allow_null)
@validators = Validator.from_config(validated, validators)
end
def validate(object, context, value)
return EMPTY_ARRAY if permitted_empty_value?(value)
all_errors = EMPTY_ARRAY
value.each do |subvalue|
@validators.each do |validator|
errors = validator.validate(object, context, subvalue)
if errors &&
(errors.is_a?(Array) && errors != EMPTY_ARRAY) ||
(errors.is_a?(String))
if all_errors.frozen? # It's empty
all_errors = []
end
if errors.is_a?(String)
all_errors << errors
else
all_errors.concat(errors)
end
end
end
end
unless all_errors.frozen?
all_errors.uniq!
end
all_errors
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/validator/exclusion_validator.rb | lib/graphql/schema/validator/exclusion_validator.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Validator
# Use this to specifically reject values from an argument.
#
# @example disallow certain values
#
# argument :favorite_non_prime, Integer, required: true,
# validates: { exclusion: { in: [2, 3, 5, 7, ... ]} }
#
class ExclusionValidator < Validator
# @param message [String]
# @param in [Array] The values to reject
def initialize(message: "%{validated} is reserved", in:, **default_options)
# `in` is a reserved word, so work around that
@in_list = binding.local_variable_get(:in)
@message = message
super(**default_options)
end
def validate(_object, _context, value)
if permitted_empty_value?(value)
# pass
elsif @in_list.include?(value)
@message
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/directive/deprecated.rb | lib/graphql/schema/directive/deprecated.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Directive < GraphQL::Schema::Member
class Deprecated < GraphQL::Schema::Directive
description "Marks an element of a GraphQL schema as no longer supported."
locations(GraphQL::Schema::Directive::FIELD_DEFINITION, GraphQL::Schema::Directive::ENUM_VALUE, GraphQL::Schema::Directive::ARGUMENT_DEFINITION, GraphQL::Schema::Directive::INPUT_FIELD_DEFINITION)
reason_description = "Explains why this element was deprecated, usually also including a "\
"suggestion for how to access supported similar data. Formatted "\
"in [Markdown](https://daringfireball.net/projects/markdown/)."
argument :reason, String, reason_description, default_value: Directive::DEFAULT_DEPRECATION_REASON, required: false
default_directive true
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/directive/include.rb | lib/graphql/schema/directive/include.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Directive < GraphQL::Schema::Member
class Include < GraphQL::Schema::Directive
description "Directs the executor to include this field or fragment only when the `if` argument is true."
locations(
GraphQL::Schema::Directive::FIELD,
GraphQL::Schema::Directive::FRAGMENT_SPREAD,
GraphQL::Schema::Directive::INLINE_FRAGMENT
)
argument :if, Boolean,
description: "Included when true."
default_directive true
def self.static_include?(args, ctx)
!!args[:if]
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/directive/specified_by.rb | lib/graphql/schema/directive/specified_by.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Directive < GraphQL::Schema::Member
class SpecifiedBy < GraphQL::Schema::Directive
description "Exposes a URL that specifies the behavior of this scalar."
locations(GraphQL::Schema::Directive::SCALAR)
default_directive true
argument :url, String, description: "The URL that specifies the behavior of this scalar."
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/directive/flagged.rb | lib/graphql/schema/directive/flagged.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Directive < GraphQL::Schema::Member
# This is _similar_ to {Directive::Feature}, except it's prescribed by the server, not the client.
#
# In this case, the server hides types and fields _entirely_, unless the current context has certain `:flags` present.
class Flagged < GraphQL::Schema::Directive
def initialize(target, **options)
if target.is_a?(Module)
# This is type class of some kind, `include` will put this module
# in between the type class itself and its super class, so `super` will work fine
target.include(VisibleByFlag)
elsif !target.is_a?(VisibleByFlag)
# This is an instance of a base class. `include` won't put this in front of the
# base class implementation, so we need to `.prepend`.
# `#visible?` could probably be moved to a module and then this could use `include` instead.
target.class.prepend(VisibleByFlag)
end
super
end
description "Hides this part of the schema unless the named flag is present in context[:flags]"
locations(
GraphQL::Schema::Directive::FIELD_DEFINITION,
GraphQL::Schema::Directive::OBJECT,
GraphQL::Schema::Directive::SCALAR,
GraphQL::Schema::Directive::ENUM,
GraphQL::Schema::Directive::UNION,
GraphQL::Schema::Directive::INTERFACE,
GraphQL::Schema::Directive::INPUT_OBJECT,
GraphQL::Schema::Directive::ENUM_VALUE,
GraphQL::Schema::Directive::ARGUMENT_DEFINITION,
GraphQL::Schema::Directive::INPUT_FIELD_DEFINITION,
)
argument :by, [String], "Flags to check for this schema member"
repeatable(true)
module VisibleByFlag
def self.included(schema_class)
schema_class.extend(self)
end
def visible?(context)
if dir = self.directives.find { |d| d.is_a?(Flagged) }
relevant_flags = (f = context[:flags]) && dir.arguments[:by] & f # rubocop:disable Development/ContextIsPassedCop -- definition-related
relevant_flags && !relevant_flags.empty? && super
else
super
end
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/directive/transform.rb | lib/graphql/schema/directive/transform.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Directive < GraphQL::Schema::Member
# An example directive to show how you might interact with the runtime.
#
# This directive takes the return value of the tagged part of the query,
# and if the named transform is whitelisted and applies to the return value,
# it's applied by calling a method with that name.
#
# @example Installing the directive
# class MySchema < GraphQL::Schema
# directive(GraphQL::Schema::Directive::Transform)
# end
#
# @example Transforming strings
# viewer {
# username @transform(by: "upcase")
# }
class Transform < Schema::Directive
description "Directs the executor to run named transform on the return value."
locations(
GraphQL::Schema::Directive::FIELD,
)
argument :by, String,
description: "The name of the transform to run if applicable"
TRANSFORMS = [
"upcase",
"downcase",
# ??
]
# Implement the Directive API
def self.resolve(object, arguments, context)
path = context.namespace(:interpreter)[:current_path]
return_value = yield
transform_name = arguments[:by]
if TRANSFORMS.include?(transform_name) && return_value.respond_to?(transform_name)
return_value = return_value.public_send(transform_name)
response = context.namespace(:interpreter_runtime)[:runtime].final_result
*keys, last = path
keys.each do |key|
if response && (response = response[key])
next
else
break
end
end
if response
response[last] = return_value
end
nil
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/directive/feature.rb | lib/graphql/schema/directive/feature.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Directive < GraphQL::Schema::Member
# An example directive to show how you might interact with the runtime.
#
# This directive might be used along with a server-side feature flag system like Flipper.
#
# With that system, you could use this directive to exclude parts of a query
# if the current viewer doesn't have certain flags enabled.
# (So, this flag would be for internal clients, like your iOS app, not third-party API clients.)
#
# To use it, you have to implement `.enabled?`, for example:
#
# @example Implementing the Feature directive
# # app/graphql/directives/feature.rb
# class Directives::Feature < GraphQL::Schema::Directive::Feature
# def self.enabled?(flag_name, _obj, context)
# # Translate some GraphQL data for Ruby:
# flag_key = flag_name.underscore
# current_user = context[:viewer]
# # Check the feature flag however your app does it:
# MyFeatureFlags.enabled?(current_user, flag_key)
# end
# end
#
# @example Flagging a part of the query
# viewer {
# # This field only runs if `.enabled?("recommendationEngine", obj, context)`
# # returns true. Otherwise, it's treated as if it didn't exist.
# recommendations @feature(flag: "recommendationEngine") {
# name
# rating
# }
# }
class Feature < Schema::Directive
description "Directs the executor to run this only if a certain server-side feature is enabled."
locations(
GraphQL::Schema::Directive::FIELD,
GraphQL::Schema::Directive::FRAGMENT_SPREAD,
GraphQL::Schema::Directive::INLINE_FRAGMENT
)
argument :flag, String,
description: "The name of the feature to check before continuing"
# Implement the Directive API
def self.include?(object, arguments, context)
flag_name = arguments[:flag]
self.enabled?(flag_name, object, context)
end
# Override this method in your app's subclass of this directive.
#
# @param flag_name [String] The client-provided string of a feature to check
# @param object [GraphQL::Schema::Objct] The currently-evaluated GraphQL object instance
# @param context [GraphQL::Query::Context]
# @return [Boolean] If truthy, execution will continue
def self.enabled?(flag_name, object, context)
raise GraphQL::RequiredImplementationMissingError, "Implement `.enabled?(flag_name, object, context)` to return true or false for the feature flag (#{flag_name.inspect})"
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/directive/skip.rb | lib/graphql/schema/directive/skip.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Directive < GraphQL::Schema::Member
class Skip < Schema::Directive
description "Directs the executor to skip this field or fragment when the `if` argument is true."
locations(
GraphQL::Schema::Directive::FIELD,
GraphQL::Schema::Directive::FRAGMENT_SPREAD,
GraphQL::Schema::Directive::INLINE_FRAGMENT
)
argument :if, Boolean,
description: "Skipped when true."
default_directive true
def self.static_include?(args, ctx)
!args[:if]
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/directive/one_of.rb | lib/graphql/schema/directive/one_of.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Directive < GraphQL::Schema::Member
class OneOf < GraphQL::Schema::Directive
description "Requires that exactly one field must be supplied and that field must not be `null`."
locations(GraphQL::Schema::Directive::INPUT_OBJECT)
default_directive true
def initialize(...)
super
owner.extend(IsOneOf)
end
module IsOneOf
def one_of?
true
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/dataloader/source.rb | lib/graphql/dataloader/source.rb | # frozen_string_literal: true
module GraphQL
class Dataloader
class Source
# Called by {Dataloader} to prepare the {Source}'s internal state
# @api private
def setup(dataloader)
# These keys have been requested but haven't been fetched yet
@pending = {}
# These keys have been passed to `fetch` but haven't been finished yet
@fetching = {}
# { key => result }
@results = {}
@dataloader = dataloader
end
attr_reader :dataloader
# @return [Dataloader::Request] a pending request for a value from `key`. Call `.load` on that object to wait for the result.
def request(value)
res_key = result_key_for(value)
if !@results.key?(res_key)
@pending[res_key] ||= normalize_fetch_key(value)
end
Dataloader::Request.new(self, value)
end
# Implement this method to return a stable identifier if different
# key objects should load the same data value.
#
# @param value [Object] A value passed to `.request` or `.load`, for which a value will be loaded
# @return [Object] The key for tracking this pending data
def result_key_for(value)
value
end
# Implement this method if varying values given to {load} (etc) should be consolidated
# or normalized before being handed off to your {fetch} implementation.
#
# This is different than {result_key_for} because _that_ method handles unification inside Dataloader's cache,
# but this method changes the value passed into {fetch}.
#
# @param value [Object] The value passed to {load}, {load_all}, {request}, or {request_all}
# @return [Object] The value given to {fetch}
def normalize_fetch_key(value)
value
end
# @return [Dataloader::Request] a pending request for a values from `keys`. Call `.load` on that object to wait for the results.
def request_all(values)
values.each do |v|
res_key = result_key_for(v)
if !@results.key?(res_key)
@pending[res_key] ||= normalize_fetch_key(v)
end
end
Dataloader::RequestAll.new(self, values)
end
# @param value [Object] A loading value which will be passed to {#fetch} if it isn't already in the internal cache.
# @return [Object] The result from {#fetch} for `key`. If `key` hasn't been loaded yet, the Fiber will yield until it's loaded.
def load(value)
result_key = result_key_for(value)
if @results.key?(result_key)
result_for(result_key)
else
@pending[result_key] ||= normalize_fetch_key(value)
sync([result_key])
result_for(result_key)
end
end
# @param values [Array<Object>] Loading keys which will be passed to `#fetch` (or read from the internal cache).
# @return [Object] The result from {#fetch} for `keys`. If `keys` haven't been loaded yet, the Fiber will yield until they're loaded.
def load_all(values)
result_keys = []
pending_keys = []
values.each { |v|
k = result_key_for(v)
result_keys << k
if !@results.key?(k)
@pending[k] ||= normalize_fetch_key(v)
pending_keys << k
end
}
if !pending_keys.empty?
sync(pending_keys)
end
result_keys.map { |k| result_for(k) }
end
# Subclasses must implement this method to return a value for each of `keys`
# @param keys [Array<Object>] keys passed to {#load}, {#load_all}, {#request}, or {#request_all}
# @return [Array<Object>] A loaded value for each of `keys`. The array must match one-for-one to the list of `keys`.
def fetch(keys)
# somehow retrieve these from the backend
raise "Implement `#{self.class}#fetch(#{keys.inspect}) to return a record for each of the keys"
end
MAX_ITERATIONS = 1000
# Wait for a batch, if there's anything to batch.
# Then run the batch and update the cache.
# @return [void]
def sync(pending_result_keys)
@dataloader.yield(self)
iterations = 0
while pending_result_keys.any? { |key| !@results.key?(key) }
iterations += 1
if iterations > MAX_ITERATIONS
raise "#{self.class}#sync tried #{MAX_ITERATIONS} times to load pending keys (#{pending_result_keys}), but they still weren't loaded. There is likely a circular dependency#{@dataloader.fiber_limit ? " or `fiber_limit: #{@dataloader.fiber_limit}` is set too low" : ""}."
end
@dataloader.yield(self)
end
nil
end
# @return [Boolean] True if this source has any pending requests for data.
def pending?
!@pending.empty?
end
# Add these key-value pairs to this source's cache
# (future loads will use these merged values).
# @param new_results [Hash<Object => Object>] key-value pairs to cache in this source
# @return [void]
def merge(new_results)
new_results.each do |new_k, new_v|
key = result_key_for(new_k)
@results[key] = new_v
end
nil
end
# Called by {GraphQL::Dataloader} to resolve and pending requests to this source.
# @api private
# @return [void]
def run_pending_keys
if !@fetching.empty?
@fetching.each_key { |k| @pending.delete(k) }
end
return if @pending.empty?
fetch_h = @pending
@pending = {}
@fetching.merge!(fetch_h)
results = fetch(fetch_h.values)
fetch_h.each_with_index do |(key, _value), idx|
@results[key] = results[idx]
end
nil
rescue StandardError => error
fetch_h.each_key { |key| @results[key] = error }
ensure
fetch_h && fetch_h.each_key { |k| @fetching.delete(k) }
end
# These arguments are given to `dataloader.with(source_class, ...)`. The object
# returned from this method is used to de-duplicate batch loads under the hood
# by using it as a Hash key.
#
# By default, the arguments are all put in an Array. To customize how this source's
# batches are merged, override this method to return something else.
#
# For example, if you pass `ActiveRecord::Relation`s to `.with(...)`, you could override
# this method to call `.to_sql` on them, thus merging `.load(...)` calls when they apply
# to equivalent relations.
#
# @param batch_args [Array<Object>]
# @param batch_kwargs [Hash]
# @return [Object]
def self.batch_key_for(*batch_args, **batch_kwargs)
[*batch_args, **batch_kwargs]
end
# Clear any already-loaded objects for this source
# @return [void]
def clear_cache
@results.clear
nil
end
attr_reader :pending, :results
private
# Reads and returns the result for the key from the internal cache, or raises an error if the result was an error
# @param key [Object] key passed to {#load} or {#load_all}
# @return [Object] The result from {#fetch} for `key`.
# @api private
def result_for(key)
if !@results.key?(key)
raise GraphQL::InvariantError, <<-ERR
Fetching result for a key on #{self.class} that hasn't been loaded yet (#{key.inspect}, loaded: #{@results.keys})
This key should have been loaded already. This is a bug in GraphQL::Dataloader, please report it on GitHub: https://github.com/rmosolgo/graphql-ruby/issues/new.
ERR
end
result = @results[key]
if result.is_a?(StandardError)
# Dup it because the rescuer may modify it.
# (This happens for GraphQL::ExecutionErrors, at least)
raise result.dup
end
result
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/dataloader/active_record_association_source.rb | lib/graphql/dataloader/active_record_association_source.rb | # frozen_string_literal: true
require "graphql/dataloader/source"
require "graphql/dataloader/active_record_source"
module GraphQL
class Dataloader
class ActiveRecordAssociationSource < GraphQL::Dataloader::Source
RECORD_SOURCE_CLASS = ActiveRecordSource
def initialize(association, scope = nil)
@association = association
@scope = scope
end
def self.batch_key_for(association, scope = nil)
if scope
[association, scope.to_sql]
else
[association]
end
end
def load(record)
if (assoc = record.association(@association)).loaded?
assoc.target
else
super
end
end
def fetch(records)
record_classes = Set.new.compare_by_identity
associated_classes = Set.new.compare_by_identity
scoped_fetch = !@scope.nil?
records.each do |record|
if scoped_fetch
assoc = record.association(@association)
assoc.reset
end
if record_classes.add?(record.class)
reflection = record.class.reflect_on_association(@association)
if !reflection.polymorphic? && reflection.klass
associated_classes.add(reflection.klass)
end
end
end
available_records = []
associated_classes.each do |assoc_class|
already_loaded_records = dataloader.with(RECORD_SOURCE_CLASS, assoc_class).results.values
available_records.concat(already_loaded_records)
end
::ActiveRecord::Associations::Preloader.new(records: records, associations: @association, available_records: available_records, scope: @scope).call
loaded_associated_records = records.map { |r|
assoc = r.association(@association)
lar = assoc.target
if scoped_fetch
assoc.reset
end
lar
}
if !scoped_fetch
# Don't cache records loaded via scope because they might have reduced `SELECT`s
# Could check .select_values here?
records_by_model = {}
loaded_associated_records.flatten.each do |record|
if record
updates = records_by_model[record.class] ||= {}
updates[record.id] = record
end
end
records_by_model.each do |model_class, updates|
dataloader.with(RECORD_SOURCE_CLASS, model_class).merge(updates)
end
end
loaded_associated_records
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/dataloader/null_dataloader.rb | lib/graphql/dataloader/null_dataloader.rb | # frozen_string_literal: true
module GraphQL
class Dataloader
# GraphQL-Ruby uses this when Dataloader isn't enabled.
#
# It runs execution code inline and gathers lazy objects (eg. Promises)
# and resolves them during {#run}.
class NullDataloader < Dataloader
def initialize(*)
@lazies_at_depth = Hash.new { |h,k| h[k] = [] }
end
def freeze
@lazies_at_depth.default_proc = nil
@lazies_at_depth.freeze
super
end
def run(trace_query_lazy: nil)
with_trace_query_lazy(trace_query_lazy) do
while !@lazies_at_depth.empty?
smallest_depth = nil
@lazies_at_depth.each_key do |depth_key|
smallest_depth ||= depth_key
if depth_key < smallest_depth
smallest_depth = depth_key
end
end
if smallest_depth
lazies = @lazies_at_depth.delete(smallest_depth)
lazies.each(&:value) # resolve these Lazy instances
end
end
end
end
def run_isolated
new_dl = self.class.new
res = nil
new_dl.append_job {
res = yield
}
new_dl.run
res
end
def clear_cache; end
def yield(_source)
raise GraphQL::Error, "GraphQL::Dataloader is not running -- add `use GraphQL::Dataloader` to your schema to use Dataloader sources."
end
def append_job(callable = nil)
callable ? callable.call : yield
nil
end
def with(*)
raise GraphQL::Error, "GraphQL::Dataloader is not running -- add `use GraphQL::Dataloader` to your schema to use Dataloader sources."
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/dataloader/async_dataloader.rb | lib/graphql/dataloader/async_dataloader.rb | # frozen_string_literal: true
module GraphQL
class Dataloader
class AsyncDataloader < Dataloader
def yield(source = Fiber[:__graphql_current_dataloader_source])
trace = Fiber[:__graphql_current_multiplex]&.current_trace
trace&.dataloader_fiber_yield(source)
if (condition = Fiber[:graphql_dataloader_next_tick])
condition.wait
else
Fiber.yield
end
trace&.dataloader_fiber_resume(source)
nil
end
def run(trace_query_lazy: nil)
trace = Fiber[:__graphql_current_multiplex]&.current_trace
jobs_fiber_limit, total_fiber_limit = calculate_fiber_limit
job_fibers = []
next_job_fibers = []
source_tasks = []
next_source_tasks = []
first_pass = true
sources_condition = Async::Condition.new
manager = spawn_fiber do
trace&.begin_dataloader(self)
while first_pass || !job_fibers.empty?
first_pass = false
fiber_vars = get_fiber_variables
run_pending_steps(job_fibers, next_job_fibers, source_tasks, jobs_fiber_limit, trace)
Sync do |root_task|
set_fiber_variables(fiber_vars)
while !source_tasks.empty? || @source_cache.each_value.any? { |group_sources| group_sources.each_value.any?(&:pending?) }
while (task = (source_tasks.shift || (((job_fibers.size + next_job_fibers.size + source_tasks.size + next_source_tasks.size) < total_fiber_limit) && spawn_source_task(root_task, sources_condition, trace))))
if task.alive?
root_task.yield # give the source task a chance to run
next_source_tasks << task
end
end
sources_condition.signal
source_tasks.concat(next_source_tasks)
next_source_tasks.clear
end
end
if !@lazies_at_depth.empty?
with_trace_query_lazy(trace_query_lazy) do
run_next_pending_lazies(job_fibers, trace)
run_pending_steps(job_fibers, next_job_fibers, source_tasks, jobs_fiber_limit, trace)
end
end
end
trace&.end_dataloader(self)
end
manager.resume
if manager.alive?
raise "Invariant: Manager didn't terminate successfully: #{manager}"
end
rescue UncaughtThrowError => e
throw e.tag, e.value
end
private
def run_pending_steps(job_fibers, next_job_fibers, source_tasks, jobs_fiber_limit, trace)
while (f = (job_fibers.shift || (((job_fibers.size + next_job_fibers.size + source_tasks.size) < jobs_fiber_limit) && spawn_job_fiber(trace))))
if f.alive?
finished = run_fiber(f)
if !finished
next_job_fibers << f
end
end
end
job_fibers.concat(next_job_fibers)
next_job_fibers.clear
end
def spawn_source_task(parent_task, condition, trace)
pending_sources = nil
@source_cache.each_value do |source_by_batch_params|
source_by_batch_params.each_value do |source|
if source.pending?
pending_sources ||= []
pending_sources << source
end
end
end
if pending_sources
fiber_vars = get_fiber_variables
parent_task.async do
trace&.dataloader_spawn_source_fiber(pending_sources)
set_fiber_variables(fiber_vars)
Fiber[:graphql_dataloader_next_tick] = condition
pending_sources.each do |s|
trace&.begin_dataloader_source(s)
s.run_pending_keys
trace&.end_dataloader_source(s)
end
cleanup_fiber
trace&.dataloader_fiber_exit
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/dataloader/request.rb | lib/graphql/dataloader/request.rb | # frozen_string_literal: true
module GraphQL
class Dataloader
# @see Source#request which returns an instance of this
class Request
def initialize(source, key)
@source = source
@key = key
end
# Call this method to cause the current Fiber to wait for the results of this request.
#
# @return [Object] the object loaded for `key`
def load
@source.load(@key)
end
def load_with_deprecation_warning
warn("Returning `.request(...)` from GraphQL::Dataloader is deprecated, use `.load(...)` instead. (See usage of #{@source} with #{@key.inspect}).")
load
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/dataloader/active_record_source.rb | lib/graphql/dataloader/active_record_source.rb | # frozen_string_literal: true
require "graphql/dataloader/source"
module GraphQL
class Dataloader
class ActiveRecordSource < GraphQL::Dataloader::Source
def initialize(model_class, find_by: model_class.primary_key)
@model_class = model_class
@find_by = find_by
@find_by_many = find_by.is_a?(Array)
if @find_by_many
@type_for_column = @find_by.map { |fb| @model_class.type_for_attribute(fb) }
else
@type_for_column = @model_class.type_for_attribute(@find_by)
end
end
def result_key_for(requested_key)
normalize_fetch_key(requested_key)
end
def normalize_fetch_key(requested_key)
if @find_by_many
requested_key.each_with_index.map do |k, idx|
@type_for_column[idx].cast(k)
end
else
@type_for_column.cast(requested_key)
end
end
def fetch(record_ids)
records = @model_class.where(@find_by => record_ids)
record_lookup = {}
if @find_by_many
records.each do |r|
key = @find_by.map { |fb| r.public_send(fb) }
record_lookup[key] = r
end
else
records.each { |r| record_lookup[r.public_send(@find_by)] = r }
end
record_ids.map { |id| record_lookup[id] }
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/dataloader/request_all.rb | lib/graphql/dataloader/request_all.rb | # frozen_string_literal: true
module GraphQL
class Dataloader
# @see Source#request_all which returns an instance of this.
class RequestAll < Request
def initialize(source, keys)
@source = source
@keys = keys
end
# Call this method to cause the current Fiber to wait for the results of this request.
#
# @return [Array<Object>] One object for each of `keys`
def load
@source.load_all(@keys)
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/generators/graphql/object_generator.rb | lib/generators/graphql/object_generator.rb | # frozen_string_literal: true
require 'generators/graphql/type_generator'
require 'generators/graphql/field_extractor'
module Graphql
module Generators
# Generate an object type by name,
# with the specified fields.
#
# ```
# rails g graphql:object PostType name:String!
# ```
#
# Add the Node interface with `--node`.
class ObjectGenerator < TypeGeneratorBase
desc "Create a GraphQL::ObjectType with the given name and fields." \
"If the given type name matches an existing ActiveRecord model, the generated type will automatically include fields for the models database columns."
source_root File.expand_path('../templates', __FILE__)
include FieldExtractor
class_option :node,
type: :boolean,
default: false,
desc: "Include the Relay Node interface"
def self.normalize_type_expression(type_expression, mode:, null: true)
case type_expression.camelize
when "Text", "Citext"
["String", null]
when "Decimal"
["Float", null]
when "DateTime", "Datetime"
["GraphQL::Types::ISO8601DateTime", null]
when "Date"
["GraphQL::Types::ISO8601Date", null]
when "Json", "Jsonb", "Hstore"
["GraphQL::Types::JSON", null]
else
super
end
end
private
def graphql_type
"object"
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/generators/graphql/core.rb | lib/generators/graphql/core.rb | # frozen_string_literal: true
require 'rails/generators/base'
module Graphql
module Generators
module Core
def self.included(base)
base.send(
:class_option,
:directory,
type: :string,
default: "app/graphql",
desc: "Directory where generated files should be saved"
)
end
def insert_root_type(type, name)
log :add_root_type, type
sentinel = /< GraphQL::Schema\s*\n/m
in_root do
if File.exist?(schema_file_path)
inject_into_file schema_file_path, " #{type}(Types::#{name})\n", after: sentinel, verbose: false, force: false
end
end
end
def schema_file_path
"#{options[:directory]}/#{schema_name.underscore}.rb"
end
def create_dir(dir)
empty_directory(dir)
if !options[:skip_keeps]
create_file("#{dir}/.keep")
end
end
def module_namespacing_when_supported
if defined?(module_namespacing)
module_namespacing { yield }
else
yield
end
end
private
def schema_name
@schema_name ||= begin
if options[:schema]
options[:schema]
else
"#{parent_name}Schema"
end
end
end
def parent_name
require File.expand_path("config/application", destination_root)
if Rails.application.class.respond_to?(:module_parent_name)
Rails.application.class.module_parent_name
else
Rails.application.class.parent_name
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/generators/graphql/orm_mutations_base.rb | lib/generators/graphql/orm_mutations_base.rb | # frozen_string_literal: true
require 'rails/generators'
require 'rails/generators/named_base'
require_relative 'core'
module Graphql
module Generators
# TODO: What other options should be supported?
#
# @example Generate a `GraphQL::Schema::RelayClassicMutation` by name
# rails g graphql:mutation CreatePostMutation
class OrmMutationsBase < Rails::Generators::NamedBase
include Core
include Rails::Generators::ResourceHelpers
desc "Create a Relay Classic mutation by name"
class_option :orm, banner: "NAME", type: :string, required: true,
desc: "ORM to generate the controller for"
class_option :namespaced_types,
type: :boolean,
required: false,
default: false,
banner: "Namespaced",
desc: "If the generated types will be namespaced"
def create_mutation_file
template "mutation_#{operation_type}.erb", File.join(options[:directory], "/mutations/", class_path, "#{file_name}_#{operation_type}.rb")
sentinel = /class .*MutationType\s*<\s*[^\s]+?\n/m
in_root do
path = "#{options[:directory]}/types/mutation_type.rb"
invoke "graphql:install:mutation_root" unless File.exist?(path)
inject_into_file "#{options[:directory]}/types/mutation_type.rb", " field :#{file_name}_#{operation_type}, mutation: Mutations::#{class_name}#{operation_type.classify}\n", after: sentinel, verbose: false, force: false
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/generators/graphql/type_generator.rb | lib/generators/graphql/type_generator.rb | # frozen_string_literal: true
require 'rails/generators'
require 'rails/generators/base'
require 'graphql'
require 'active_support'
require 'active_support/core_ext/string/inflections'
require_relative 'core'
module Graphql
module Generators
class TypeGeneratorBase < Rails::Generators::NamedBase
include Core
class_option :namespaced_types,
type: :boolean,
required: false,
default: false,
banner: "Namespaced",
desc: "If the generated types will be namespaced"
argument :custom_fields,
type: :array,
default: [],
banner: "name:type name:type ...",
desc: "Fields for this object (type may be expressed as Ruby or GraphQL)"
attr_accessor :graphql_type
def create_type_file
template "#{graphql_type}.erb", "#{options[:directory]}/types#{subdirectory}/#{type_file_name}.rb"
end
# Take a type expression in any combination of GraphQL or Ruby styles
# and return it in a specified output style
# TODO: nullability / list with `mode: :graphql` doesn't work
# @param type_expresson [String]
# @param mode [Symbol]
# @param null [Boolean]
# @return [(String, Boolean)] The type expression, followed by `null:` value
def self.normalize_type_expression(type_expression, mode:, null: true)
if type_expression.start_with?("!")
normalize_type_expression(type_expression[1..-1], mode: mode, null: false)
elsif type_expression.end_with?("!")
normalize_type_expression(type_expression[0..-2], mode: mode, null: false)
elsif type_expression.start_with?("[") && type_expression.end_with?("]")
name, is_null = normalize_type_expression(type_expression[1..-2], mode: mode, null: null)
["[#{name}]", is_null]
elsif type_expression.end_with?("Type")
normalize_type_expression(type_expression[0..-5], mode: mode, null: null)
elsif type_expression.start_with?("Types::")
normalize_type_expression(type_expression[7..-1], mode: mode, null: null)
elsif type_expression.start_with?("types.")
normalize_type_expression(type_expression[6..-1], mode: mode, null: null)
else
case mode
when :ruby
case type_expression
when "Int"
["Integer", null]
when "Integer", "Float", "Boolean", "String", "ID"
[type_expression, null]
else
["Types::#{type_expression.camelize}Type", null]
end
when :graphql
[type_expression.camelize, null]
else
raise "Unexpected normalize mode: #{mode}"
end
end
end
private
# @return [String] The user-provided type name, normalized to Ruby code
def type_ruby_name
@type_ruby_name ||= self.class.normalize_type_expression(name, mode: :ruby)[0]
end
# @return [String] The user-provided type name, as a GraphQL name
def type_graphql_name
@type_graphql_name ||= self.class.normalize_type_expression(name, mode: :graphql)[0]
end
# @return [String] The user-provided type name, as a file name (without extension)
def type_file_name
@type_file_name ||= "#{type_graphql_name}Type".underscore
end
# @return [Array<NormalizedField>] User-provided fields, in `(name, Ruby type name)` pairs
def normalized_fields
@normalized_fields ||= fields.map { |f|
name, raw_type = f.split(":", 2)
type_expr, null = self.class.normalize_type_expression(raw_type, mode: :ruby)
NormalizedField.new(name, type_expr, null)
}
end
def ruby_class_name
class_prefix =
if options[:namespaced_types]
"#{graphql_type.pluralize.camelize}::"
else
""
end
@ruby_class_name || class_prefix + type_ruby_name.sub(/^Types::/, "")
end
def subdirectory
if options[:namespaced_types]
"/#{graphql_type.pluralize}"
else
""
end
end
class NormalizedField
def initialize(name, type_expr, null)
@name = name
@type_expr = type_expr
@null = null
end
def to_object_field
"field :#{@name}, #{@type_expr}#{@null ? '' : ', null: false'}"
end
def to_input_argument
"argument :#{@name}, #{@type_expr}, required: false"
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/generators/graphql/field_extractor.rb | lib/generators/graphql/field_extractor.rb | # frozen_string_literal: true
require 'rails/generators/base'
module Graphql
module Generators
module FieldExtractor
def fields
columns = []
columns += (klass&.columns&.map { |c| generate_column_string(c) } || [])
columns + custom_fields
end
def generate_column_string(column)
name = column.name
required = column.null ? "" : "!"
type = column_type_string(column)
"#{name}:#{required}#{type}"
end
def column_type_string(column)
column.name == "id" ? "ID" : column.type.to_s.camelize
end
def klass
@klass ||= Module.const_get(name.camelize)
rescue NameError
@klass = nil
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/generators/graphql/relay_generator.rb | lib/generators/graphql/relay_generator.rb | # frozen_string_literal: true
require 'rails/generators'
require 'rails/generators/base'
require_relative 'core'
require_relative 'relay'
module Graphql
module Generators
class RelayGenerator < Rails::Generators::Base
include Core
include Relay
desc "Add base types and fields for Relay-style nodes and connections"
source_root File.expand_path('../templates', __FILE__)
def install_relay
super
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/generators/graphql/mutation_create_generator.rb | lib/generators/graphql/mutation_create_generator.rb | # frozen_string_literal: true
require_relative 'orm_mutations_base'
module Graphql
module Generators
# TODO: What other options should be supported?
#
# @example Generate a `GraphQL::Schema::RelayClassicMutation` by name
# rails g graphql:mutation CreatePostMutation
class MutationCreateGenerator < OrmMutationsBase
desc "Scaffold a Relay Classic ORM create mutation for the given model class"
source_root File.expand_path('../templates', __FILE__)
private
def operation_type
"create"
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/generators/graphql/union_generator.rb | lib/generators/graphql/union_generator.rb | # frozen_string_literal: true
require 'generators/graphql/type_generator'
module Graphql
module Generators
# Generate a union type by name
# with the specified member types.
#
# ```
# rails g graphql:union SearchResultType ImageType AudioType
# ```
class UnionGenerator < TypeGeneratorBase
desc "Create a GraphQL::UnionType with the given name and possible types"
source_root File.expand_path('../templates', __FILE__)
argument :possible_types,
type: :array,
default: [],
banner: "type type ...",
desc: "Possible types for this union (expressed as Ruby or GraphQL)"
private
def graphql_type
"union"
end
def normalized_possible_types
custom_fields.map { |t| self.class.normalize_type_expression(t, mode: :ruby)[0] }
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/generators/graphql/relay.rb | lib/generators/graphql/relay.rb | # frozen_string_literal: true
module Graphql
module Generators
module Relay
def install_relay
# Add Node, `node(id:)`, and `nodes(ids:)`
template("node_type.erb", "#{options[:directory]}/types/node_type.rb")
in_root do
fields = <<-RUBY
field :node, Types::NodeType, null: true, description: "Fetches an object given its ID." do
argument :id, ID, required: true, description: "ID of the object."
end
def node(id:)
context.schema.object_from_id(id, context)
end
field :nodes, [Types::NodeType, null: true], null: true, description: "Fetches a list of objects given a list of IDs." do
argument :ids, [ID], required: true, description: "IDs of the objects."
end
def nodes(ids:)
ids.map { |id| context.schema.object_from_id(id, context) }
end
RUBY
inject_into_file "#{options[:directory]}/types/query_type.rb", fields, after: /class .*QueryType\s*<\s*[^\s]+?\n/m, force: false
end
# Add connections and edges
template("base_connection.erb", "#{options[:directory]}/types/base_connection.rb")
template("base_edge.erb", "#{options[:directory]}/types/base_edge.rb")
connectionable_type_files = {
"#{options[:directory]}/types/base_object.rb" => /class .*BaseObject\s*<\s*[^\s]+?\n/m,
"#{options[:directory]}/types/base_union.rb" => /class .*BaseUnion\s*<\s*[^\s]+?\n/m,
"#{options[:directory]}/types/base_interface.rb" => /include GraphQL::Schema::Interface\n/m,
}
in_root do
connectionable_type_files.each do |type_class_file, sentinel|
inject_into_file type_class_file, " connection_type_class(Types::BaseConnection)\n", after: sentinel, force: false
inject_into_file type_class_file, " edge_type_class(Types::BaseEdge)\n", after: sentinel, force: false
end
end
# Add object ID hooks & connection plugin
schema_code = <<-RUBY
# Relay-style Object Identification:
# Return a string UUID for `object`
def self.id_from_object(object, type_definition, query_ctx)
# For example, use Rails' GlobalID library (https://github.com/rails/globalid):
object.to_gid_param
end
# Given a string UUID, find the object
def self.object_from_id(global_id, query_ctx)
# For example, use Rails' GlobalID library (https://github.com/rails/globalid):
GlobalID.find(global_id)
end
RUBY
inject_into_file schema_file_path, schema_code, before: /^end\n/m, force: false
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/generators/graphql/enum_generator.rb | lib/generators/graphql/enum_generator.rb | # frozen_string_literal: true
require 'generators/graphql/type_generator'
module Graphql
module Generators
# Generate an enum type by name, with the given values.
# To add a `value:` option, add another value after a `:`.
#
# ```
# rails g graphql:enum ProgrammingLanguage RUBY PYTHON PERL PERL6:"PERL"
# ```
class EnumGenerator < TypeGeneratorBase
desc "Create a GraphQL::EnumType with the given name and values"
source_root File.expand_path('../templates', __FILE__)
private
def graphql_type
"enum"
end
def prepared_values
custom_fields.map { |v| v.split(":", 2) }
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/generators/graphql/mutation_update_generator.rb | lib/generators/graphql/mutation_update_generator.rb | # frozen_string_literal: true
require_relative 'orm_mutations_base'
module Graphql
module Generators
# TODO: What other options should be supported?
#
# @example Generate a `GraphQL::Schema::RelayClassicMutation` by name
# rails g graphql:mutation UpdatePostMutation
class MutationUpdateGenerator < OrmMutationsBase
desc "Scaffold a Relay Classic ORM update mutation for the given model class"
source_root File.expand_path('../templates', __FILE__)
private
def operation_type
"update"
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/generators/graphql/mutation_generator.rb | lib/generators/graphql/mutation_generator.rb | # frozen_string_literal: true
require 'rails/generators'
require 'rails/generators/named_base'
require_relative 'core'
module Graphql
module Generators
# TODO: What other options should be supported?
#
# @example Generate a `GraphQL::Schema::RelayClassicMutation` by name
# rails g graphql:mutation CreatePostMutation
class MutationGenerator < Rails::Generators::NamedBase
include Core
desc "Create a Relay Classic mutation by name"
source_root File.expand_path('../templates', __FILE__)
def create_mutation_file
template "mutation.erb", File.join(options[:directory], "/mutations/", class_path, "#{file_name}.rb")
sentinel = /class .*MutationType\s*<\s*[^\s]+?\n/m
in_root do
path = "#{options[:directory]}/types/mutation_type.rb"
invoke "graphql:install:mutation_root" unless File.exist?(path)
inject_into_file "#{options[:directory]}/types/mutation_type.rb", " field :#{file_name}, mutation: Mutations::#{class_name}\n", after: sentinel, verbose: false, force: false
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/generators/graphql/scalar_generator.rb | lib/generators/graphql/scalar_generator.rb | # frozen_string_literal: true
require 'generators/graphql/type_generator'
module Graphql
module Generators
# Generate a scalar type by given name.
#
# ```
# rails g graphql:scalar Date
# ```
class ScalarGenerator < TypeGeneratorBase
desc "Create a GraphQL::ScalarType with the given name"
source_root File.expand_path('../templates', __FILE__)
private
def graphql_type
"scalar"
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/generators/graphql/interface_generator.rb | lib/generators/graphql/interface_generator.rb | # frozen_string_literal: true
require 'generators/graphql/type_generator'
module Graphql
module Generators
# Generate an interface type by name,
# with the specified fields.
#
# ```
# rails g graphql:interface NamedEntityType name:String!
# ```
class InterfaceGenerator < TypeGeneratorBase
desc "Create a GraphQL::InterfaceType with the given name and fields"
source_root File.expand_path('../templates', __FILE__)
private
def graphql_type
"interface"
end
def fields
custom_fields
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/generators/graphql/mutation_delete_generator.rb | lib/generators/graphql/mutation_delete_generator.rb | # frozen_string_literal: true
require_relative 'orm_mutations_base'
module Graphql
module Generators
# TODO: What other options should be supported?
#
# @example Generate a `GraphQL::Schema::RelayClassicMutation` by name
# rails g graphql:mutation DeletePostMutation
class MutationDeleteGenerator < OrmMutationsBase
desc "Scaffold a Relay Classic ORM delete mutation for the given model class"
source_root File.expand_path('../templates', __FILE__)
private
def operation_type
"delete"
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/generators/graphql/input_generator.rb | lib/generators/graphql/input_generator.rb | # frozen_string_literal: true
require 'generators/graphql/type_generator'
require 'generators/graphql/field_extractor'
module Graphql
module Generators
# Generate an input type by name,
# with the specified fields.
#
# ```
# rails g graphql:object PostType name:string!
# ```
class InputGenerator < TypeGeneratorBase
desc "Create a GraphQL::InputObjectType with the given name and fields"
source_root File.expand_path('../templates', __FILE__)
include FieldExtractor
def self.normalize_type_expression(type_expression, mode:, null: true)
case type_expression.camelize
when "Text", "Citext"
["String", null]
when "Decimal"
["Float", null]
when "DateTime", "Datetime"
["GraphQL::Types::ISO8601DateTime", null]
when "Date"
["GraphQL::Types::ISO8601Date", null]
when "Json", "Jsonb", "Hstore"
["GraphQL::Types::JSON", null]
else
super
end
end
private
def graphql_type
"input"
end
def type_ruby_name
super.gsub(/Type\z/, "InputType")
end
def type_file_name
super.gsub(/_type\z/, "_input_type")
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/generators/graphql/install_generator.rb | lib/generators/graphql/install_generator.rb | # frozen_string_literal: true
require 'rails/generators'
require 'rails/generators/base'
require_relative 'core'
require_relative 'relay'
module Graphql
module Generators
# Add GraphQL to a Rails app with `rails g graphql:install`.
#
# Setup a folder structure for GraphQL:
#
# ```
# - app/
# - graphql/
# - resolvers/
# - types/
# - base_argument.rb
# - base_field.rb
# - base_enum.rb
# - base_input_object.rb
# - base_interface.rb
# - base_object.rb
# - base_scalar.rb
# - base_union.rb
# - query_type.rb
# - loaders/
# - mutations/
# - base_mutation.rb
# - {app_name}_schema.rb
# ```
#
# (Add `.gitkeep`s by default, support `--skip-keeps`)
#
# Add a controller for serving GraphQL queries:
#
# ```
# app/controllers/graphql_controller.rb
# ```
#
# Add a route for that controller:
#
# ```ruby
# # config/routes.rb
# post "/graphql", to: "graphql#execute"
# ```
#
# Add ActiveRecord::QueryLogs metadata:
# ```ruby
# current_graphql_operation: -> { GraphQL::Current.operation_name },
# current_graphql_field: -> { GraphQL::Current.field&.path },
# current_dataloader_source: -> { GraphQL::Current.dataloader_source_class },
# ```
#
# Accept a `--batch` option which adds `GraphQL::Batch` setup.
#
# Use `--skip-graphiql` to skip `graphiql-rails` installation.
#
# TODO: also add base classes
class InstallGenerator < Rails::Generators::Base
include Core
include Relay
desc "Install GraphQL folder structure and boilerplate code"
source_root File.expand_path('../templates', __FILE__)
class_option :schema,
type: :string,
default: nil,
desc: "Name for the schema constant (default: {app_name}Schema)"
class_option :skip_keeps,
type: :boolean,
default: false,
desc: "Skip .keep files for source control"
class_option :skip_graphiql,
type: :boolean,
default: false,
desc: "Skip graphiql-rails installation"
class_option :skip_mutation_root_type,
type: :boolean,
default: false,
desc: "Skip creation of the mutation root type"
class_option :relay,
type: :boolean,
default: true,
desc: "Include installation of Relay conventions (nodes, connections, edges)"
class_option :batch,
type: :boolean,
default: false,
desc: "Include GraphQL::Batch installation"
class_option :playground,
type: :boolean,
default: false,
desc: "Use GraphQL Playground over Graphiql as IDE"
class_option :skip_query_logs,
type: :boolean,
default: false,
desc: "Skip ActiveRecord::QueryLogs hooks in config/application.rb"
# These two options are taken from Rails' own generators'
class_option :api,
type: :boolean,
desc: "Preconfigure smaller stack for API only apps"
def create_folder_structure
create_dir("#{options[:directory]}/types")
template("schema.erb", schema_file_path)
["base_object", "base_argument", "base_field", "base_enum", "base_input_object", "base_interface", "base_scalar", "base_union"].each do |base_type|
template("#{base_type}.erb", "#{options[:directory]}/types/#{base_type}.rb")
end
# All resolvers are defined as living in their own module, including this class.
template("base_resolver.erb", "#{options[:directory]}/resolvers/base_resolver.rb")
# Note: You can't have a schema without the query type, otherwise introspection breaks
template("query_type.erb", "#{options[:directory]}/types/query_type.rb")
insert_root_type('query', 'QueryType')
invoke "graphql:install:mutation_root" unless options.skip_mutation_root_type?
template("graphql_controller.erb", "app/controllers/graphql_controller.rb")
route('post "/graphql", to: "graphql#execute"')
if options[:batch]
gem("graphql-batch")
create_dir("#{options[:directory]}/loaders")
end
if options.api?
say("Skipped graphiql, as this rails project is API only")
say(" You may wish to use GraphiQL.app for development: https://github.com/skevy/graphiql-app")
elsif !options[:skip_graphiql]
# `gem(...)` uses `gsub_file(...)` under the hood, which is a no-op for `rails destroy...` (when `behavior == :revoke`).
# So handle that case by calling `gsub_file` with `force: true`.
if behavior == :invoke && !File.read(Rails.root.join("Gemfile")).include?("graphiql-rails")
gem("graphiql-rails", group: :development)
elsif behavior == :revoke
gemfile_pattern = /\n\s*gem ('|")graphiql-rails('|"), :?group(:| =>) :development/
gsub_file Rails.root.join("Gemfile"), gemfile_pattern, "", { force: true }
end
# This is a little cheat just to get cleaner shell output:
log :route, 'graphiql-rails'
shell.mute do
# Rails 5.2 has better support for `route`?
if Rails::VERSION::STRING > "5.2"
route <<-RUBY
if Rails.env.development?
mount GraphiQL::Rails::Engine, at: "/graphiql", graphql_path: "/graphql"
end
RUBY
else
route <<-RUBY
if Rails.env.development?
mount GraphiQL::Rails::Engine, at: "/graphiql", graphql_path: "/graphql"
end
RUBY
end
end
end
if options[:playground]
gem("graphql_playground-rails", group: :development)
log :route, 'graphql_playground-rails'
shell.mute do
if Rails::VERSION::STRING > "5.2"
route <<-RUBY
if Rails.env.development?
mount GraphqlPlayground::Rails::Engine, at: "/playground", graphql_path: "/graphql"
end
RUBY
else
route <<-RUBY
if Rails.env.development?
mount GraphqlPlayground::Rails::Engine, at: "/playground", graphql_path: "/graphql"
end
RUBY
end
end
end
if options[:relay]
install_relay
end
if !options[:skip_query_logs]
config_file = "config/application.rb"
current_app_rb = File.read(Rails.root.join(config_file))
existing_log_tags_pattern = /config.active_record.query_log_tags = \[\n?(\s*:[a-z_]+,?\s*\n?|\s*#[^\]]*\n)*/m
existing_log_tags = existing_log_tags_pattern.match(current_app_rb)
if existing_log_tags && behavior == :invoke
code = <<-RUBY
# GraphQL-Ruby query log tags:
current_graphql_operation: -> { GraphQL::Current.operation_name },
current_graphql_field: -> { GraphQL::Current.field&.path },
current_dataloader_source: -> { GraphQL::Current.dataloader_source_class },
RUBY
if !existing_log_tags.to_s.end_with?(",")
code = ",\n#{code} "
end
# Try to insert this code _after_ any plain symbol entries in the array of query log tags:
after_code = existing_log_tags_pattern
else
code = <<-RUBY
config.active_record.query_log_tags_enabled = true
config.active_record.query_log_tags = [
# Rails query log tags:
:application, :controller, :action, :job,
# GraphQL-Ruby query log tags:
current_graphql_operation: -> { GraphQL::Current.operation_name },
current_graphql_field: -> { GraphQL::Current.field&.path },
current_dataloader_source: -> { GraphQL::Current.dataloader_source_class },
]
RUBY
after_code = "class Application < Rails::Application\n"
end
insert_into_file(config_file, code, after: after_code)
end
if gemfile_modified?
say "Gemfile has been modified, make sure you `bundle install`"
end
end
private
def gemfile_modified?
@gemfile_modified
end
def gem(*args)
@gemfile_modified = true
super(*args)
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/generators/graphql/loader_generator.rb | lib/generators/graphql/loader_generator.rb | # frozen_string_literal: true
require 'rails/generators'
require "rails/generators/named_base"
require_relative "core"
module Graphql
module Generators
# @example Generate a `GraphQL::Batch` loader by name.
# rails g graphql:loader RecordLoader
class LoaderGenerator < Rails::Generators::NamedBase
include Core
desc "Create a GraphQL::Batch::Loader by name"
source_root File.expand_path('../templates', __FILE__)
def create_loader_file
template "loader.erb", "#{options[:directory]}/loaders/#{file_path}.rb"
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/generators/graphql/install/mutation_root_generator.rb | lib/generators/graphql/install/mutation_root_generator.rb | # frozen_string_literal: true
require "rails/generators/base"
require_relative "../core"
module Graphql
module Generators
module Install
class MutationRootGenerator < Rails::Generators::Base
include Core
desc "Create mutation base type, mutation root type, and adds the latter to the schema"
source_root File.expand_path('../templates', __FILE__)
class_option :schema,
type: :string,
default: nil,
desc: "Name for the schema constant (default: {app_name}Schema)"
class_option :skip_keeps,
type: :boolean,
default: false,
desc: "Skip .keep files for source control"
def generate
create_dir("#{options[:directory]}/mutations")
template("base_mutation.erb", "#{options[:directory]}/mutations/base_mutation.rb", { skip: true })
template("mutation_type.erb", "#{options[:directory]}/types/mutation_type.rb", { skip: true })
insert_root_type('mutation', 'MutationType')
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/guides/_tasks/site.rb | guides/_tasks/site.rb | # frozen_string_literal: true
require "yard"
require "webrick"
namespace :apidocs do
desc "Fetch a gem version from RubyGems, build the docs"
task :gen_version, [:version] do |t, args|
# GITHUB_REF comes from GitHub Actions
version = args[:version] || ENV["GITHUB_REF"] || raise("A version is required")
puts "Building docs for #{version}"
# GitHub Actions gives the full tag name
if version.start_with?("refs/tags/")
version = version[10..-1]
end
if version.start_with?("v")
version = version[1..-1]
end
Dir.mktmpdir do
puts "Fetching graphql-#{version}"
system("gem fetch graphql --version=#{version}")
system("gem unpack graphql-#{version}.gem")
system("rm graphql-#{version}.gem")
Dir.chdir("graphql-#{version}") do
# Copy it into gh-pages for publishing
# and locally for previewing
push_dest = File.expand_path("../gh-pages/api-doc/#{version}")
local_dest = File.expand_path("../guides/_site/api-doc/#{version}")
puts "Creating directories: #{push_dest.inspect}, #{local_dest.inspect}"
FileUtils.mkdir_p(push_dest)
FileUtils.mkdir_p(local_dest)
system("yardoc")
puts "Copying from #{Dir.pwd}/doc to #{push_dest}"
copy_entry "doc", push_dest
puts "Copying from #{Dir.pwd}/doc to #{local_dest}"
copy_entry "doc", local_dest
end
end
puts "Successfully generated docs for #{version}"
end
end
namespace :site do
desc "View the documentation site locally"
task serve: [] do # if you need api docs, add `:build_doc` to the list of dependencies
require "jekyll"
options = {
"source" => File.expand_path("guides"),
"destination" => File.expand_path("guides/_site"),
"watch" => true,
"serving" => true
}
# Generate the site in server mode.
puts "Running Jekyll..."
Jekyll::Commands::Build.process(options)
Jekyll::Commands::Serve.process(options)
end
desc "Get the gh-pages branch locally, make sure it's up-to-date"
task :fetch_latest do
# Ensure the gh-pages dir exists so we can generate into it.
puts "Checking for gh-pages dir..."
unless File.exist?("./gh-pages")
puts "Creating gh-pages dir..."
sh "git clone git@github.com:rmosolgo/graphql-ruby gh-pages"
end
# Ensure latest gh-pages branch history.
Dir.chdir("gh-pages") do
sh "git checkout gh-pages"
sh "git pull origin gh-pages"
end
end
desc "Remove all generated HTML (making space to re-generate)"
task :clean_html do
# Proceed to purge all files in case we removed a file in this release.
puts "Cleaning gh-pages directory..."
purge_exclude = [
'gh-pages/.',
'gh-pages/..',
'gh-pages/.git',
'gh-pages/.gitignore',
'gh-pages/api-doc',
]
FileList["gh-pages/{*,.*}"].exclude(*purge_exclude).each do |path|
sh "rm -rf #{path}"
end
end
desc "Build guides/ into gh-pages/ with Jekyll"
task :build_html do
# Copy site to gh-pages dir.
puts "Building site into gh-pages branch..."
ENV['JEKYLL_ENV'] = 'production'
require "jekyll"
Jekyll::Commands::Build.process({
"source" => File.expand_path("guides"),
"destination" => File.expand_path("gh-pages"),
"sass" => { "style" => "compressed" }
})
File.write('gh-pages/.nojekyll', "Prevent GitHub from running Jekyll")
end
desc "Commit new docs"
task :commit_changes do
puts "Committing and pushing to GitHub Pages..."
sha = `git rev-parse HEAD`.strip
Dir.chdir('gh-pages') do
system "git status"
system "git add ."
system "git status"
system "git commit --allow-empty -m 'Updating to #{sha}.'"
end
end
desc "Push docs to gh-pages branch"
task :push_commit do
Dir.chdir('gh-pages') do
sh "git push origin gh-pages"
end
end
desc "Commit the local site to the gh-pages branch and publish to GitHub Pages"
task publish: [:build_doc, :update_search_index, :fetch_latest, :clean_html, :build_html, :commit_changes, :push_commit]
YARD::Rake::YardocTask.new(:prepare_yardoc)
task build_doc: :prepare_yardoc do
require_relative "../../lib/graphql/version"
def to_rubydoc_url(path)
"/api-doc/#{GraphQL::VERSION}/" + path
.gsub("::", "/") # namespaces
.sub(/#(.+)$/, "#\\1-instance_method") # instance methods
.sub(/\.(.+)$/, "#\\1-class_method") # class methods
end
DOC_TEMPLATE = <<-PAGE
---
layout: doc_stub
search: true
title: %{title}
url: %{url}
rubydoc_url: %{url}
doc_stub: true
---
%{documentation}
PAGE
puts "Preparing YARD docs @ v#{GraphQL::VERSION} for search index..."
registry = YARD::Registry.load!(".yardoc")
files_target = "guides/yardoc"
FileUtils.rm_rf(files_target)
FileUtils.mkdir_p(files_target)
# Get docs for all classes and modules
docs = registry.all(:class, :module)
docs.each do |code_object|
begin
# Skip private classes and modules
if code_object.visibility == :private
next
end
rubydoc_url = to_rubydoc_url(code_object.path)
page_content = DOC_TEMPLATE % {
title: code_object.path,
url: rubydoc_url,
documentation: code_object.format.gsub(/-{2,}/, " ").gsub(/^\s+/, ""),
}
filename = code_object.path.gsub(/\W+/, "_")
filepath = "guides/yardoc/#{filename}.md"
File.write(filepath, page_content)
rescue StandardError => err
puts "Error on: #{code_object.path}"
puts err
puts err.backtrace
end
end
puts "Wrote #{docs.size} YARD docs to #{files_target}."
end
desc "Update the Algolia search index used for graphql-ruby.org"
task :update_search_index do
if !ENV["ALGOLIA_API_KEY"]
warn("Can't update search index without ALGOLIA_API_KEY; Search will be out-of-date.")
else
system("bundle exec jekyll algolia push --source=./guides")
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/guides/_plugins/api_doc.rb | guides/_plugins/api_doc.rb | # frozen_string_literal: true
require_relative "../../lib/graphql/version"
require "kramdown"
module GraphQLSite
API_DOC_ROOT = "/api-doc/#{GraphQL::VERSION}/"
module APIDoc
def api_doc(input)
if !input.start_with?("GraphQL")
ruby_ident = "GraphQL::#{input}"
else
ruby_ident = input
end
doc_path = ruby_ident
.gsub("::", "/") # namespaces
.sub(/#(.+)$/, "#\\1-instance_method") # instance methods
.sub(/\.(.+)$/, "#\\1-class_method") # class methods
%|<a href="#{API_DOC_ROOT}#{doc_path}" target="_blank" title="API docs for #{ruby_ident}"><code>#{input}</code></a>|
end
def link_to_img(img_path, img_title)
full_img_path = "#{@context.registers[:site].baseurl}#{img_path}"
<<-HTML
<a href="#{full_img_path}" target="_blank" class="img-link">
<img src="#{full_img_path}" title="#{img_title}" alt="#{img_title}" />
</a>
HTML
end
end
class APIDocRoot < Liquid::Tag
def render(context)
API_DOC_ROOT
end
end
class CalloutBlock < Liquid::Block
def initialize(tag_name, callout_class, tokens)
super
@callout_class = callout_class.strip
end
def render(context)
raw_text = super
site = context.registers[:site]
converter = site.find_converter_instance(::Jekyll::Converters::Markdown)
rendered_text = converter.convert(raw_text)
heading = case @callout_class
when "warning"
"⚠ Heads up!"
else
raise ArgumentError, "Unhandled callout class: #{@callout_class.inspect}"
end
%|<div class="callout callout-#{@callout_class}"><p class="heading">#{heading}</p>#{rendered_text}</div>|
end
end
class OpenAnIssue < Liquid::Tag
def initialize(tag_name, issue_info, tokens)
title, body = issue_info.split(",")
# remove whitespace and quotes if value is present
@title = strip_arg(title)
@body = strip_arg(body)
end
def render(context)
%|<a href="https://github.com/rmosolgo/graphql-ruby/issues/new?title=#{@title}#{@body ? "&body=#{@body}" : ""}" target="_blank">open an issue</a>|
end
private
def strip_arg(text)
text && text.strip[1..-2]
end
end
# Build a URL relative to `site.baseurl`,
# asserting that the page exists.
class InternalLink < Liquid::Tag
GUIDES_ROOT = "guides/"
def initialize(tag_name, guide_info, tokens)
text, path = guide_info.split(",")
# remove whitespace and quotes if value is present
@text = strip_arg(text)
@path = strip_arg(path)
if @path && @path.start_with?("/")
@path = @path[1..-1]
end
if !exist?(@path)
raise "Internal link failed, couldn't find file for: #{path}"
end
end
def render(context)
<<-HTML.chomp
<a href="#{context["site"]["baseurl"]}/#{@path}">#{@text}</a>
HTML
end
private
def strip_arg(text)
text && text.strip[1..-2]
end
POSSIBLE_EXTENSIONS = [".html", ".md"]
def exist?(path)
filepath = GUIDES_ROOT + path.split("#").first
filepath = filepath.sub(".html", "")
POSSIBLE_EXTENSIONS.any? { |ext| File.exist?(filepath + ext) }
end
end
class TableOfContents < Liquid::Tag
def render(context)
headers = context["page"]["content"].scan(/^##+[^\n]+$/m)
section_count = 0
current_table = header_table = [nil]
prev_depth = nil
headers.each do |h|
header_hashes = h.match(/^#+/)[0]
depth = header_hashes.size
if depth == 2
section_count += 1
end
text = h.gsub(/^#+ /, "")
target = text.downcase
.gsub(/[^a-z0-9_]+/, "-")
.sub(/-$/, "")
.sub(/^-/, "")
rendered_text = Kramdown::Document.new(text, auto_ids: false)
.to_html
.sub("<p>", "")
.sub("</p>", "") # remove wrapping added by kramdown
if prev_depth
if prev_depth > depth
# outdent
current_table = current_table[0]
elsif prev_depth < depth
# indent
new_table = [current_table]
current_table[-1][-1] = new_table
current_table = new_table
else
# same depth
end
end
current_table << [rendered_text, target, []]
prev_depth = depth
end
table_html = "".dup
render_table_into_html(table_html, header_table)
html = <<~HTML
<div class="table-of-contents">
<h3 class="contents-header">Contents</h3>
#{table_html}
</div>
HTML
if section_count == 0
if headers.any?
full_path = "guides/#{context["page"]["path"]}"
warn("No sections identified for #{full_path} -- make sure it's using `## ...` for section headings.")
end
""
else
html
end
end
private
def render_table_into_html(html_str, table)
html_str << "<ol class='contents-list'>"
table.each_with_index do |entry, idx|
if idx == 0
next # parent reference
end
rendered_text, target, child_table = *entry
html_str << "<li class='contents-entry'>"
html_str << "<a href='##{target}'>#{rendered_text}</a>"
if child_table.any?
render_table_into_html(html_str, child_table)
end
html_str << "</li>"
end
html_str << "</ol>"
end
end
end
Liquid::Template.register_filter(GraphQLSite::APIDoc)
Liquid::Template.register_tag("api_doc_root", GraphQLSite::APIDocRoot)
Liquid::Template.register_tag("open_an_issue", GraphQLSite::OpenAnIssue)
Liquid::Template.register_tag("internal_link", GraphQLSite::InternalLink)
Liquid::Template.register_tag("table_of_contents", GraphQLSite::TableOfContents)
Liquid::Template.register_tag('callout', GraphQLSite::CalloutBlock)
Jekyll::Hooks.register :site, :pre_render do |site|
section_pages = Hash.new { |h, k| h[k] = [] }
section_names = []
site.pages.each do |page|
this_section = page.data["section"]
if this_section
this_section_pages = section_pages[this_section]
this_section_pages << page
this_section_pages.sort_by! { |page| page.data["index"] || 100 }
page.data["section_pages"] = this_section_pages
section_names << this_section
end
end
section_names.compact!
section_names.uniq!
all_sections = []
section_names.each do |section_name|
all_sections << {
"name" => section_name,
"overview_page" => section_pages[section_name].first,
}
end
sorted_section_names = site.pages.find { |p| p.data["title"] == "Guides Index" }.data["sections"].map { |s| s["name"] }
all_sections.sort_by! { |s| sorted_section_names.index(s["name"]) }
site.data["all_sections"] = all_sections
end
module Jekyll
module Algolia
module Hooks
def self.before_indexing_each(record, node, context)
record = record.dup
record.delete(:section_pages)
record
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/tasks/performance/optimization_status.rb | tasks/performance/optimization_status.rb | # backtick_javascript: true
klasses = [
Array,
Class,
# Complex,
# Dir,
Enumerable,
Enumerator,
Exception,
Hash,
# Kernel,
Math,
Method,
Module,
Object,
Proc,
Range,
Rational,
Regexp,
Struct,
String,
Time
]
%x{
function getOptimizationStatus(fn) {
var optstatus = %GetOptimizationStatus(fn);
return (optstatus & (1 << 6)) ? "[INTERPRETED]" : "[COMPILED]";
}
function triggerOptAndGetStatus(fn) {
// using try/catch to avoid having to call functions properly
try {
// Fill type-info
fn();
// 2 calls are needed to go from uninitialized -> pre-monomorphic -> monomorphic
fn();
}
catch (e) {}
%OptimizeFunctionOnNextCall(fn);
try {
fn();
}
catch (e) {}
return getOptimizationStatus(fn);
}
}
optimization_status = Hash[klasses.map do |klass|
methods = klass.instance_methods
methods -= Object.instance_methods unless klass == Object
methods -= [:product, :exit, :exit!, :at_exit]
opt_status = Hash[methods.map do |method|
method_func = `#{klass.instance_method(method)}.method`
method_func = `#{method_func}.$$proxy_target || #{method_func}`
[method, `triggerOptAndGetStatus(#{method_func})`]
end]
by_status_grouped = opt_status.group_by {|method, status| status }
as_hash = Hash[by_status_grouped.map do |status, stuff|
list = stuff.map {|val| val[0]}
[status, list]
end]
[klass, as_hash]
end]
puts '----Report----'
optimization_status.sort_by {|klass,_| klass.name}.each do |klass, statuses|
puts "---------------"
puts "Class #{klass}:"
puts "---------------"
statuses.sort_by {|stat,_| stat }.each do |status, methods|
methods.sort.each do |m|
puts " #{status} #{m}"
end
end
end
puts 'done!'
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/tasks/testing/mspec_special_calls.rb | tasks/testing/mspec_special_calls.rb | require 'opal/nodes/call'
require 'opal/ast/builder'
class Opal::Nodes::CallNode
# Rubyspec uses these calls features at runtime.
# We can't do this at runtime, so handle it during compilation
add_special :not_supported_on do |compile_default|
unless arglist.children.include?(s(:sym, :opal))
compile_default.call
end
end
has_xstring = -> node {
next if node.nil? || !node.respond_to?(:type)
node.type == :xstr || (node.children && node.children.any?(&has_xstring))
}
add_special :platform_is_not do |compile_default|
next if arglist.children.include?(s(:sym, :opal))
next if children.any?(&has_xstring)
compile_default.call
end
add_special :platform_is do |compile_default|
if arglist.children.include?(s(:sym, :opal)) || !children.any?(&has_xstring)
compile_default.call
end
end
add_special :requirable_spec_file do |compile_default|
str = DependencyResolver.new(compiler, arglist.children[0]).resolve
compiler.track_require str unless str.nil?
end
end
require 'opal/rewriter'
require 'opal/rewriters/rubyspec/filters_rewriter'
Opal::Rewriter.use Opal::Rubyspec::FiltersRewriter
# When a spec is marked as filtered (most probably non-implemented functionality)
# we need to exclude it from the test suite
# (except of the case with inverted suite specified using INVERT_RUNNING_MODE=true)
#
def opal_filter(filter_name, &block)
unless ENV['INVERT_RUNNING_MODE']
Opal::Rubyspec::FiltersRewriter.instance_eval(&block)
end
end
# When a spec is marked as unsupported we need to exclude it from the test suite.
#
# This filter ignores ENV['INVERT_RUNNING_MODE'],
# unsupported feature is always unsupported.
#
def opal_unsupported_filter(filter_name, &block)
Opal::Rubyspec::FiltersRewriter.instance_eval(&block)
end
Dir[File.expand_path('../../../spec/filters/unsupported/**/*.rb', __FILE__)].each { |f| require f }
Dir[File.expand_path('../../../spec/filters/bugs/**/*.rb', __FILE__)].each { |f| require f }
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/opal.rb | opal/opal.rb | ::Object.require 'opal/base'
::Object.require 'opal/mini'
::Object.require 'corelib/kernel/format'
::Object.require 'corelib/string/encoding'
::Object.autoload :Math, 'corelib/math'
::Object.require 'corelib/complex/base'
::Object.autoload :Complex, 'corelib/complex'
::Object.require 'corelib/rational/base'
::Object.autoload :Rational, 'corelib/rational'
::Object.require 'corelib/time'
::Object.autoload :Struct, 'corelib/struct'
::Object.autoload :Set, 'corelib/set'
::Object.autoload :Dir, 'corelib/dir'
::Object.autoload :File, 'corelib/file'
::Object.require 'corelib/process/base'
::Object.autoload :Process, 'corelib/process'
::Object.autoload :Random, 'corelib/random'
::Object.require 'corelib/unsupported'
::Object.require 'corelib/binding'
::Object.require 'corelib/irb'
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/proc.rb | opal/corelib/proc.rb | # helpers: slice, each_ivar
# backtick_javascript: true
# use_strict: true
class ::Proc < `Function`
`Opal.prop(self.$$prototype, '$$is_proc', true)`
`Opal.prop(self.$$prototype, '$$is_lambda', false)`
def self.new(&block)
unless block
::Kernel.raise ::ArgumentError, 'tried to create a Proc object without a block'
end
block
end
%x{
function $call_lambda(self, args) {
if (self.$$ret) {
try {
return self.apply(null, args);
} catch (err) {
if (err === self.$$ret) {
return err.$v;
} else {
throw err;
}
}
} else {
return self.apply(null, args);
}
}
function $call_proc(self, args) {
if (self.$$brk) {
try {
return Opal.yieldX(self, args);
} catch (err) {
if (err === self.$$brk) {
return err.$v;
} else {
throw err;
}
}
} else {
return Opal.yieldX(self, args);
}
}
}
def call(*args, &block)
%x{
if (block !== nil) self.$$p = block;
if (self.$$is_lambda) return $call_lambda(self, args);
return $call_proc(self, args);
}
end
def >>(other)
::Kernel.proc do |*args, &block|
out = call(*args, &block)
other.call(out)
end
end
def <<(other)
::Kernel.proc do |*args, &block|
out = other.call(*args, &block)
call(out)
end
end
def to_proc
self
end
def lambda?
# This method should tell the user if the proc tricks are unavailable,
# (see Proc#lambda? on ruby docs to find out more).
`!!self.$$is_lambda`
end
def arity
%x{
if (self.$$is_curried) {
return -1;
} else if (self.$$arity != null) {
return self.$$arity;
} else {
return self.length;
}
}
end
def source_location
`if (self.$$is_curried) { return nil; }`
`self.$$source_location` || nil
end
def binding
`if (self.$$is_curried) { #{::Kernel.raise ::ArgumentError, "Can't create Binding"} }`
if defined? ::Binding
::Binding.new(nil, [], `self.$$s`, source_location)
end
end
def parameters(lambda: undefined)
%x{
if (self.$$is_curried) {
return #{[[:rest]]};
} else if (self.$$parameters) {
if (lambda == null ? self.$$is_lambda : lambda) {
return self.$$parameters;
} else {
var result = [], i, length;
for (i = 0, length = self.$$parameters.length; i < length; i++) {
var parameter = self.$$parameters[i];
if (parameter[0] === 'req') {
// required arguments always have name
parameter = ['opt', parameter[1]];
}
result.push(parameter);
}
return result;
}
} else {
return [];
}
}
end
def curry(arity = undefined)
%x{
if (arity === undefined) {
arity = self.length;
}
else {
arity = #{::Opal.coerce_to!(arity, ::Integer, :to_int)};
if (self.$$is_lambda && arity !== self.length) {
#{::Kernel.raise ::ArgumentError, "wrong number of arguments (#{`arity`} for #{`self.length`})"}
}
}
function curried () {
var args = $slice(arguments),
length = args.length,
result;
if (length > arity && self.$$is_lambda && !self.$$is_curried) {
#{::Kernel.raise ::ArgumentError, "wrong number of arguments (#{`length`} for #{`arity`})"}
}
if (length >= arity) {
return self.$call.apply(self, args);
}
result = function () {
return curried.apply(null,
args.concat($slice(arguments)));
}
result.$$is_lambda = self.$$is_lambda;
result.$$is_curried = true;
return result;
};
curried.$$is_lambda = self.$$is_lambda;
curried.$$is_curried = true;
return curried;
}
end
def dup
%x{
var original_proc = self.$$original_proc || self,
proc = function () {
return original_proc.apply(this, arguments);
};
$each_ivar(self, function(prop) {
proc[prop] = self[prop];
});
return proc;
}
end
alias === call
alias clone dup
alias yield call
alias [] call
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/main.rb | opal/corelib/main.rb | # backtick_javascript: true
class << self
def to_s
'main'
end
def include(mod)
::Object.include mod
end
def autoload(*args)
`Opal.Object.$autoload.apply(Opal.Object, args)`
end
# Compiler overrides this method
def using(mod)
::Kernel.raise 'main.using is permitted only at toplevel'
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/io.rb | opal/corelib/io.rb | # backtick_javascript: true
class ::IO
self::SEEK_SET = 0
self::SEEK_CUR = 1
self::SEEK_END = 2
self::SEEK_DATA = 3
self::SEEK_HOLE = 4
self::READABLE = 1
self::WRITABLE = 4
attr_reader :eof
attr_accessor :read_proc, :sync, :tty, :write_proc
def initialize(fd, flags = 'r')
@fd = fd
@flags = flags
@eof = false
if flags.include?('r') && !flags.match?(/[wa+]/)
@closed = :write
elsif flags.match?(/[wa]/) && !flags.match?(/[r+]/)
@closed = :read
end
end
def fileno
@fd
end
def tty?
`self.tty == true`
end
def write(string)
`self.write_proc(string)`
string.size
end
def flush
# noop
end
def <<(string)
write(string)
self
end
def print(*args)
%x{
for (var i = 0, ii = args.length; i < ii; i++) {
args[i] = #{::Kernel.String(`args[i]`)}
}
self.$write(args.join(#{$,}));
}
nil
end
def puts(*args)
%x{
var line
if (args.length === 0) {
#{write "\n"};
return nil;
} else {
for (var i = 0, ii = args.length; i < ii; i++) {
if (args[i].$$is_array){
var ary = #{`args[i]`.flatten}
if (ary.length > 0) #{puts(*`ary`)}
} else {
if (args[i].$$is_string) {
line = args[i].valueOf();
} else {
line = #{::Kernel.String(`args[i]`)};
}
if (!line.endsWith("\n")) line += "\n"
#{write `line`}
}
}
}
}
nil
end
# Reading
def getc
@read_buffer ||= ''
parts = ''
# Will execure at most twice - one time reading from a buffer
# second time executing read proc
begin
@read_buffer += parts
if @read_buffer != ''
ret = @read_buffer[0]
@read_buffer = @read_buffer[1..-1]
return ret
end
end while parts = sysread_noraise(1)
nil
end
def getbyte
getc&.ord
end
def readbyte
readchar.ord
end
def readchar
getc || ::Kernel.raise(::EOFError, 'end of file reached')
end
def readline(*args)
gets(*args) || ::Kernel.raise(::EOFError, 'end of file reached')
end
def gets(sep = false, limit = nil, opts = {})
if `sep.$$is_number` && !limit
sep, limit, opts = false, sep, limit
end
if `sep.$$is_hash` && !limit && opts == {}
sep, limit, opts = false, nil, sep
elsif `limit.$$is_hash` && opts == {}
sep, limit, opts = sep, nil, limit
end
orig_sep = sep
sep = $/ if sep == false
sep = /\r?\n\r?\n/ if sep == ''
sep ||= ''
sep = sep.to_str unless orig_sep == ''
# Try to deduce length of a regexp
seplen = orig_sep == '' ? 2 : sep.length
sep = / / if sep == ' ' # WTF is this, String#split(" ") matches all whitespaces???
@read_buffer ||= ''
data = ''
ret = nil
begin
@read_buffer += data
if sep != '' && (`sep.$$is_regexp` ? @read_buffer.match?(sep) : @read_buffer.include?(sep))
orig_buffer = @read_buffer
ret, @read_buffer = @read_buffer.split(sep, 2)
ret += orig_buffer[ret.length, seplen] if ret != orig_buffer
break
end
end while data = sysread_noraise(sep == '' ? 65_536 : 1)
unless ret
ret, @read_buffer = @read_buffer || '', ''
ret = nil if ret == ''
end
if ret
if limit
ret = ret[0...limit]
@read_buffer = ret[limit..-1] + @read_buffer
end
ret = ret.sub(/\r?\n\z/, '') if opts[:chomp]
ret = ret.sub(/\A[\r\n]+/, '') if orig_sep == ''
end
$_ = ret if orig_sep == false
ret
end
# This method is to be overloaded, or read_proc can be changed
def sysread(integer)
`self.read_proc(integer)` || begin
@eof = true
::Kernel.raise ::EOFError, 'end of file reached'
end
end
# @private
def sysread_noraise(integer)
sysread(integer)
rescue ::EOFError
nil
end
def readpartial(integer)
@read_buffer ||= ''
part = sysread(integer)
ret, @read_buffer = @read_buffer + (part || ''), ''
ret = nil if ret == ''
ret
end
def read(integer = nil)
@read_buffer ||= ''
parts = ''
ret = nil
begin
@read_buffer += parts
if integer && @read_buffer.length > integer
ret, @read_buffer = @read_buffer[0...integer], @read_buffer[integer..-1]
return ret
end
end while parts = sysread_noraise(integer || 65_536)
ret, @read_buffer = @read_buffer, ''
ret
end
# Eaches
def readlines(separator = $/)
each_line(separator).to_a
end
def each(sep = $/, *args, &block)
return enum_for :each, sep, *args unless block_given?
while (s = gets(sep, *args))
yield(s)
end
self
end
def each_byte(&block)
return enum_for :each_byte unless block_given?
while (s = getbyte)
yield(s)
end
self
end
def each_char(&block)
return enum_for :each_char unless block_given?
while (s = getc)
yield(s)
end
self
end
# Closedness
def close
@closed = :both
end
def close_read
if @closed == :write
@closed = :both
else
@closed = :read
end
end
def close_write
if @closed == :read
@closed = :both
else
@closed = :write
end
end
def closed?
@closed == :both
end
def closed_read?
@closed == :read || @closed == :both
end
def closed_write?
@closed == :write || @closed == :both
end
# @private
def check_writable
if closed_write?
::Kernel.raise ::IOError, 'not opened for writing'
end
end
# @private
def check_readable
if closed_read?
::Kernel.raise ::IOError, 'not opened for reading'
end
end
alias each_line each
alias eof? eof
end
::STDIN = $stdin = ::IO.new(0, 'r')
::STDOUT = $stdout = ::IO.new(1, 'w')
::STDERR = $stderr = ::IO.new(2, 'w')
`var console = Opal.global.console`
::STDOUT.write_proc = `typeof(process) === 'object' && typeof(process.stdout) === 'object' ? function(s){process.stdout.write(s)} : function(s){console.log(s)}`
::STDERR.write_proc = `typeof(process) === 'object' && typeof(process.stderr) === 'object' ? function(s){process.stderr.write(s)} : function(s){console.warn(s)}`
::STDIN.read_proc = `function(s) { var p = prompt(); if (p !== null) return p + "\n"; return nil; }`
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/range.rb | opal/corelib/range.rb | # backtick_javascript: true
# use_strict: true
require 'corelib/enumerable'
class ::Range
include ::Enumerable
`self.$$prototype.$$is_range = true`
attr_reader :begin, :end
def initialize(first, last, exclude = false)
::Kernel.raise ::NameError, "'initialize' called twice" if @begin
::Kernel.raise ::ArgumentError, 'bad value for range' unless first <=> last || first.nil? || last.nil?
@begin = first
@end = last
@excl = exclude
end
def ===(value)
return false if `value.$$is_range`
cover? value
end
%x{
function is_infinite(self) {
if (self.begin === nil || self.end === nil ||
self.begin === -Infinity || self.end === Infinity ||
self.begin === Infinity || self.end === -Infinity) return true;
return false;
}
}
def count(&block)
if !block_given? && `is_infinite(self)`
return ::Float::INFINITY
end
super
end
def to_a
::Kernel.raise ::TypeError, 'cannot convert endless range to an array' if `is_infinite(self)`
super
end
def cover?(value)
compare = ->(a, b) {
a <=> b || 1
}
if `value.$$is_range`
val_begin = value.begin
val_end = value.end
val_excl = value.exclude_end?
if (@begin && val_begin.nil?) ||
(@end && val_end.nil?) ||
(val_begin && val_end && compare.call(val_begin, val_end).then { |c| val_excl ? c >= 0 : c > 0 }) ||
(val_begin && !cover?(val_begin))
return false
end
cmp = compare.call(@end, val_end)
return cmp >= 0 if @excl == val_excl
return cmp > 0 if @excl
return true if cmp >= 0
val_max = value.max
return !val_max.nil? && compare.call(val_max, @end) <= 0
end
return false if @begin && compare.call(@begin, value) > 0
return true if @end.nil?
end_cmp = compare.call(value, @end)
@excl ? end_cmp < 0 : end_cmp <= 0
end
def each(&block)
return enum_for(:each) { size } unless block_given?
%x{
var i, limit;
if (#{@begin}.$$is_number && #{@end}.$$is_number) {
if (#{@begin} % 1 !== 0 || #{@end} % 1 !== 0) {
#{::Kernel.raise ::TypeError, "can't iterate from Float"}
}
for (i = #{@begin}, limit = #{@end} + #{@excl ? 0 : 1}; i < limit; i++) {
block(i);
}
return self;
}
if (#{@begin}.$$is_string && #{@end}.$$is_string) {
#{@begin.upto(@end, @excl, &block)}
return self;
}
}
current = @begin
last = @end
unless current.respond_to?(:succ)
::Kernel.raise ::TypeError, "can't iterate from #{current.class}"
end
while @end.nil? || (current <=> last) < 0
yield current
current = current.succ
end
yield current if !@excl && current == last
self
end
def eql?(other)
return false unless ::Range === other
@excl === other.exclude_end? &&
@begin.eql?(other.begin) &&
@end.eql?(other.end)
end
def exclude_end?
@excl
end
def first(n = undefined)
::Kernel.raise ::RangeError, 'cannot get the minimum of beginless range' if @begin.nil?
return @begin if `n == null`
super
end
def include?(val)
if `self.begin.$$is_number || self.end.$$is_number` ||
@begin.is_a?(::Time) || @end.is_a?(::Time) ||
::Integer.try_convert(@begin) || ::Integer.try_convert(@end)
return cover?(val)
end
if `self.begin.$$is_string || self.end.$$is_string`
if `self.begin.$$is_string && self.end.$$is_string`
return @begin.upto(@end, @excl).any? { |s| s == val }
elsif @begin.nil?
cmp = val <=> @end
return !cmp.nil? && (@excl ? cmp < 0 : cmp <= 0)
elsif @end.nil?
cmp = @begin <=> val
return !cmp.nil? && cmp <= 0
end
end
# invoke Enumerable#include?
super
end
def last(n = undefined)
::Kernel.raise ::RangeError, 'cannot get the maximum of endless range' if @end.nil?
return @end if `n == null`
to_a.last(n)
end
# FIXME: currently hardcoded to assume range holds numerics
def max
if @end.nil?
::Kernel.raise ::RangeError, 'cannot get the maximum of endless range'
elsif block_given?
super
elsif !@begin.nil? && (@begin > @end ||
@excl && @begin == @end)
nil
else
`#{@excl} ? #{@end} - 1 : #{@end}`
end
end
def min
if @begin.nil?
::Kernel.raise ::RangeError, 'cannot get the minimum of beginless range'
elsif block_given?
super
elsif !@end.nil? && (@begin > @end ||
@excl && @begin == @end)
nil
else
@begin
end
end
def size
%x{
var b = this.begin, e = this.end;
// If begin is Numeric
if (#{::Numeric === `b`}) {
// If end is Numeric
if (#{::Numeric === `e`}) {
// Calculating size based on whether range is exclusive or inclusive
var size = #{`e` - `b`};
if (size < 0) {
return 0;
}
if (!this.excl) {
size += 1;
}
return (#{::Float === `b`} || #{::Float === `e`}) ? Math.floor(size) : size;
}
// If end is nil
else if (e === nil) {
return Infinity;
}
}
// If begin is nil
else if (b === nil) {
// If end is Numeric
if (#{::Numeric === `e`}) {
return Infinity;
}
}
// If neither begin nor end is Numeric
return nil;
}
end
def step(n = undefined)
%x{
function coerceStepSize() {
if (n == null) {
n = 1;
}
else if (!n.$$is_number) {
n = #{::Opal.coerce_to!(n, ::Integer, :to_int)}
}
if (n < 0) {
#{::Kernel.raise ::ArgumentError, "step can't be negative"}
} else if (n === 0) {
#{::Kernel.raise ::ArgumentError, "step can't be 0"}
}
}
function enumeratorSize() {
if (!#{@begin.respond_to?(:succ)}) {
return nil;
}
if (#{@begin}.$$is_string && #{@end}.$$is_string) {
return nil;
}
if (n % 1 === 0) {
return #{(size / n).ceil};
} else {
// n is a float
var begin = self.begin, end = self.end,
abs = Math.abs, floor = Math.floor,
err = (abs(begin) + abs(end) + abs(end - begin)) / abs(n) * #{::Float::EPSILON},
size;
if (err > 0.5) {
err = 0.5;
}
if (self.excl) {
size = floor((end - begin) / n - err);
if (size * n + begin < end) {
size++;
}
} else {
size = floor((end - begin) / n + err) + 1
}
return size;
}
}
}
unless block_given?
if (@begin.is_a?(Numeric) || @begin.nil?) &&
(@end.is_a?(Numeric) || @end.nil?) &&
!(@begin.nil? && @end.nil?)
return ::Enumerator::ArithmeticSequence.new(self, n, :step)
else
return enum_for(:step, n) do
%x{
coerceStepSize();
return enumeratorSize();
}
end
end
end
`coerceStepSize()`
if `self.begin.$$is_number && self.end.$$is_number`
i = 0
loop do
current = @begin + i * n
if @excl
break if current >= @end
elsif current > @end
break
end
yield(current)
i += 1
end
else
%x{
if (#{@begin}.$$is_string && #{@end}.$$is_string && n % 1 !== 0) {
#{::Kernel.raise ::TypeError, 'no implicit conversion to float from string'}
}
}
each_with_index do |value, idx|
yield(value) if idx % n == 0
end
end
self
end
def %(n)
if @begin.is_a?(Numeric) && @end.is_a?(Numeric)
::Enumerator::ArithmeticSequence.new(self, n, :%)
else
step(n)
end
end
def bsearch(&block)
return enum_for(:bsearch) unless block_given?
if `is_infinite(self) && (self.begin.$$is_number || self.end.$$is_number)`
::Kernel.raise ::NotImplementedError, "Can't #bsearch an infinite range"
end
unless `self.begin.$$is_number && self.end.$$is_number`
::Kernel.raise ::TypeError, "can't do binary search for #{@begin.class}"
end
to_a.bsearch(&block)
end
def to_s
"#{@begin || ''}#{@excl ? '...' : '..'}#{@end || ''}"
end
def inspect
"#{@begin && @begin.inspect}#{@excl ? '...' : '..'}#{@end && @end.inspect}"
end
def marshal_load(args)
@begin = args[:begin]
@end = args[:end]
@excl = args[:excl]
end
def hash
[::Range, @begin, @end, @excl].hash
end
alias == eql?
alias member? include?
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/object_space.rb | opal/corelib/object_space.rb | # backtick_javascript: true
# helpers: respond_to, truthy
module ::ObjectSpace
module_function
%x{
var callers = {}, registry, add_caller, delete_callers;
if (typeof FinalizationRegistry === "function") {
registry = new FinalizationRegistry(function(id) {
if (typeof callers[id] !== "undefined") {
for (var i = 0; i < callers[id].length; i++) {
#{`callers[id][i]`.call(`id`)};
}
delete callers[id];
}
});
add_caller = function(id, value) {
callers[id] = callers[id] || [];
callers[id].push(value);
}
delete_callers = function(id) {
delete callers[id];
}
}
else {
// A weak polyfill for FinalizationRegistry
registry = {
register: function(){},
unregister: function(){}
};
add_caller = function(){};
delete_callers = function(){};
}
}
def define_finalizer(obj, aproc = undefined, &block)
%x{
if ($truthy(block)) aproc = block;
if (!$truthy(aproc)) aproc = #{::Kernel.proc};
if (!$respond_to(aproc, '$call')) {
#{::Kernel.raise ::ArgumentError, "Wrong type argument #{aproc.class} (should be callable)"};
}
var id = #{obj.__id__};
add_caller(id, aproc);
try {
registry.register(obj, id, obj);
}
catch (e) {
delete_callers(id);
#{::Kernel.raise ::ArgumentError, "cannot define finalizer for #{obj.class}"};
}
return [0, aproc];
}
end
def undefine_finalizer(obj)
%x{
var id = #{obj.__id__};
registry.unregister(obj);
delete_callers(id);
return obj;
}
end
class self::WeakMap
include ::Enumerable
def initialize
@weak_map = `new WeakMap()`
@primitive_map = {}
end
def [](p1)
%x{
if (typeof p1 !== "function" && typeof p1 !== "object") return #{@primitive_map[p1]};
return #{@weak_map}.get(p1);
}
end
def []=(p1, p2)
%x{
if (typeof p1 !== "function" && typeof p1 !== "object") return #{@primitive_map[p1] = p2};
return #{@weak_map}.set(p1, p2);
}
end
def include?(p1)
%x{
if (typeof p1 !== "function" && typeof p1 !== "object") return #{@primitive_map.key? p1};
return #{@weak_map}.has(p1);
}
end
%i[each each_key each_value each_pair keys values size length].each do |i|
define_method i do |*|
::Kernel.raise ::NotImplementedError, "##{i} can't be implemented on top of JS interfaces"
end
end
alias member? include?
alias key? include?
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/struct.rb | opal/corelib/struct.rb | # backtick_javascript: true
require 'corelib/enumerable'
class ::Struct
include ::Enumerable
def self.new(const_name, *args, keyword_init: false, &block)
if const_name
if const_name.class == ::String && const_name[0].upcase != const_name[0]
# Fast track so that we skip needlessly going thru exceptions
# in most cases.
args.unshift(const_name)
const_name = nil
else
begin
const_name = ::Opal.const_name!(const_name)
rescue ::TypeError, ::NameError
args.unshift(const_name)
const_name = nil
end
end
end
args.map do |arg|
::Opal.coerce_to!(arg, ::String, :to_str)
end
klass = ::Class.new(self) do
args.each { |arg| define_struct_attribute(arg) }
class << self
def new(*args)
instance = allocate
`#{instance}.$$data = {}`
instance.initialize(*args)
instance
end
alias_method :[], :new
end
end
klass.module_eval(&block) if block
`klass.$$keyword_init = keyword_init`
if const_name
::Struct.const_set(const_name, klass)
end
klass
end
def self.define_struct_attribute(name)
if self == ::Struct
::Kernel.raise ::ArgumentError, 'you cannot define attributes to the Struct class'
end
members << name
define_method name do
`self.$$data[name]`
end
define_method "#{name}=" do |value|
`self.$$data[name] = value`
end
end
def self.members
if self == ::Struct
::Kernel.raise ::ArgumentError, 'the Struct class has no members'
end
@members ||= []
end
def self.inherited(klass)
members = @members
klass.instance_eval do
@members = members
end
end
def initialize(*args)
if `#{self.class}.$$keyword_init`
kwargs = args.last || {}
if args.length > 1 || `(args.length === 1 && !kwargs.$$is_hash)`
::Kernel.raise ::ArgumentError, "wrong number of arguments (given #{args.length}, expected 0)"
end
extra = kwargs.keys - self.class.members
if extra.any?
::Kernel.raise ::ArgumentError, "unknown keywords: #{extra.join(', ')}"
end
self.class.members.each do |name|
self[name] = kwargs[name]
end
else
if args.length > self.class.members.length
::Kernel.raise ::ArgumentError, 'struct size differs'
end
self.class.members.each_with_index do |name, index|
self[name] = args[index]
end
end
end
def initialize_copy(from)
%x{
self.$$data = {}
var keys = Object.keys(from.$$data), i, max, name;
for (i = 0, max = keys.length; i < max; i++) {
name = keys[i];
self.$$data[name] = from.$$data[name];
}
}
end
def self.keyword_init?
`self.$$keyword_init`
end
def members
self.class.members
end
def hash
[self.class, to_a].hash
end
def [](name)
if ::Integer === name
::Kernel.raise ::IndexError, "offset #{name} too small for struct(size:#{self.class.members.size})" if name < -self.class.members.size
::Kernel.raise ::IndexError, "offset #{name} too large for struct(size:#{self.class.members.size})" if name >= self.class.members.size
name = self.class.members[name]
elsif ::String === name
%x{
if(!self.$$data.hasOwnProperty(name)) {
#{::Kernel.raise ::NameError.new("no member '#{name}' in struct", name)}
}
}
else
::Kernel.raise ::TypeError, "no implicit conversion of #{name.class} into Integer"
end
name = ::Opal.coerce_to!(name, ::String, :to_str)
`self.$$data[name]`
end
def []=(name, value)
if ::Integer === name
::Kernel.raise ::IndexError, "offset #{name} too small for struct(size:#{self.class.members.size})" if name < -self.class.members.size
::Kernel.raise ::IndexError, "offset #{name} too large for struct(size:#{self.class.members.size})" if name >= self.class.members.size
name = self.class.members[name]
elsif ::String === name
::Kernel.raise ::NameError.new("no member '#{name}' in struct", name) unless self.class.members.include?(name.to_sym)
else
::Kernel.raise ::TypeError, "no implicit conversion of #{name.class} into Integer"
end
name = ::Opal.coerce_to!(name, ::String, :to_str)
`self.$$data[name] = value`
end
def ==(other)
return false unless other.instance_of?(self.class)
%x{
var recursed1 = {}, recursed2 = {};
function _eqeq(struct, other) {
var key, a, b;
recursed1[#{`struct`.__id__}] = true;
recursed2[#{`other`.__id__}] = true;
for (key in struct.$$data) {
a = struct.$$data[key];
b = other.$$data[key];
if (#{::Struct === `a`}) {
if (!recursed1.hasOwnProperty(#{`a`.__id__}) || !recursed2.hasOwnProperty(#{`b`.__id__})) {
if (!_eqeq(a, b)) {
return false;
}
}
} else {
if (!#{`a` == `b`}) {
return false;
}
}
}
return true;
}
return _eqeq(self, other);
}
end
def eql?(other)
return false unless other.instance_of?(self.class)
%x{
var recursed1 = {}, recursed2 = {};
function _eqeq(struct, other) {
var key, a, b;
recursed1[#{`struct`.__id__}] = true;
recursed2[#{`other`.__id__}] = true;
for (key in struct.$$data) {
a = struct.$$data[key];
b = other.$$data[key];
if (#{::Struct === `a`}) {
if (!recursed1.hasOwnProperty(#{`a`.__id__}) || !recursed2.hasOwnProperty(#{`b`.__id__})) {
if (!_eqeq(a, b)) {
return false;
}
}
} else {
if (!#{`a`.eql?(`b`)}) {
return false;
}
}
}
return true;
}
return _eqeq(self, other);
}
end
def each
return enum_for(:each) { size } unless block_given?
self.class.members.each { |name| yield self[name] }
self
end
def each_pair
return enum_for(:each_pair) { size } unless block_given?
self.class.members.each { |name| yield [name, self[name]] }
self
end
def length
self.class.members.length
end
def to_a
self.class.members.map { |name| self[name] }
end
`var inspect_stack = []`
def inspect
result = '#<struct '
if `inspect_stack`.include? __id__
result + ':...>'
else
`inspect_stack` << __id__
pushed = true
if ::Struct === self && self.class.name
result += "#{self.class} "
end
result += each_pair.map do |name, value|
"#{name}=#{Opal.inspect(value)}"
end.join ', '
result += '>'
result
end
ensure
`inspect_stack.pop()` if pushed
end
def to_h(*args, &block)
return map(&block).to_h(*args) if block_given?
self.class.members.each_with_object({}) { |name, h| h[name] = self[name] }
end
def values_at(*args)
args = args.map { |arg| `arg.$$is_range ? #{arg.to_a} : arg` }.flatten
%x{
var result = [];
for (var i = 0, len = args.length; i < len; i++) {
if (!args[i].$$is_number) {
#{::Kernel.raise ::TypeError, "no implicit conversion of #{`args[i]`.class} into Integer"}
}
result.push(#{self[`args[i]`]});
}
return result;
}
end
def dig(key, *keys)
item = if `key.$$is_string && self.$$data.hasOwnProperty(key)`
`self.$$data[key] || nil`
end
%x{
if (item === nil || keys.length === 0) {
return item;
}
}
unless item.respond_to?(:dig)
::Kernel.raise ::TypeError, "#{item.class} does not have #dig method"
end
item.dig(*keys)
end
alias size length
alias to_s inspect
alias values to_a
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/comparable.rb | opal/corelib/comparable.rb | # helpers: truthy
# backtick_javascript: true
module ::Comparable
%x{
function normalize(what) {
if (Opal.is_a(what, Opal.Integer)) { return what; }
if (#{`what` > 0}) { return 1; }
if (#{`what` < 0}) { return -1; }
return 0;
}
function fail_comparison(lhs, rhs) {
var class_name;
#{
case `rhs`
when nil, true, false, ::Integer, ::Float
`class_name = rhs.$inspect()`
else
`class_name = rhs.$$class`
end
}
#{::Kernel.raise ::ArgumentError, "comparison of #{`lhs`.class} with #{`class_name`} failed"}
}
function cmp_or_fail(lhs, rhs) {
var cmp = #{`lhs` <=> `rhs`};
if (!$truthy(cmp)) fail_comparison(lhs, rhs);
return normalize(cmp);
}
}
def ==(other)
return true if equal?(other)
%x{
if (self["$<=>"] == Opal.Kernel["$<=>"]) {
return false;
}
// check for infinite recursion
if (self.$$comparable) {
self.$$comparable = false;
return false;
}
}
return false unless cmp = (self <=> other)
`normalize(cmp) == 0`
end
def >(other)
`cmp_or_fail(self, other) > 0`
end
def >=(other)
`cmp_or_fail(self, other) >= 0`
end
def <(other)
`cmp_or_fail(self, other) < 0`
end
def <=(other)
`cmp_or_fail(self, other) <= 0`
end
def between?(min, max)
return false if self < min
return false if self > max
true
end
def clamp(min, max = nil)
%x{
var c, excl;
if (max === nil) {
// We are dealing with a new Ruby 2.7 behaviour that we are able to
// provide a single Range argument instead of 2 Comparables.
if (!Opal.is_a(min, Opal.Range)) {
#{::Kernel.raise ::TypeError, "wrong argument type #{min.class} (expected Range)"}
}
excl = min.excl;
max = min.end;
min = min.begin;
if (max !== nil && excl) {
#{::Kernel.raise ::ArgumentError, 'cannot clamp with an exclusive range'}
}
}
if (min !== nil && max !== nil && cmp_or_fail(min, max) > 0) {
#{::Kernel.raise ::ArgumentError, 'min argument must be smaller than max argument'}
}
if (min !== nil) {
c = cmp_or_fail(self, min);
if (c == 0) return self;
if (c < 0) return min;
}
if (max !== nil) {
c = cmp_or_fail(self, max);
if (c > 0) return max;
}
return self;
}
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/method.rb | opal/corelib/method.rb | # backtick_javascript: true
class ::Method
attr_reader :owner, :receiver, :name
def initialize(receiver, owner, method, name)
@receiver = receiver
@owner = owner
@name = name
@method = method
end
def arity
@method.arity
end
def parameters
`#{@method}.$$parameters`
end
def source_location
`#{@method}.$$source_location` || ['(eval)', 0]
end
def comments
`#{@method}.$$comments` || []
end
def call(*args, &block)
%x{
#{@method}.$$p = block;
return #{@method}.apply(#{@receiver}, args);
}
end
def curry(arity = undefined)
@method.curry(arity)
end
def >>(other)
@method >> other
end
def <<(other)
@method << other
end
def unbind
::UnboundMethod.new(@receiver.class, @owner, @method, @name)
end
def to_proc
%x{
var proc = self.$call.bind(self);
proc.$$unbound = #{@method};
proc.$$is_lambda = true;
proc.$$arity = #{@method}.$$arity == null ? #{@method}.length : #{@method}.$$arity;
proc.$$parameters = #{@method}.$$parameters;
return proc;
}
end
def inspect
"#<#{self.class}: #{@receiver.class}##{@name} (defined in #{@owner} in #{source_location.join(':')})>"
end
alias [] call
alias === call
end
class ::UnboundMethod
attr_reader :source, :owner, :name
def initialize(source, owner, method, name)
@source = source
@owner = owner
@method = method
@name = name
`self.$$method = method`
end
def arity
@method.arity
end
def parameters
`#{@method}.$$parameters`
end
def source_location
`#{@method}.$$source_location` || ['(eval)', 0]
end
def comments
`#{@method}.$$comments` || []
end
def bind(object)
%x{
if (#{@owner}.$$is_module || Opal.is_a(#{object}, #{@owner})) {
return #{::Method.new(object, @owner, @method, @name)};
}
else {
#{::Kernel.raise ::TypeError, "can't bind singleton method to a different class (expected #{object}.kind_of?(#{@owner} to be true)"};
}
}
end
def bind_call(object, *args, &block)
bind(object).call(*args, &block)
end
def inspect
"#<#{self.class}: #{@source}##{@name} (defined in #{@owner} in #{source_location.join(':')})>"
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/variables.rb | opal/corelib/variables.rb | # backtick_javascript: true
# use_strict: true
# regexp matches
%x{$gvars['&'] = $gvars['~'] = $gvars['`'] = $gvars["'"] = nil}
# requires
$LOADED_FEATURES = $" = `Opal.loaded_features`
$LOAD_PATH = $: = []
# split lines
$/ = "\n"
$, = nil
::ARGV = []
::ARGF = ::Object.new
::ENV = {}
$VERBOSE = false
$DEBUG = false
$SAFE = 0
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/math.rb | opal/corelib/math.rb | # helpers: type_error
# backtick_javascript: true
# use_strict: true
module ::Math
self::E = `Math.E`
self::PI = `Math.PI`
self::DomainError = ::Class.new(::StandardError)
def self.checked(method, *args)
%x{
if (isNaN(args[0]) || (args.length == 2 && isNaN(args[1]))) {
return NaN;
}
var result = Math[method].apply(null, args);
if (isNaN(result)) {
#{::Kernel.raise DomainError, "Numerical argument is out of domain - \"#{method}\""};
}
return result;
}
end
def self.float!(value)
::Kernel.Float(value)
rescue ::ArgumentError
::Kernel.raise `$type_error(value, #{::Float})`
end
def self.integer!(value)
::Kernel.Integer(value)
rescue ::ArgumentError
::Kernel.raise `$type_error(value, #{::Integer})`
end
module_function
unless defined?(`Math.erf`)
%x{
Opal.prop(Math, 'erf', function(x) {
var A1 = 0.254829592,
A2 = -0.284496736,
A3 = 1.421413741,
A4 = -1.453152027,
A5 = 1.061405429,
P = 0.3275911;
var sign = 1;
if (x < 0) {
sign = -1;
}
x = Math.abs(x);
var t = 1.0 / (1.0 + P * x);
var y = 1.0 - (((((A5 * t + A4) * t) + A3) * t + A2) * t + A1) * t * Math.exp(-x * x);
return sign * y;
});
}
end
unless defined?(`Math.erfc`)
%x{
Opal.prop(Math, 'erfc', function(x) {
var z = Math.abs(x),
t = 1.0 / (0.5 * z + 1.0);
var A1 = t * 0.17087277 + -0.82215223,
A2 = t * A1 + 1.48851587,
A3 = t * A2 + -1.13520398,
A4 = t * A3 + 0.27886807,
A5 = t * A4 + -0.18628806,
A6 = t * A5 + 0.09678418,
A7 = t * A6 + 0.37409196,
A8 = t * A7 + 1.00002368,
A9 = t * A8,
A10 = -z * z - 1.26551223 + A9;
var a = t * Math.exp(A10);
if (x < 0.0) {
return 2.0 - a;
}
else {
return a;
}
});
}
end
# Single argument equivalent functions
%i[
acos acosh asin asinh atan atanh cbrt
cos cosh erf erfc exp sin sinh sqrt tanh
].each do |method|
define_method method do |x|
::Math.checked method, ::Math.float!(x)
end
end
def atan2(y, x)
::Math.checked :atan2, ::Math.float!(y), ::Math.float!(x)
end
def hypot(x, y)
::Math.checked :hypot, ::Math.float!(x), ::Math.float!(y)
end
def frexp(x)
x = Math.float!(x)
%x{
if (isNaN(x)) {
return [NaN, 0];
}
var ex = Math.floor(Math.log(Math.abs(x)) / Math.log(2)) + 1,
frac = x / Math.pow(2, ex);
return [frac, ex];
}
end
def gamma(n)
n = Math.float!(n)
%x{
var i, t, x, value, result, twoN, threeN, fourN, fiveN;
var G = 4.7421875;
/* eslint no-loss-of-precision: "warn" */
var P = [
0.99999999999999709182,
57.156235665862923517,
-59.597960355475491248,
14.136097974741747174,
-0.49191381609762019978,
0.33994649984811888699e-4,
0.46523628927048575665e-4,
-0.98374475304879564677e-4,
0.15808870322491248884e-3,
-0.21026444172410488319e-3,
0.21743961811521264320e-3,
-0.16431810653676389022e-3,
0.84418223983852743293e-4,
-0.26190838401581408670e-4,
0.36899182659531622704e-5
];
if (isNaN(n)) {
return NaN;
}
if (n === 0 && 1 / n < 0) {
return -Infinity;
}
if (n === -1 || n === -Infinity) {
#{::Kernel.raise DomainError, 'Numerical argument is out of domain - "gamma"'};
}
if (#{Integer === n}) {
if (n <= 0) {
return isFinite(n) ? Infinity : NaN;
}
if (n > 171) {
return Infinity;
}
value = n - 2;
result = n - 1;
while (value > 1) {
result *= value;
value--;
}
if (result == 0) {
result = 1;
}
return result;
}
if (n < 0.5) {
return Math.PI / (Math.sin(Math.PI * n) * #{::Math.gamma(1 - n)});
}
if (n >= 171.35) {
return Infinity;
}
if (n > 85.0) {
twoN = n * n;
threeN = twoN * n;
fourN = threeN * n;
fiveN = fourN * n;
return Math.sqrt(2 * Math.PI / n) * Math.pow((n / Math.E), n) *
(1 + 1 / (12 * n) + 1 / (288 * twoN) - 139 / (51840 * threeN) -
571 / (2488320 * fourN) + 163879 / (209018880 * fiveN) +
5246819 / (75246796800 * fiveN * n));
}
n -= 1;
x = P[0];
for (i = 1; i < P.length; ++i) {
x += P[i] / (n + i);
}
t = n + G + 0.5;
return Math.sqrt(2 * Math.PI) * Math.pow(t, n + 0.5) * Math.exp(-t) * x;
}
end
def ldexp(mantissa, exponent)
mantissa = Math.float!(mantissa)
exponent = Math.integer!(exponent)
%x{
if (isNaN(exponent)) {
#{::Kernel.raise ::RangeError, 'float NaN out of range of integer'};
}
return mantissa * Math.pow(2, exponent);
}
end
def lgamma(n)
%x{
if (n == -1) {
return [Infinity, 1];
}
else {
return [Math.log(Math.abs(#{::Math.gamma(n)})), #{::Math.gamma(n)} < 0 ? -1 : 1];
}
}
end
def log(x, base = undefined)
if ::String === x
::Kernel.raise `$type_error(x, #{::Float})`
end
if `base == null`
::Math.checked :log, ::Math.float!(x)
else
if ::String === base
::Kernel.raise `$type_error(base, #{::Float})`
end
::Math.checked(:log, ::Math.float!(x)) / ::Math.checked(:log, ::Math.float!(base))
end
end
def log10(x)
if ::String === x
::Kernel.raise `$type_error(x, #{::Float})`
end
::Math.checked :log10, ::Math.float!(x)
end
def log2(x)
if ::String === x
::Kernel.raise `$type_error(x, #{::Float})`
end
::Math.checked :log2, ::Math.float!(x)
end
def tan(x)
x = ::Math.float!(x)
if x.infinite?
return ::Float::NAN
end
::Math.checked :tan, ::Math.float!(x)
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/array.rb | opal/corelib/array.rb | # helpers: truthy, falsy, yield1, hash_get, hash_put, hash_delete, coerce_to, respond_to, deny_frozen_access, freeze, opal32_init, opal32_add
# backtick_javascript: true
require 'corelib/enumerable'
require 'corelib/numeric'
class ::Array < `Array`
include ::Enumerable
# Mark all javascript arrays as being valid ruby arrays
`Opal.prop(self.$$prototype, '$$is_array', true)`
%x{
// Recent versions of V8 (> 7.1) only use an optimized implementation when Array.prototype is unmodified.
// For instance, "array-splice.tq" has a "fast path" (ExtractFastJSArray, defined in "src/codegen/code-stub-assembler.cc")
// but it's only enabled when "IsPrototypeInitialArrayPrototype()" is true.
//
// Older versions of V8 were using relatively fast JS-with-extensions code even when Array.prototype is modified:
// https://github.com/v8/v8/blob/7.0.1/src/js/array.js#L599-L642
//
// In short, Array operations are slow in recent versions of V8 when the Array.prototype has been tampered.
// So, when possible, we are using faster open-coded version to boost the performance.
// As of V8 8.4, depending on the size of the array, this is up to ~25x times faster than Array#shift()
// Implementation is heavily inspired by: https://github.com/nodejs/node/blob/ba684805b6c0eded76e5cd89ee00328ac7a59365/lib/internal/util.js#L341-L347
function shiftNoArg(list) {
var r = list[0];
var index = 1;
var length = list.length;
for (; index < length; index++) {
list[index - 1] = list[index];
}
list.pop();
return r;
}
function toArraySubclass(obj, klass) {
if (klass.$$name === Opal.Array) {
return obj;
} else {
return klass.$allocate().$replace(#{`obj`.to_a});
}
}
// A helper for keep_if and delete_if, filter is either Opal.truthy
// or Opal.falsy.
function filterIf(self, filter, block) {
var value, raised = null, updated = new Array(self.length);
for (var i = 0, i2 = 0; i < self.length; i++) {
if (!raised) {
try {
value = $yield1(block, self[i])
} catch(error) {
raised = error;
}
}
if (raised || filter(value)) {
updated[i2] = self[i]
i2 += 1;
}
}
if (i2 !== i) {
self.splice.apply(self, [0, updated.length].concat(updated));
self.splice(i2, updated.length);
}
if (raised) throw raised;
}
function convertToArray(array) {
if (!array.$$is_array) {
array = $coerce_to(array, #{::Array}, 'to_ary');
}
return #{`array`.to_a};
}
function fast_push(arr, objects) {
// push.apply() for arrays longer than 32767 may cause various argument errors in browsers
// but it is significantly faster than a for loop, which pushes each element separately
// but apply() has a overhead by itself, for a small number of elements
// the for loop is significantly faster
// this is using the best option depending on objects.length
var length = objects.length;
if (length > 6 && length < 32767) {
arr.push.apply(arr, objects);
} else {
for (var i = 0; i < length; i++) {
arr.push(objects[i]);
}
}
}
}
def self.[](*objects)
`toArraySubclass(objects, self)`
end
def initialize(size = nil, obj = nil, &block)
%x{
$deny_frozen_access(self);
if (obj !== nil && block !== nil) {
#{::Kernel.warn('warning: block supersedes default value argument')}
}
if (size > #{::Integer::MAX}) {
#{::Kernel.raise ::ArgumentError, 'array size too big'}
}
if (arguments.length > 2) {
#{::Kernel.raise ::ArgumentError, "wrong number of arguments (#{`arguments.length`} for 0..2)"}
}
if (arguments.length === 0) {
if (self.length > 0) self.splice(0, self.length);
return self;
}
if (arguments.length === 1) {
if (size.$$is_array) {
#{replace(size.to_a)}
return self;
} else if (#{size.respond_to? :to_ary}) {
#{replace(size.to_ary)}
return self;
}
}
size = $coerce_to(size, #{::Integer}, 'to_int');
if (size < 0) {
#{::Kernel.raise ::ArgumentError, 'negative array size'}
}
self.splice(0, self.length);
var i, value;
if (block === nil) {
for (i = 0; i < size; i++) {
self.push(obj);
}
}
else {
for (i = 0, value; i < size; i++) {
value = block(i);
self[i] = value;
}
}
return self;
}
end
def self.try_convert(obj)
::Opal.coerce_to? obj, ::Array, :to_ary
end
def &(other)
%x{
other = convertToArray(other)
if (self.length === 0 || other.length === 0) {
return [];
}
var result = [], hash = #{{}}, i, length, item;
for (i = 0, length = other.length; i < length; i++) {
$hash_put(hash, other[i], true);
}
for (i = 0, length = self.length; i < length; i++) {
item = self[i];
if ($hash_delete(hash, item) !== undefined) {
result.push(item);
}
}
return result;
}
end
def |(other)
other = `convertToArray(other)`
%x{
var hash = #{{}}, i, length, item;
for (i = 0, length = self.length; i < length; i++) {
$hash_put(hash, self[i], true);
}
for (i = 0, length = other.length; i < length; i++) {
$hash_put(hash, other[i], true);
}
return hash.$keys();
}
end
def *(other)
return join(other.to_str) if other.respond_to? :to_str
other = `$coerce_to(other, #{::Integer}, 'to_int')`
if `other < 0`
::Kernel.raise ::ArgumentError, 'negative argument'
end
%x{
var result = [],
converted = #{to_a};
for (var i = 0; i < other; i++) {
result = result.concat(converted);
}
return result;
}
end
def +(other)
other = `convertToArray(other)`
`self.concat(other)`
end
def -(other)
other = `convertToArray(other)`
return [] if `self.length === 0`
return `self.slice()` if `other.length === 0`
%x{
var result = [], hash = #{{}}, i, length, item;
for (i = 0, length = other.length; i < length; i++) {
$hash_put(hash, other[i], true);
}
for (i = 0, length = self.length; i < length; i++) {
item = self[i];
if ($hash_get(hash, item) === undefined) {
result.push(item);
}
}
return result;
}
end
def <<(object)
`$deny_frozen_access(self)`
`self.push(object)`
self
end
def <=>(other)
if ::Array === other
other = other.to_a
elsif other.respond_to? :to_ary
other = other.to_ary.to_a
else
return
end
%x{
if (#{self} === #{other}) {
return 0;
}
var count = Math.min(self.length, other.length);
for (var i = 0; i < count; i++) {
var tmp = #{`self[i]` <=> `other[i]`};
if (tmp !== 0) {
return tmp;
}
}
return #{`self.length` <=> `other.length`};
}
end
def ==(other)
%x{
var recursed = {};
function _eqeq(array, other) {
var i, length, a, b;
if (array === other)
return true;
if (!other.$$is_array) {
if ($respond_to(other, '$to_ary')) {
return #{`other` == `array`};
} else {
return false;
}
}
if (array.$$constructor !== Array)
array = #{`array`.to_a};
if (other.$$constructor !== Array)
other = #{`other`.to_a};
if (array.length !== other.length) {
return false;
}
recursed[#{`array`.object_id}] = true;
for (i = 0, length = array.length; i < length; i++) {
a = array[i];
b = other[i];
if (a.$$is_array) {
if (b.$$is_array && b.length !== a.length) {
return false;
}
if (!recursed.hasOwnProperty(#{`a`.object_id})) {
if (!_eqeq(a, b)) {
return false;
}
}
} else {
if (!#{`a` == `b`}) {
return false;
}
}
}
return true;
}
return _eqeq(self, other);
}
end
%x{
function $array_slice_range(self, index) {
var size = self.length,
exclude, from, to, result;
exclude = index.excl;
from = index.begin === nil ? 0 : $coerce_to(index.begin, Opal.Integer, 'to_int');
to = index.end === nil ? -1 : $coerce_to(index.end, Opal.Integer, 'to_int');
if (from < 0) {
from += size;
if (from < 0) {
return nil;
}
}
if (index.excl_rev && index.begin !== nil) {
from += 1;
}
if (from > size) {
return nil;
}
if (to < 0) {
to += size;
if (to < 0) {
return [];
}
}
if (!exclude || index.end === nil) {
to += 1;
}
result = self.slice(from, to);
return result;
}
function $array_slice_arithmetic_seq(self, index) {
var array, out = [], i = 0, pseudorange;
if (index.step < 0) {
pseudorange = {
begin: index.range.end,
end: index.range.begin,
excl: false,
excl_rev: index.range.excl
};
array = $array_slice_range(self, pseudorange).$reverse();
}
else {
array = $array_slice_range(self, index.range);
}
while (i < array.length) {
out.push(array[i]);
i += Math.abs(index.step);
}
return out;
}
function $array_slice_index_length(self, index, length) {
var size = self.length,
exclude, from, to, result;
index = $coerce_to(index, Opal.Integer, 'to_int');
if (index < 0) {
index += size;
if (index < 0) {
return nil;
}
}
if (length === undefined) {
if (index >= size || index < 0) {
return nil;
}
return self[index];
}
else {
length = $coerce_to(length, Opal.Integer, 'to_int');
if (length < 0 || index > size || index < 0) {
return nil;
}
result = self.slice(index, index + length);
}
return result;
}
}
def [](index, length = undefined)
%x{
if (index.$$is_range) {
return $array_slice_range(self, index);
}
else if (index.$$is_arithmetic_seq) {
return $array_slice_arithmetic_seq(self, index);
}
else {
return $array_slice_index_length(self, index, length);
}
}
end
def []=(index, value, extra = undefined)
`$deny_frozen_access(self)`
data = nil
%x{
var i, size = self.length;
if (index.$$is_range) {
if (value.$$is_array)
data = #{value.to_a};
else if (#{value.respond_to? :to_ary})
data = #{value.to_ary.to_a};
else
data = [value];
var exclude = index.excl,
from = index.begin === nil ? 0 : $coerce_to(index.begin, Opal.Integer, 'to_int'),
to = index.end === nil ? -1 : $coerce_to(index.end, Opal.Integer, 'to_int');
if (from < 0) {
from += size;
if (from < 0) {
#{::Kernel.raise ::RangeError, "#{index.inspect} out of range"};
}
}
if (to < 0) {
to += size;
}
if (!exclude || index.end === nil) {
to += 1;
}
if (from > size) {
for (i = size; i < from; i++) {
self[i] = nil;
}
}
if (to < 0) {
self.splice.apply(self, [from, 0].concat(data));
}
else {
self.splice.apply(self, [from, to - from].concat(data));
}
return value;
} else {
if (extra === undefined) {
#{length = 1}
} else {
length = value;
value = extra;
if (value.$$is_array)
data = #{value.to_a};
else if (#{value.respond_to? :to_ary})
data = #{value.to_ary.to_a};
else
data = [value];
}
var old;
index = $coerce_to(index, #{::Integer}, 'to_int');
length = $coerce_to(length, #{::Integer}, 'to_int');
if (index < 0) {
old = index;
index += size;
if (index < 0) {
#{::Kernel.raise ::IndexError, "index #{`old`} too small for array; minimum #{`-self.length`}"};
}
}
if (length < 0) {
#{::Kernel.raise ::IndexError, "negative length (#{length})"}
}
if (index > size) {
for (i = size; i < index; i++) {
self[i] = nil;
}
}
if (extra === undefined) {
self[index] = value;
}
else {
self.splice.apply(self, [index, length].concat(data));
}
return value;
}
}
end
def any?(pattern = undefined, &block)
%x{
if (self.length === 0) return false;
// A special optimized fastpath for Array#any? if no argument
// or block is given. Since Array#any? in this form is often
// used instead of !Array#empty?, and Enumerable#any? uses
// closure exceptions, this shortpath may provide some
// optimization gains.
if (pattern == null && !#{block_given?}) {
for (var i = 0; i < self.length; i++) {
if ($truthy(self[i])) return true;
}
return false;
}
}
# For other cases, defer to Enumerable#any?
super
end
def assoc(object)
%x{
for (var i = 0, length = self.length, item; i < length; i++) {
if (item = self[i], item.length && #{`item[0]` == object}) {
return item;
}
}
return nil;
}
end
def at(index)
%x{
index = $coerce_to(index, #{::Integer}, 'to_int')
if (index < 0) {
index += self.length;
}
if (index < 0 || index >= self.length) {
return nil;
}
return self[index];
}
end
def bsearch_index(&block)
return enum_for :bsearch_index unless block_given?
%x{
var min = 0,
max = self.length,
mid,
val,
ret,
smaller = false,
satisfied = nil;
while (min < max) {
mid = min + Math.floor((max - min) / 2);
val = self[mid];
ret = $yield1(block, val);
if (ret === true) {
satisfied = mid;
smaller = true;
}
else if (ret === false || ret === nil) {
smaller = false;
}
else if (ret.$$is_number) {
if (ret === 0) { return mid; }
smaller = (ret < 0);
}
else {
#{::Kernel.raise ::TypeError, "wrong argument type #{`ret`.class} (must be numeric, true, false or nil)"}
}
if (smaller) { max = mid; } else { min = mid + 1; }
}
return satisfied;
}
end
def bsearch(&block)
return enum_for :bsearch unless block_given?
index = bsearch_index(&block)
%x{
if (index != null && index.$$is_number) {
return self[index];
} else {
return index;
}
}
end
def cycle(n = nil, &block)
unless block_given?
return enum_for(:cycle, n) do
if n.nil?
::Float::INFINITY
else
n = ::Opal.coerce_to!(n, ::Integer, :to_int)
n > 0 ? enumerator_size * n : 0
end
end
end
return if empty? || n == 0
%x{
var i, length, value;
if (n === nil) {
while (true) {
for (i = 0, length = self.length; i < length; i++) {
value = $yield1(block, self[i]);
}
}
}
else {
n = #{::Opal.coerce_to!(n, ::Integer, :to_int)};
if (n <= 0) {
return self;
}
while (n > 0) {
for (i = 0, length = self.length; i < length; i++) {
value = $yield1(block, self[i]);
}
n--;
}
}
}
self
end
def clear
`$deny_frozen_access(self)`
`self.splice(0, self.length)`
self
end
def count(object = undefined, &block)
if `object !== undefined` || block
super
else
size
end
end
def initialize_copy(other)
replace other
end
def collect(&block)
return enum_for(:collect) { size } unless block_given?
%x{
var result = [];
for (var i = 0; i < self.length; i++) {
var value = $yield1(block, self[i]);
result[i] = value;
}
return result;
}
end
def collect!(&block)
return enum_for(:collect!) { size } unless block_given?
%x{
$deny_frozen_access(self);
for (var i = 0; i < self.length; i++) {
var value = $yield1(block, self[i]);
self[i] = value;
}
}
self
end
%x{
function binomial_coefficient(n, k) {
if (n === k || k === 0) {
return 1;
}
if (k > 0 && n > k) {
return binomial_coefficient(n - 1, k - 1) + binomial_coefficient(n - 1, k);
}
return 0;
}
}
def combination(n)
num = ::Opal.coerce_to! n, ::Integer, :to_int
return enum_for(:combination, num) { `binomial_coefficient(#{self}.length, num)` } unless block_given?
%x{
var i, length, stack, chosen, lev, done, next;
if (num === 0) {
#{yield []}
} else if (num === 1) {
for (i = 0, length = self.length; i < length; i++) {
#{yield `[self[i]]`}
}
}
else if (num === self.length) {
#{yield `self.slice()`}
}
else if (num >= 0 && num < self.length) {
stack = [];
for (i = 0; i <= num + 1; i++) {
stack.push(0);
}
chosen = [];
lev = 0;
done = false;
stack[0] = -1;
while (!done) {
chosen[lev] = self[stack[lev+1]];
while (lev < num - 1) {
lev++;
next = stack[lev+1] = stack[lev] + 1;
chosen[lev] = self[next];
}
#{ yield `chosen.slice()` }
lev++;
do {
done = (lev === 0);
stack[lev]++;
lev--;
} while ( stack[lev+1] + num === self.length + lev + 1 );
}
}
}
self
end
def repeated_combination(n)
num = ::Opal.coerce_to! n, ::Integer, :to_int
unless block_given?
return enum_for(:repeated_combination, num) { `binomial_coefficient(self.length + num - 1, num)` }
end
%x{
function iterate(max, from, buffer, self) {
if (buffer.length == max) {
var copy = buffer.slice();
#{yield `copy`}
return;
}
for (var i = from; i < self.length; i++) {
buffer.push(self[i]);
iterate(max, i, buffer, self);
buffer.pop();
}
}
if (num >= 0) {
iterate(num, 0, [], self);
}
}
self
end
def compact
%x{
var result = [];
for (var i = 0, length = self.length, item; i < length; i++) {
item = self[i];
if (item !== nil && item != null) {
result.push(item);
}
}
return result;
}
end
def compact!
%x{
$deny_frozen_access(self);
var original = self.length;
for (var i = 0, length = self.length, item; i < length; i++) {
item = self[i];
if (item === nil || item == null) {
self.splice(i, 1);
length--;
i--;
}
}
return self.length === original ? nil : self;
}
end
def concat(*others)
`$deny_frozen_access(self)`
others = others.map do |other|
`other = convertToArray(other)`
if other.equal?(self)
other = other.dup
end
other
end
others.each do |other|
%x{
for (var i = 0, length = other.length; i < length; i++) {
self.push(other[i]);
}
}
end
self
end
def delete(object)
%x{
var original = self.length;
for (var i = 0, length = original; i < length; i++) {
if (#{`self[i]` == object}) {
$deny_frozen_access(self);
self.splice(i, 1);
length--;
i--;
}
}
if (self.length === original) {
if (#{block_given?}) {
return #{yield};
}
return nil;
}
return object;
}
end
def delete_at(index)
%x{
$deny_frozen_access(self);
index = $coerce_to(index, #{::Integer}, 'to_int');
if (index < 0) {
index += self.length;
}
if (index < 0 || index >= self.length) {
return nil;
}
var result = self[index];
self.splice(index, 1);
return result;
}
end
def delete_if(&block)
return enum_for(:delete_if) { size } unless block_given?
%x{
$deny_frozen_access(self);
filterIf(self, $falsy, block)
}
self
end
def difference(*arrays)
arrays.reduce(to_a.dup) { |a, b| a - b }
end
def dig(idx, *idxs)
item = self[idx]
%x{
if (item === nil || idxs.length === 0) {
return item;
}
}
unless item.respond_to?(:dig)
::Kernel.raise ::TypeError, "#{item.class} does not have #dig method"
end
item.dig(*idxs)
end
def drop(number)
%x{
number = $coerce_to(number, #{::Integer}, 'to_int');
if (number < 0) {
#{::Kernel.raise ::ArgumentError}
}
return self.slice(number);
}
end
def dup
%x{
if (self.$$class === Opal.Array &&
self.$$class.$allocate.$$pristine &&
self.$copy_instance_variables.$$pristine &&
self.$initialize_dup.$$pristine) {
return self.slice(0);
}
}
super
end
def each(&block)
return enum_for(:each) { size } unless block_given?
%x{
for (var i = 0; i < self.length; i++) {
$yield1(block, self[i]);
}
}
self
end
def each_index(&block)
return enum_for(:each_index) { size } unless block_given?
%x{
for (var i = 0; i < self.length; i++) {
$yield1(block, i);
}
}
self
end
def empty?
`self.length === 0`
end
def eql?(other)
%x{
var recursed = {};
function _eql(array, other) {
var i, length, a, b;
if (!other.$$is_array) {
return false;
}
other = #{other.to_a};
if (array.length !== other.length) {
return false;
}
recursed[#{`array`.object_id}] = true;
for (i = 0, length = array.length; i < length; i++) {
a = array[i];
b = other[i];
if (a.$$is_array) {
if (b.$$is_array && b.length !== a.length) {
return false;
}
if (!recursed.hasOwnProperty(#{`a`.object_id})) {
if (!_eql(a, b)) {
return false;
}
}
} else {
if (!#{`a`.eql?(`b`)}) {
return false;
}
}
}
return true;
}
return _eql(self, other);
}
end
def fetch(index, defaults = undefined, &block)
%x{
var original = index;
index = $coerce_to(index, #{::Integer}, 'to_int');
if (index < 0) {
index += self.length;
}
if (index >= 0 && index < self.length) {
return self[index];
}
if (block !== nil && defaults != null) {
#{warn('warning: block supersedes default value argument')}
}
if (block !== nil) {
return block(original);
}
if (defaults != null) {
return defaults;
}
if (self.length === 0) {
#{::Kernel.raise ::IndexError, "index #{`original`} outside of array bounds: 0...0"}
}
else {
#{::Kernel.raise ::IndexError, "index #{`original`} outside of array bounds: -#{`self.length`}...#{`self.length`}"};
}
}
end
def fill(*args, &block)
%x{
$deny_frozen_access(self);
var i, length, value;
}
if block
if `args.length > 2`
::Kernel.raise ::ArgumentError, "wrong number of arguments (#{args.length} for 0..2)"
end
one, two = args
else
if `args.length == 0`
::Kernel.raise ::ArgumentError, 'wrong number of arguments (0 for 1..3)'
elsif `args.length > 3`
::Kernel.raise ::ArgumentError, "wrong number of arguments (#{args.length} for 1..3)"
end
obj, one, two = args
end
if ::Range === one
::Kernel.raise ::TypeError, 'length invalid with range' if two
left = `one.begin === nil ? 0 : $coerce_to(one.begin, #{::Integer}, 'to_int')`
`left += this.length` if `left < 0`
::Kernel.raise ::RangeError, "#{one.inspect} out of range" if `left < 0`
right = `one.end === nil ? -1 : $coerce_to(one.end, #{::Integer}, 'to_int')`
`right += this.length` if `right < 0`
`right += 1` unless one.exclude_end?
return self if `right <= left`
elsif one
left = `$coerce_to(one, #{::Integer}, 'to_int')`
`left += this.length` if `left < 0`
left = 0 if `left < 0`
if two
right = `$coerce_to(two, #{::Integer}, 'to_int')`
return self if `right == 0`
`right += left`
else
right = `this.length`
end
else
left = 0
right = `this.length`
end
if `left > this.length`
%x{
for (i = this.length; i < right; i++) {
self[i] = nil;
}
}
end
if `right > this.length`
`this.length = right`
end
if block
%x{
for (length = this.length; left < right; left++) {
value = block(left);
self[left] = value;
}
}
else
%x{
for (length = this.length; left < right; left++) {
self[left] = #{obj};
}
}
end
self
end
def first(count = undefined)
%x{
if (count == null) {
return self.length === 0 ? nil : self[0];
}
count = $coerce_to(count, #{::Integer}, 'to_int');
if (count < 0) {
#{::Kernel.raise ::ArgumentError, 'negative array size'};
}
return self.slice(0, count);
}
end
def flatten(level = undefined)
%x{
function _flatten(array, level) {
var result = [],
i, length,
item, ary;
array = #{`array`.to_a};
for (i = 0, length = array.length; i < length; i++) {
item = array[i];
if (!$respond_to(item, '$to_ary', true)) {
result.push(item);
continue;
}
ary = #{`item`.to_ary};
if (ary === nil) {
result.push(item);
continue;
}
if (!ary.$$is_array) {
#{::Kernel.raise ::TypeError, "can't convert #{`ary`.class} into Array (#{`ary`.class}#to_ary gives #{`ary`.class})"};
}
if (ary === self || ary === array) {
#{::Kernel.raise ::ArgumentError, 'tried to flatten recursive array'};
}
switch (level) {
case undefined:
result = result.concat(_flatten(ary));
break;
case 0:
result.push(ary);
break;
default:
fast_push(result, _flatten(ary, level - 1));
}
}
return result;
}
if (level !== undefined) {
level = $coerce_to(level, #{::Integer}, 'to_int');
}
return _flatten(self, level);
}
end
def flatten!(level = undefined)
%x{
$deny_frozen_access(self);
var flattened = #{flatten level};
if (self.length == flattened.length) {
for (var i = 0, length = self.length; i < length; i++) {
if (self[i] !== flattened[i]) {
break;
}
}
if (i == length) {
return nil;
}
}
#{replace `flattened`};
}
self
end
def freeze
return self if frozen?
`$freeze(self)`
end
`var $hash_ids`
def hash
%x{
var top = ($hash_ids === undefined),
result = $opal32_init(),
hash_id = self.$object_id(),
item, i, key, values;
result = $opal32_add(result, 0xA);
result = $opal32_add(result, self.length);
if (top) {
$hash_ids = new Map();
}
// return early for recursive structures
else if ($hash_ids.has(hash_id)) {
return $opal32_add(result, 0x01010101);
}
try {
if (!top) {
values = $hash_ids.values();
for (item of values) {
if (#{eql?(`item`)}) {
return $opal32_add(result, 0x01010101);
}
}
}
$hash_ids.set(hash_id, self);
for (i = 0; i < self.length; i++) {
item = self[i];
result = $opal32_add(result, item.$hash());
}
return result;
} finally {
if (top) {
$hash_ids = undefined;
}
}
}
end
def include?(member)
%x{
for (var i = 0, length = self.length; i < length; i++) {
if ($eqeq(self[i], member)) {
return true;
}
}
return false;
}
end
def index(object = undefined, &block)
%x{
var i, length, value;
if (object != null && block !== nil) {
#{warn('warning: given block not used')}
}
if (object != null) {
for (i = 0, length = self.length; i < length; i++) {
if (#{`self[i]` == object}) {
return i;
}
}
}
else if (block !== nil) {
for (i = 0; i < self.length; i++) {
value = block(self[i]);
if (value !== false && value !== nil) {
return i;
}
}
}
else {
return #{enum_for :index};
}
return nil;
}
end
def insert(index, *objects)
%x{
$deny_frozen_access(self);
index = $coerce_to(index, #{::Integer}, 'to_int');
if (objects.length > 0) {
if (index < 0) {
index += self.length + 1;
if (index < 0) {
#{ ::Kernel.raise ::IndexError, "#{index} is out of bounds" };
}
}
if (index > self.length) {
for (var i = self.length; i < index; i++) {
self.push(nil);
}
}
self.splice.apply(self, [index, 0].concat(objects));
}
}
self
end
`var inspect_stack = []`
def inspect
%x{
var result = [],
id = #{__id__},
pushed = true;
}
begin
%x{
if (inspect_stack.indexOf(id) !== -1) {
pushed = false;
return '[...]';
}
inspect_stack.push(id)
for (var i = 0, length = self.length; i < length; i++) {
var item = #{self[`i`]};
result.push(#{Opal.inspect(`item`)});
}
return '[' + result.join(', ') + ']';
}
nil
ensure
`if (pushed) inspect_stack.pop()`
end
end
def intersection(*arrays)
%x{
if (arrays.length === 0) {
return #{to_a.dup};
}
arrays = arrays.map(convertToArray);
if (self.length === 0) {
return [];
}
}
arrays = arrays.sort_by(&:length)
# When self is the smallest among the arrays
if `self.length < arrays[0].length`
return arrays.reduce(self, &:&)
end
# First, calculate intersection of argument arrays.
# Array#& is faster when the argument size is small.
# So `largest & shortest & second_shortest & ...` would be the fastest.
largest = `arrays.pop()`
intersection_of_args = arrays.reduce(largest, &:&)
# self array must come last to maintain the order
self & intersection_of_args
end
def intersect?(other)
%x{
var small, large, hash = #{{}}, i, length;
if (self.length < other.length) {
small = self;
large = other;
} else {
small = other;
large = self;
}
for (i = 0, length = small.length; i < length; i++) {
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | true |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/set.rb | opal/corelib/set.rb | # helpers: freeze
# backtick_javascript: true
# use_strict: true
# Portions Copyright (c) 2002-2013 Akinori MUSHA <knu@iDaemons.org>
class ::Set
include ::Enumerable
def self.[](*ary)
new(ary)
end
def initialize(enum = nil, &block)
@hash = {}
return if enum.nil?
::Kernel.raise ::ArgumentError, 'value must be enumerable' unless ::Enumerable === enum
if block
enum.each { |item| add yield(item) }
else
merge(enum)
end
end
def dup
result = self.class.new
result.merge(self)
end
def -(enum)
unless enum.respond_to? :each
::Kernel.raise ::ArgumentError, 'value must be enumerable'
end
dup.subtract(enum)
end
def inspect
"#<Set: {#{to_a.join(',')}}>"
end
def ==(other)
if equal?(other)
true
elsif other.instance_of?(self.class)
@hash == other.instance_variable_get(:@hash)
elsif other.is_a?(::Set) && size == other.size
other.all? { |o| @hash.include?(o) }
else
false
end
end
def add(o)
@hash[o] = true
self
end
def classify(&block)
return enum_for(:classify) unless block_given?
result = ::Hash.new { |h, k| h[k] = self.class.new }
each { |item| result[yield(item)].add item }
result
end
def collect!(&block)
return enum_for(:collect!) unless block_given?
result = self.class.new
each { |item| result << yield(item) }
replace result
end
def compare_by_identity
if @hash.respond_to?(:compare_by_identity)
@hash.compare_by_identity
self
else
raise NotImplementedError, "#{self.class.name}\##{__method__} is not implemented"
end
end
def compare_by_identity?
@hash.respond_to?(:compare_by_identity?) && @hash.compare_by_identity?
end
def delete(o)
@hash.delete(o)
self
end
def delete?(o)
if include?(o)
delete(o)
self
end
end
def delete_if
return enum_for(:delete_if) unless block_given?
# @hash.delete_if should be faster, but using it breaks the order
# of enumeration in subclasses.
select { |o| yield o }.each { |o| @hash.delete(o) }
self
end
def freeze
return self if frozen?
@hash.freeze
`$freeze(self)`
end
def keep_if
return enum_for(:keep_if) unless block_given?
reject { |o| yield o }.each { |o| @hash.delete(o) }
self
end
def reject!(&block)
return enum_for(:reject!) unless block_given?
before = size
delete_if(&block)
size == before ? nil : self
end
def select!(&block)
return enum_for(:select!) unless block_given?
before = size
keep_if(&block)
size == before ? nil : self
end
def add?(o)
if include?(o)
nil
else
add(o)
end
end
def each(&block)
return enum_for(:each) unless block_given?
@hash.each_key(&block)
self
end
def empty?
@hash.empty?
end
def eql?(other)
@hash.eql?(other.instance_eval { @hash })
end
def clear
@hash.clear
self
end
def include?(o)
@hash.include?(o)
end
def merge(enum)
enum.each { |item| add item }
self
end
def replace(enum)
clear
merge(enum)
self
end
def size
@hash.size
end
def subtract(enum)
enum.each { |item| delete item }
self
end
def |(enum)
unless enum.respond_to? :each
::Kernel.raise ::ArgumentError, 'value must be enumerable'
end
dup.merge(enum)
end
%x{
function is_set(set) {
#{`set`.is_a?(::Set) || ::Kernel.raise(::ArgumentError, 'value must be a set')}
}
}
def superset?(set)
`is_set(set)`
return false if size < set.size
set.all? { |o| include?(o) }
end
def proper_superset?(set)
`is_set(set)`
return false if size <= set.size
set.all? { |o| include?(o) }
end
def subset?(set)
`is_set(set)`
return false if set.size < size
all? { |o| set.include?(o) }
end
def proper_subset?(set)
`is_set(set)`
return false if set.size <= size
all? { |o| set.include?(o) }
end
def intersect?(set)
`is_set(set)`
if size < set.size
any? { |o| set.include?(o) }
else
set.any? { |o| include?(o) }
end
end
def disjoint?(set)
!intersect?(set)
end
def to_a
@hash.keys
end
alias + |
alias < proper_subset?
alias << add
alias <= subset?
alias > proper_superset?
alias >= superset?
alias difference -
alias filter! select!
alias length size
alias map! collect!
alias member? include?
alias union |
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/time.rb | opal/corelib/time.rb | # helpers: slice, deny_frozen_access
# backtick_javascript: true
# use_strict: true
require 'corelib/comparable'
class ::Time < `Date`
include ::Comparable
%x{
var days_of_week = #{%w[Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sunday]},
short_days = #{%w[Sun Mon Tue Wed Thu Fri Sat]},
short_months = #{%w[Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec]},
long_months = #{%w[January February March April May June July August September October November December]};
}
def self.at(seconds, frac = undefined, unit = :microsecond)
%x{
var result;
if (#{::Time === seconds}) {
if (frac !== undefined) {
#{::Kernel.raise ::TypeError, "can't convert Time into an exact number"}
}
result = new Date(seconds.getTime());
result.timezone = seconds.timezone;
return result;
}
if (!seconds.$$is_number) {
seconds = #{::Opal.coerce_to!(seconds, ::Integer, :to_int)};
}
if (frac === undefined) {
return new Date(seconds * 1000);
}
if (!frac.$$is_number) {
frac = #{::Opal.coerce_to!(frac, ::Integer, :to_int)};
}
let value;
switch (unit) {
case "millisecond": value = seconds * 1000 + frac; break;
case "microsecond": value = seconds * 1000 + frac / 1_000; break;
case "nanosecond": value = seconds * 1000 + frac / 1_000_000; break;
default:
#{::Kernel.raise ::ArgumentError, "unexpected unit: #{unit}"}
}
return new Date(value);
}
end
%x{
function time_params(year, month, day, hour, min, sec) {
if (year.$$is_string) {
year = parseInt(year, 10);
} else {
year = #{::Opal.coerce_to!(`year`, ::Integer, :to_int)};
}
if (month === nil) {
month = 1;
} else if (!month.$$is_number) {
if (#{`month`.respond_to?(:to_str)}) {
month = #{`month`.to_str};
switch (month.toLowerCase()) {
case 'jan': month = 1; break;
case 'feb': month = 2; break;
case 'mar': month = 3; break;
case 'apr': month = 4; break;
case 'may': month = 5; break;
case 'jun': month = 6; break;
case 'jul': month = 7; break;
case 'aug': month = 8; break;
case 'sep': month = 9; break;
case 'oct': month = 10; break;
case 'nov': month = 11; break;
case 'dec': month = 12; break;
default: month = #{`month`.to_i};
}
} else {
month = #{::Opal.coerce_to!(`month`, ::Integer, :to_int)};
}
}
if (month < 1 || month > 12) {
#{::Kernel.raise ::ArgumentError, "month out of range: #{`month`}"}
}
month = month - 1;
if (day === nil) {
day = 1;
} else if (day.$$is_string) {
day = parseInt(day, 10);
} else {
day = #{::Opal.coerce_to!(`day`, ::Integer, :to_int)};
}
if (day < 1 || day > 31) {
#{::Kernel.raise ::ArgumentError, "day out of range: #{`day`}"}
}
if (hour === nil) {
hour = 0;
} else if (hour.$$is_string) {
hour = parseInt(hour, 10);
} else {
hour = #{::Opal.coerce_to!(`hour`, ::Integer, :to_int)};
}
if (hour < 0 || hour > 24) {
#{::Kernel.raise ::ArgumentError, "hour out of range: #{`hour`}"}
}
if (min === nil) {
min = 0;
} else if (min.$$is_string) {
min = parseInt(min, 10);
} else {
min = #{::Opal.coerce_to!(`min`, ::Integer, :to_int)};
}
if (min < 0 || min > 59) {
#{::Kernel.raise ::ArgumentError, "min out of range: #{`min`}"}
}
if (sec === nil) {
sec = 0;
} else if (!sec.$$is_number) {
if (sec.$$is_string) {
sec = parseInt(sec, 10);
} else {
sec = #{::Opal.coerce_to!(`sec`, ::Integer, :to_int)};
}
}
if (sec < 0 || sec > 60) {
#{::Kernel.raise ::ArgumentError, "sec out of range: #{`sec`}"}
}
return [year, month, day, hour, min, sec];
}
}
def self.new(year = undefined, month = nil, day = nil, hour = nil, min = nil, sec = nil, utc_offset = nil)
%x{
var args, result, timezone, utc_date;
if (year === undefined) {
return new Date();
}
args = time_params(year, month, day, hour, min, sec);
year = args[0];
month = args[1];
day = args[2];
hour = args[3];
min = args[4];
sec = args[5];
if (utc_offset === nil) {
result = new Date(year, month, day, hour, min, 0, sec * 1000);
if (year < 100) {
result.setFullYear(year);
}
return result;
}
timezone = #{_parse_offset(utc_offset)};
utc_date = new Date(Date.UTC(year, month, day, hour, min, 0, sec * 1000));
if (year < 100) {
utc_date.setUTCFullYear(year);
}
result = new Date(utc_date.getTime() - timezone * 3600000);
result.timezone = timezone;
return result;
}
end
# @private
def self._parse_offset(utc_offset)
%x{
var timezone;
if (utc_offset.$$is_string) {
if (utc_offset == 'UTC') {
timezone = 0;
}
else if(/^[+-]\d\d:[0-5]\d$/.test(utc_offset)) {
var sign, hours, minutes;
sign = utc_offset[0];
hours = +(utc_offset[1] + utc_offset[2]);
minutes = +(utc_offset[4] + utc_offset[5]);
timezone = (sign == '-' ? -1 : 1) * (hours + minutes / 60);
}
else {
// Unsupported: "A".."I","K".."Z"
#{::Kernel.raise ::ArgumentError, %'"+HH:MM", "-HH:MM", "UTC" expected for utc_offset: #{utc_offset}'}
}
}
else if (utc_offset.$$is_number) {
timezone = utc_offset / 3600;
}
else {
#{::Kernel.raise ::ArgumentError, "Opal doesn't support other types for a timezone argument than Integer and String"}
}
return timezone;
}
end
def self.local(year, month = nil, day = nil, hour = nil, min = nil, sec = nil, millisecond = nil, _dummy1 = nil, _dummy2 = nil, _dummy3 = nil)
# The _dummy args are there only because the MRI version accepts up to 10 arguments
%x{
var args, result;
if (arguments.length === 10) {
args = $slice(arguments);
year = args[5];
month = args[4];
day = args[3];
hour = args[2];
min = args[1];
sec = args[0];
}
args = time_params(year, month, day, hour, min, sec);
year = args[0];
month = args[1];
day = args[2];
hour = args[3];
min = args[4];
sec = args[5];
result = new Date(year, month, day, hour, min, 0, sec * 1000);
if (year < 100) {
result.setFullYear(year);
}
return result;
}
end
def self.gm(year, month = nil, day = nil, hour = nil, min = nil, sec = nil, millisecond = nil, _dummy1 = nil, _dummy2 = nil, _dummy3 = nil)
# The _dummy args are there only because the MRI version accepts up to 10 arguments
%x{
var args, result;
if (arguments.length === 10) {
args = $slice(arguments);
year = args[5];
month = args[4];
day = args[3];
hour = args[2];
min = args[1];
sec = args[0];
}
args = time_params(year, month, day, hour, min, sec);
year = args[0];
month = args[1];
day = args[2];
hour = args[3];
min = args[4];
sec = args[5];
result = new Date(Date.UTC(year, month, day, hour, min, 0, sec * 1000));
if (year < 100) {
result.setUTCFullYear(year);
}
result.timezone = 0;
return result;
}
end
def self.now
new
end
def +(other)
if ::Time === other
::Kernel.raise ::TypeError, 'time + time?'
end
%x{
if (!other.$$is_number) {
other = #{::Opal.coerce_to!(other, ::Integer, :to_int)};
}
var result = new Date(self.getTime() + (other * 1000));
result.timezone = self.timezone;
return result;
}
end
def -(other)
if ::Time === other
return `(self.getTime() - other.getTime()) / 1000`
end
%x{
if (!other.$$is_number) {
other = #{::Opal.coerce_to!(other, ::Integer, :to_int)};
}
var result = new Date(self.getTime() - (other * 1000));
result.timezone = self.timezone;
return result;
}
end
def <=>(other)
if ::Time === other
to_f <=> other.to_f
else
r = other <=> self
if r.nil?
nil
elsif r > 0
-1
elsif r < 0
1
else
0
end
end
end
def ==(other)
::Time === other && `#{to_f} === #{other.to_f}`
end
def asctime
strftime '%a %b %e %H:%M:%S %Y'
end
[
[:year, 'getFullYear', 'getUTCFullYear'],
[:mon, 'getMonth', 'getUTCMonth', 1],
[:wday, 'getDay', 'getUTCDay'],
[:day, 'getDate', 'getUTCDate'],
[:hour, 'getHours', 'getUTCHours'],
[:min, 'getMinutes', 'getUTCMinutes'],
[:sec, 'getSeconds', 'getUTCSeconds'],
].each do |method, getter, utcgetter, difference = 0|
define_method method do
%x{
return difference + ((self.timezone != null) ?
(new Date(self.getTime() + self.timezone * 3600000))[utcgetter]() :
self[getter]())
}
end
end
def yday
# http://javascript.about.com/library/bldayyear.htm
# also see moment.js implementation: http://git.io/vCKNE
start_of_year = Time.new(year).to_i
start_of_day = Time.new(year, month, day).to_i
one_day = 86_400
((start_of_day - start_of_year) / one_day).round + 1
end
def isdst
%x{
var jan = new Date(self.getFullYear(), 0, 1),
jul = new Date(self.getFullYear(), 6, 1);
return self.getTimezoneOffset() < Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
end
def dup
copy = `new Date(self.getTime())`
copy.copy_instance_variables(self)
copy.initialize_dup(self)
copy
end
def eql?(other)
other.is_a?(::Time) && (self <=> other).zero?
end
[
[:sunday?, 0],
[:monday?, 1],
[:tuesday?, 2],
[:wednesday?, 3],
[:thursday?, 4],
[:friday?, 5],
[:saturday?, 6]
].each do |method, weekday|
define_method method do
`#{wday} === weekday`
end
end
def hash
[::Time, `self.getTime()`].hash
end
def inspect
if utc?
strftime '%Y-%m-%d %H:%M:%S UTC'
else
strftime '%Y-%m-%d %H:%M:%S %z'
end
end
def succ
%x{
var result = new Date(self.getTime() + 1000);
result.timezone = self.timezone;
return result;
}
end
def usec
`self.getMilliseconds() * 1000`
end
def zone
%x{
if (self.timezone === 0) return "UTC";
else if (self.timezone != null) return nil;
var string = self.toString(),
result;
if (string.indexOf('(') == -1) {
result = string.match(/[A-Z]{3,4}/)[0];
}
else {
result = string.match(/\((.+)\)(?:\s|$)/)[1]
}
if (result == "GMT" && /(GMT\W*\d{4})/.test(string)) {
return RegExp.$1;
}
else {
return result;
}
}
end
def getgm
%x{
var result = new Date(self.getTime());
result.timezone = 0;
return result;
}
end
def gmtime
%x{
if (self.timezone !== 0) {
$deny_frozen_access(self);
self.timezone = 0;
}
return self;
}
end
def gmt?
`self.timezone === 0`
end
def gmt_offset
`(self.timezone != null) ? self.timezone * 60 : -self.getTimezoneOffset() * 60`
end
def strftime(format)
%x{
return format.replace(/%([\-_#^0]*:{0,2})(\d+)?([EO]*)(.)/g, function(full, flags, width, _, conv) {
var result = "", jd, c, s,
zero = flags.indexOf('0') !== -1,
pad = flags.indexOf('-') === -1,
blank = flags.indexOf('_') !== -1,
upcase = flags.indexOf('^') !== -1,
invert = flags.indexOf('#') !== -1,
colons = (flags.match(':') || []).length;
width = parseInt(width, 10);
if (zero && blank) {
if (flags.indexOf('0') < flags.indexOf('_')) {
zero = false;
}
else {
blank = false;
}
}
switch (conv) {
case 'Y':
result += #{year};
break;
case 'C':
zero = !blank;
result += Math.round(#{year} / 100);
break;
case 'y':
zero = !blank;
result += (#{year} % 100);
break;
case 'm':
zero = !blank;
result += #{mon};
break;
case 'B':
result += long_months[#{mon} - 1];
break;
case 'b':
case 'h':
blank = !zero;
result += short_months[#{mon} - 1];
break;
case 'd':
zero = !blank
result += #{day};
break;
case 'e':
blank = !zero
result += #{day};
break;
case 'j':
zero = !blank;
width = isNaN(width) ? 3 : width;
result += #{yday};
break;
case 'H':
zero = !blank;
result += #{hour};
break;
case 'k':
blank = !zero;
result += #{hour};
break;
case 'I':
zero = !blank;
result += (#{hour} % 12 || 12);
break;
case 'l':
blank = !zero;
result += (#{hour} % 12 || 12);
break;
case 'P':
result += (#{hour} >= 12 ? "pm" : "am");
break;
case 'p':
result += (#{hour} >= 12 ? "PM" : "AM");
break;
case 'M':
zero = !blank;
result += #{min};
break;
case 'S':
zero = !blank;
result += #{sec}
break;
case 'L':
zero = !blank;
width = isNaN(width) ? 3 : width;
result += self.getMilliseconds();
break;
case 'N':
width = isNaN(width) ? 9 : width;
result += #{`self.getMilliseconds().toString()`.rjust(3, '0')};
result = #{`result`.ljust(`width`, '0')};
break;
case 'z':
var offset = (self.timezone == null) ? self.getTimezoneOffset() : (-self.timezone * 60),
hours = Math.floor(Math.abs(offset) / 60),
minutes = Math.abs(offset) % 60;
result += offset < 0 ? "+" : "-";
result += hours < 10 ? "0" : "";
result += hours;
if (colons > 0) {
result += ":";
}
result += minutes < 10 ? "0" : "";
result += minutes;
if (colons > 1) {
result += ":00";
}
break;
case 'Z':
result += #{zone};
break;
case 'A':
result += days_of_week[#{wday}];
break;
case 'a':
result += short_days[#{wday}];
break;
case 'u':
result += (#{wday} + 1);
break;
case 'w':
result += #{wday};
break;
case 'V':
result += #{cweek_cyear[0].to_s.rjust(2, '0')};
break;
case 'G':
result += #{cweek_cyear[1]};
break;
case 'g':
result += #{cweek_cyear[1][-2..-1]};
break;
case 's':
result += #{to_i};
break;
case 'n':
result += "\n";
break;
case 't':
result += "\t";
break;
case '%':
result += "%";
break;
case 'c':
result += #{strftime('%a %b %e %T %Y')};
break;
case 'D':
case 'x':
result += #{strftime('%m/%d/%y')};
break;
case 'F':
result += #{strftime('%Y-%m-%d')};
break;
case 'v':
result += #{strftime('%e-%^b-%4Y')};
break;
case 'r':
result += #{strftime('%I:%M:%S %p')};
break;
case 'R':
result += #{strftime('%H:%M')};
break;
case 'T':
case 'X':
result += #{strftime('%H:%M:%S')};
break;
// Non-standard: JIS X 0301 date format
case 'J':
jd = #{to_date.jd};
if (jd < 2405160) {
result += #{strftime('%Y-%m-%d')};
break;
}
else if (jd < 2419614)
c = 'M', s = 1867;
else if (jd < 2424875)
c = 'T', s = 1911;
else if (jd < 2447535)
c = 'S', s = 1925;
else if (jd < 2458605)
c = 'H', s = 1988;
else
c = 'R', s = 2018;
result += #{format '%c%02d', `c`, year - `s`};
result += #{strftime('-%m-%d')};
break;
default:
return full;
}
if (upcase) {
result = result.toUpperCase();
}
if (invert) {
result = result.replace(/[A-Z]/, function(c) { c.toLowerCase() }).
replace(/[a-z]/, function(c) { c.toUpperCase() });
}
if (pad && (zero || blank)) {
result = #{`result`.rjust(`isNaN(width) ? 2 : width`, `blank ? " " : "0"`)};
}
return result;
});
}
end
def to_a
[sec, min, hour, day, month, year, wday, yday, isdst, zone]
end
def to_f
`self.getTime() / 1000`
end
def to_i
`parseInt(self.getTime() / 1000, 10)`
end
def cweek_cyear
jan01 = ::Time.new(year, 1, 1)
jan01_wday = jan01.wday
first_monday = 0
year = self.year
if jan01_wday <= 4 && jan01_wday != 0
# Jan 01 is in the first week of the year
offset = jan01_wday - 1
else
# Jan 01 is in the last week of the previous year
offset = jan01_wday - 7 - 1
offset = -1 if offset == -8 # Adjust if Jan 01 is a Sunday
end
total = yday + offset
week = `Math.ceil(total / 7)`
if week <= 0
# Get the last week of the previous year
return ::Time.new(self.year - 1, 12, 31).cweek_cyear
elsif week == 53
# Find out whether this is actually week 53 or already week 01 of the following year
dec31 = ::Time.new(self.year, 12, 31)
dec31_wday = dec31.wday
if dec31_wday <= 3 && dec31_wday != 0
week = 1
year += 1
end
end
[week, year]
end
class << self
alias mktime local
alias utc gm
end
alias ctime asctime
alias dst? isdst
alias getutc getgm
alias gmtoff gmt_offset
alias mday day
alias month mon
alias to_s inspect
alias tv_sec to_i
alias tv_usec usec
alias utc gmtime
alias utc? gmt?
alias utc_offset gmt_offset
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/file.rb | opal/corelib/file.rb | # helpers: truthy
# backtick_javascript: true
class ::File < ::IO
Separator = SEPARATOR = '/'
ALT_SEPARATOR = nil
PATH_SEPARATOR = ':'
# Assuming case insenstive filesystem
FNM_SYSCASE = 0
windows_root_rx = %r{^[a-zA-Z]:(?:\\|\/)}
class << self
def absolute_path(path, basedir = nil)
sep = SEPARATOR
sep_chars = `$sep_chars()`
new_parts = []
path = path.respond_to?(:to_path) ? path.to_path : path
path = ::Opal.coerce_to!(`path`, ::String, :to_str)
basedir ||= ::Dir.pwd
path_abs = `path.substr(0, sep.length) === sep || windows_root_rx.test(path)`
basedir_abs = `basedir.substr(0, sep.length) === sep || windows_root_rx.test(basedir)`
if path_abs
parts = path.split(/[#{sep_chars}]/)
leading_sep = `windows_root_rx.test(path) ? '' : #{path.sub(/^([#{sep_chars}]+).*$/, '\1')}`
abs = true
else
parts = basedir.split(/[#{sep_chars}]/) + path.split(/[#{sep_chars}]/)
leading_sep = `windows_root_rx.test(basedir) ? '' : #{basedir.sub(/^([#{sep_chars}]+).*$/, '\1')}`
abs = basedir_abs
end
%x{
var part;
for (var i = 0, ii = parts.length; i < ii; i++) {
part = parts[i];
if (
(part === nil) ||
(part == '' && ((new_parts.length === 0) || abs)) ||
(part == '.' && ((new_parts.length === 0) || abs))
) {
continue;
}
if (part == '..') {
new_parts.pop();
} else {
new_parts.push(part);
}
}
if (!abs && parts[0] != '.') {
#{new_parts.unshift '.'}
}
}
new_path = new_parts.join(sep)
new_path = leading_sep + new_path if abs
new_path
end
def expand_path(path, basedir = nil)
sep = SEPARATOR
sep_chars = `$sep_chars()`
if `path[0] === '~' || (basedir && basedir[0] === '~')`
home = Dir.home
::Kernel.raise(::ArgumentError, "couldn't find HOME environment -- expanding `~'") unless home
leading_sep = `windows_root_rx.test(home) ? '' : #{home.sub(/^([#{sep_chars}]+).*$/, '\1')}`
::Kernel.raise(::ArgumentError, 'non-absolute home') unless home.start_with?(leading_sep)
home += sep
home_path_regexp = /^\~(?:#{sep}|$)/
path = path.sub(home_path_regexp, home)
basedir = basedir.sub(home_path_regexp, home) if basedir
end
absolute_path(path, basedir)
end
%x{
// Coerce a given path to a path string using #to_path and #to_str
function $coerce_to_path(path) {
if ($truthy(#{`path`.respond_to?(:to_path)})) {
path = path.$to_path();
}
path = #{::Opal.coerce_to!(`path`, ::String, :to_str)};
return path;
}
// Return a RegExp compatible char class
function $sep_chars() {
if (#{ALT_SEPARATOR} === nil) {
return Opal.escape_regexp(#{SEPARATOR});
} else {
return Opal.escape_regexp(#{SEPARATOR + ALT_SEPARATOR});
}
}
}
def dirname(path, level = 1)
return path if level == 0
::Kernel.raise ::ArgumentError, "level can't be negative" if level < 0
sep_chars = `$sep_chars()`
path = `$coerce_to_path(path)`
%x{
var absolute = path.match(new RegExp(#{"^[#{sep_chars}]"})), out;
path = path.replace(new RegExp(#{"[#{sep_chars}]+$"}), ''); // remove trailing separators
path = path.replace(new RegExp(#{"[^#{sep_chars}]+$"}), ''); // remove trailing basename
path = path.replace(new RegExp(#{"[#{sep_chars}]+$"}), ''); // remove final trailing separators
if (path === '') {
out = absolute ? '/' : '.';
}
else {
out = path;
}
if (level == 1) {
return out;
}
else {
return #{dirname(`out`, level - 1)}
}
}
end
def basename(name, suffix = nil)
sep_chars = `$sep_chars()`
name = `$coerce_to_path(name)`
%x{
if (name.length == 0) {
return name;
}
if (suffix !== nil) {
suffix = #{::Opal.coerce_to!(suffix, ::String, :to_str)}
} else {
suffix = null;
}
name = name.replace(new RegExp(#{"(.)[#{sep_chars}]*$"}), '$1');
name = name.replace(new RegExp(#{"^(?:.*[#{sep_chars}])?([^#{sep_chars}]+)$"}), '$1');
if (suffix === ".*") {
name = name.replace(/\.[^\.]+$/, '');
} else if(suffix !== null) {
suffix = Opal.escape_regexp(suffix);
name = name.replace(new RegExp(#{"#{suffix}$"}), '');
}
return name;
}
end
def extname(path)
`path = $coerce_to_path(path)`
filename = basename(path)
return '' if filename.empty?
last_dot_idx = filename[1..-1].rindex('.')
# extension name must contains at least one character .(something)
last_dot_idx.nil? || last_dot_idx + 1 == filename.length - 1 ? '' : filename[(last_dot_idx + 1)..-1]
end
def exist?(path)
`Opal.modules[#{path}] != null`
end
def directory?(path)
files = []
%x{
for (var key in Opal.modules) {
#{files}.push(key)
}
}
path = path.gsub(/(^.#{SEPARATOR}+|#{SEPARATOR}+$)/)
file = files.find { |f| f =~ /^#{path}/ }
file
end
def join(*paths)
if paths.empty?
return ''
end
result = ''
paths = paths.flatten.each_with_index.map do |item, index|
if index == 0 && item.empty?
SEPARATOR
elsif paths.length == index + 1 && item.empty?
SEPARATOR
else
item
end
end
paths = paths.reject(&:empty?)
paths.each_with_index do |item, index|
next_item = paths[index + 1]
if next_item.nil?
result = "#{result}#{item}"
else
if item.end_with?(SEPARATOR) && next_item.start_with?(SEPARATOR)
item = item.sub(/#{SEPARATOR}+$/, '')
end
result = if item.end_with?(SEPARATOR) || next_item.start_with?(SEPARATOR)
"#{result}#{item}"
else
"#{result}#{item}#{SEPARATOR}"
end
end
end
result
end
def split(path)
path.split(SEPARATOR)
end
alias realpath expand_path
alias exists? exist?
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/boolean.rb | opal/corelib/boolean.rb | # use_strict: true
# backtick_javascript: true
class ::Boolean < `Boolean`
`Opal.prop(self.$$prototype, '$$is_boolean', true)`
%x{
var properties = ['$$class', '$$meta'];
for (var i = 0; i < properties.length; i++) {
Object.defineProperty(self.$$prototype, properties[i], {
configurable: true,
enumerable: false,
get: function() {
return this == true ? Opal.TrueClass :
this == false ? Opal.FalseClass :
Opal.Boolean;
}
});
}
Object.defineProperty(self.$$prototype, "$$id", {
configurable: true,
enumerable: false,
get: function() {
return this == true ? 2 :
this == false ? 0 :
nil;
}
});
}
class << self
def allocate
::Kernel.raise ::TypeError, "allocator undefined for #{name}"
end
undef :new
end
def __id__
`self.valueOf() ? 2 : 0`
end
def !
`self != true`
end
def &(other)
`(self == true) ? (other !== false && other !== nil) : false`
end
def |(other)
`(self == true) ? true : (other !== false && other !== nil)`
end
def ^(other)
`(self == true) ? (other === false || other === nil) : (other !== false && other !== nil)`
end
def ==(other)
`(self == true) === other.valueOf()`
end
def singleton_class
`self.$$meta`
end
def to_s
`(self == true) ? 'true' : 'false'`
end
def dup
self
end
def clone(freeze: true)
self
end
# See: https://github.com/opal/opal/issues/2230
#
# This is a hack that allows you to add methods to TrueClass and FalseClass.
# Do note, that while true and false have a correct $$class (it's either
# TrueClass or FalseClass), their prototype is `Boolean.$$prototype`, which
# basically means that when calling `true.something` we actually call
# `Boolean#something` instead of `TrueClass#something`. So using
# method_missing we dispatch it to `TrueClass/FalseClass#something` correctly.
#
# The downside is that a correct implementation would also allow us to override
# the methods defined on Boolean, but our implementation doesn't allow that,
# unless you define them on Boolean and not on TrueClass/FalseClass.
def method_missing(method, *args, &block)
`var body = self.$$class.$$prototype[Opal.jsid(#{method})]`
super unless `typeof body !== 'undefined' && !body.$$stub`
`Opal.send(self, body, #{args}, #{block})`
end
def respond_to_missing?(method, _include_all = false)
`var body = self.$$class.$$prototype[Opal.jsid(#{method})]`
`typeof body !== 'undefined' && !body.$$stub`
end
alias eql? ==
alias equal? ==
alias inspect to_s
alias object_id __id__
end
class ::TrueClass < ::Boolean; end
class ::FalseClass < ::Boolean; end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/constants.rb | opal/corelib/constants.rb | ::RUBY_PLATFORM = 'opal'
::RUBY_ENGINE = 'opal'
::RUBY_VERSION = '3.2.0'
::RUBY_ENGINE_VERSION = '2.0.0dev'
::RUBY_RELEASE_DATE = '2023-11-16'
::RUBY_PATCHLEVEL = 0
::RUBY_REVISION = '0'
::RUBY_COPYRIGHT = 'opal - Copyright (C) 2011-2023 Adam Beynon and the Opal contributors'
::RUBY_DESCRIPTION = "opal #{::RUBY_ENGINE_VERSION} (#{::RUBY_RELEASE_DATE} revision #{::RUBY_REVISION})"
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
opal/opal | https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/opal/corelib/irb.rb | opal/corelib/irb.rb | # backtick_javascript: true
# Debug is a helper module that allows us to conduct some debugging on
# a live codebase. It goes with an assumption, that opal-parser or
# opal-replutils will not be loaded, in which case we will do what we can
# to provision it.
require 'runtime/irb'
module Opal
module IRB
def self.ensure_loaded(library)
return if `Opal.loaded_features`.include? library
version = if RUBY_ENGINE_VERSION.include? 'dev'
'master'
else
RUBY_ENGINE_VERSION
end
url = "https://cdn.opalrb.com/opal/#{version}/#{library}.js"
%x{
var libcode;
if (typeof XMLHttpRequest !== 'undefined') { // Browser
var r = new XMLHttpRequest();
r.open("GET", url, false);
r.send('');
libcode = r.responseText;
}
else {
#{::Kernel.raise "You need to provision #{library} yourself in this environment"}
}
(new Function('Opal', libcode))(Opal);
Opal.require(library);
}
::Kernel.raise "Could not load #{library} for some reason" unless `Opal.loaded_features`.include? library
end
singleton_class.attr_accessor :output
def self.prepare_console(&block)
self.output = ''
original = {
$stdout => ->(i) { $stdout = i },
$stderr => ->(i) { $stderr = i },
}
# Prepare a better prompt experience for a browser
if browser?
original.each do |pipe, pipe_setter|
new_pipe = pipe.dup
new_pipe.write_proc = proc do |str|
self.output += str
self.output = output.split("\n").last(30).join("\n")
self.output += "\n" if str.end_with? "\n"
pipe.write_proc.call(str)
end
new_pipe.tty = false
pipe_setter.call(new_pipe)
end
original_read_proc = $stdin.read_proc
$stdin.read_proc = `function(s) { var p = prompt(#{output}); if (p !== null) return p + "\n"; return nil; }`
end
yield
ensure
original.each do |pipe, pipe_setter|
pipe_setter.call(pipe)
end
$stdin.read_proc = original_read_proc
self.output = ''
end
def self.browser?
`typeof(document) !== 'undefined' && typeof(prompt) !== 'undefined'`
end
LINEBREAKS = [
'unexpected token $end',
'unterminated string meets end of file'
].freeze
class Silencer
def initialize
@stderr = $stderr
end
def silence
@collector = ::StringIO.new
$stderr = @collector
yield
ensure
$stderr = @stderr
end
def warnings
@collector.string
end
end
end
end
class ::Binding
def irb
::Opal::IRB.ensure_loaded('opal-replutils')
silencer = ::Opal::IRB::Silencer.new
::Opal::IRB.prepare_console do
loop do
print '>> '
line = gets
break unless line
code = ''
puts line if ::Opal::IRB.browser?
if line.start_with? 'ls '
code = line[3..-1]
mode = :ls
elsif line == "ls\n"
code = 'self'
mode = :ls
elsif line.start_with? 'show '
code = line[5..-1]
mode = :show
else
code = line
mode = :inspect
end
js_code = nil
begin
silencer.silence do
js_code = `Opal.compile(code, {irb: true})`
end
rescue SyntaxError => e
if ::Opal::IRB::LINEBREAKS.include?(e.message)
print '.. '
line = gets
return unless line
puts line if ::Opal::IRB.browser?
code += line
retry
elsif silencer.warnings.empty?
warn e.full_message
else
# Most likely a parser error
warn silencer.warnings
end
end
if mode == :show
puts js_code
return
end
puts ::REPLUtils.eval_and_print(js_code, mode, false, self)
end
end
end
end
| ruby | MIT | b4e228990534515b83cd509a9297beca59bf8733 | 2026-01-04T15:44:44.154940Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.