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 |
|---|---|---|---|---|---|---|---|---|
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/definer.rb | lib/graphql/models/definer.rb | # frozen_string_literal: true
# This is a helper class. It lets you build simple DSL's. Methods called against the class are
# converted into attributes in a hash.
module GraphQL
module Models
class Definer
def initialize(*methods)
@values = {}
methods.each do |m|
define_singleton_method(m) do |*args|
@values[m] = if args.blank?
nil
elsif args.length == 1
args[0]
else
args
end
end
end
end
def defined_values
@values
end
end
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/definition_helpers.rb | lib/graphql/models/definition_helpers.rb | # frozen_string_literal: true
require 'ostruct'
module GraphQL
module Models
module DefinitionHelpers
def self.types
GraphQL::Define::TypeDefiner.instance
end
# Returns a promise that will eventually resolve to the model that is at the end of the path
def self.load_and_traverse(current_model, path, context)
cache_model(context, current_model)
return Promise.resolve(current_model) if path.empty? || current_model.nil?
association = current_model.association(path[0])
while !path.empty? && (association.loaded? || attempt_cache_load(current_model, association, context))
current_model = association.target
path = path[1..-1]
cache_model(context, current_model)
return Promise.resolve(current_model) if path.empty? || current_model.nil?
association = current_model.association(path[0])
end
# If this is a has_many :through, then we need to load the two associations in sequence
# (eg: Company has_many :health_lines, through: :open_enrollments => load open enrollments, then health lines)
promise = if association.reflection.options[:through]
# First step, load the :through association (ie, the :open_enrollments)
through = association.reflection.options[:through]
load_and_traverse(current_model, [through], context).then do |intermediate_models|
# Now, for each of the intermediate models (OpenEnrollment), load the source association (:health_line)
sources = intermediate_models.map do |im|
load_and_traverse(im, [association.reflection.source_reflection_name], context)
end
# Once all of the eventual models are loaded, flatten the results
Promise.all(sources).then do |result|
result = result.flatten
Helpers.load_association_with(association, result)
end
end
else
AssociationLoadRequest.new(current_model, path[0], context).load
end
promise.then do |next_model|
next next_model if next_model.blank?
cache_model(context, next_model)
if path.length == 1
sanity = next_model.is_a?(Array) ? next_model[0] : next_model
next next_model
else
DefinitionHelpers.load_and_traverse(next_model, path[1..-1], context)
end
end
end
# Attempts to retrieve the model from the query's cache. If it's found, the association is marked as
# loaded and the model is added. This only works for belongs_to and has_one associations.
def self.attempt_cache_load(model, association, context)
return false unless context
reflection = association.reflection
return false unless %i[has_one belongs_to].include?(reflection.macro)
if reflection.macro == :belongs_to
target_id = model.send(reflection.foreign_key)
# If there isn't an associated model, mark the association loaded and return
if target_id.nil?
mark_association_loaded(association, nil)
return true
end
# If the associated model isn't cached, return false
target = context.cached_models.detect { |m| m.is_a?(association.klass) && m.id == target_id }
return false unless target
# Found it!
mark_association_loaded(association, target)
return true
else
target = context.cached_models.detect do |m|
m.is_a?(association.klass) && m.send(reflection.foreign_key) == model.id && (!reflection.options.include?(:as) || m.send(reflection.type) == model.class.name)
end
return false unless target
mark_association_loaded(association, target)
return true
end
end
def self.cache_model(context, model)
return unless context
context.cached_models.merge(Array.wrap(model))
end
def self.mark_association_loaded(association, target)
association.loaded!
association.target = target
association.set_inverse_instance(target) unless target.nil?
end
def self.traverse_path(base_model, path, _context)
model = base_model
path.each do |segment|
return nil unless model
model = model.public_send(segment)
end
model
end
# Stores metadata about GraphQL fields that are available on this model's GraphQL type.
# @param metadata Should be a hash that contains information about the field's definition, including :macro and :type
def self.register_field_metadata(graph_type, field_name, metadata)
field_name = field_name.to_s
field_meta = graph_type.instance_variable_get(:@field_metadata)
field_meta ||= graph_type.instance_variable_set(:@field_metadata, {})
field_meta[field_name] = OpenStruct.new(metadata).freeze
end
end
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/active_record_extension.rb | lib/graphql/models/active_record_extension.rb | # frozen_string_literal: true
module GraphQL
module Models
module ActiveRecordExtension
class EnumTypeHash
extend Forwardable
attr_accessor :hash
def initialize
@hash = {}.with_indifferent_access
end
def [](attribute)
type = hash[attribute]
type = type.call if type.is_a?(Proc)
type = type.constantize if type.is_a?(String)
type
end
def_delegators :@hash, :[]=, :include?, :keys
end
extend ::ActiveSupport::Concern
class_methods do
def graphql_enum_types
@graphql_enum_types ||= EnumTypeHash.new
end
# Defines a GraphQL enum type on the model
def graphql_enum(attribute, type: nil, upcase: true)
# Case 1: Providing a type. Only thing to do is register the enum type.
if type
graphql_enum_types[attribute] = type
return type
end
# Case 2: Automatically generating the type
name = "#{self.name}#{attribute.to_s.classify}"
description = "#{attribute.to_s.titleize} field on #{self.name.titleize}"
values = if defined_enums.include?(attribute.to_s)
defined_enums[attribute.to_s].keys
else
Reflection.possible_values(self, attribute)
end
if values.nil?
raise ArgumentError, "Could not auto-detect the values for enum #{attribute} on #{self.name}"
end
type = GraphQL::EnumType.define do
name(name)
description(description)
values.each do |val|
value(upcase ? val.upcase : val, val.to_s.titleize, value: val)
end
end
graphql_enum_types[attribute] = type
end
end
end
end
end
::ActiveRecord::Base.send(:include, GraphQL::Models::ActiveRecordExtension)
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/promise_relation_connection.rb | lib/graphql/models/promise_relation_connection.rb | # frozen_string_literal: true
module GraphQL
module Models
class PromiseRelationConnection < GraphQL::Relay::RelationConnection
def edges
# Can't do any optimization if the request is asking for the last X items, since there's
# no easy way to turn it into a generalized query.
return super if last
relation = sliced_nodes
limit = [first, last, max_page_size].compact.min
relation = relation.limit(limit) if first
request = RelationLoadRequest.new(relation)
request.load.then do |models|
models.map { |m| GraphQL::Relay::Edge.new(m, self) }
end
end
end
# GraphQL::Relay::BaseConnection.register_connection_implementation(ActiveRecord::Relation, PromiseRelationConnection)
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/relation_loader.rb | lib/graphql/models/relation_loader.rb | # frozen_string_literal: true
module GraphQL
module Models
class RelationLoader < GraphQL::Batch::Loader
attr_reader :model_class
def initialize(model_class)
@model_class = model_class
end
def perform(load_requests)
# Group the requests to load by id into a single relation, and we'll fan it back out after
# we have the results
relations = []
id_requests = load_requests.select { |r| r.load_type == :id }
id_relation = model_class.where(id: id_requests.map(&:load_target))
relations.push(id_relation) if id_requests.any?
relations_to_requests = {}
# Gather up all of the requests to load a relation, and map the relations back to their requests
load_requests.select { |r| r.load_type == :relation }.each do |request|
relation = request.load_target
relations.push(relation) unless relations.detect { |r| r.object_id == relation.object_id }
relations_to_requests[relation.object_id] ||= []
relations_to_requests[relation.object_id].push(request)
end
# We need to build a query that will return all of the rows that match any of the relations.
# But in addition, we also need to know how that relation sorted them. So we pull any ordering
# information by adding RANK() columns to the query, and we determine whether that row belonged
# to the query by adding CASE columns.
# Map each relation to a SQL query that selects only the ID column for the rows that match it
selection_clauses = relations.map do |relation|
relation.unscope(:select).select(model_class.primary_key).to_sql
end
# Generate a CASE column that will tell us whether the row matches this particular relation
slicing_columns = relations.each_with_index.map do |_relation, index|
%{ CASE WHEN "#{model_class.table_name}"."#{model_class.primary_key}" IN (#{selection_clauses[index]}) THEN 1 ELSE 0 END AS "in_relation_#{index}" }
end
# For relations that have sorting applied, generate a RANK() column that tells us how the rows are
# sorted within that relation
sorting_columns = relations.each_with_index.map do |relation, index|
arel = relation.arel
next nil unless arel.orders.any?
order_by = arel.orders.map do |expr|
if expr.is_a?(Arel::Nodes::SqlLiteral)
expr.to_s
else
expr.to_sql
end
end
%{ RANK() OVER (ORDER BY #{order_by.join(', ')}) AS "sort_relation_#{index}" }
end
sorting_columns.compact!
# Build the query that will select any of the rows that match the selection clauses
main_relation = model_class
.where("id in ((#{selection_clauses.join(") UNION (")}))")
.select(%( "#{model_class.table_name}".* ))
main_relation = slicing_columns.reduce(main_relation) { |relation, memo| relation.select(memo) }
main_relation = sorting_columns.reduce(main_relation) { |relation, memo| relation.select(memo) }
# Run the query
result = main_relation.to_a
# Now multiplex the results out to all of the relations that had asked for values
relations.each_with_index do |relation, index|
slice_col = "in_relation_#{index}"
sort_col = "sort_relation_#{index}"
matching_rows = result.select { |r| r[slice_col] == 1 }.sort_by { |r| r[sort_col] }
if relation.object_id == id_relation.object_id
pk = relation.klass.primary_key
id_requests.each do |request|
row = matching_rows.detect { |r| r[pk] == request.load_target }
fulfill(request, row)
end
else
relations_to_requests[relation.object_id].each do |request|
fulfill_request(request, matching_rows)
end
end
end
end
def fulfill_request(request, result)
result = request.ensure_cardinality(result)
request.fulfilled(result)
fulfill(request, result)
end
end
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/helpers.rb | lib/graphql/models/helpers.rb | # frozen_string_literal: true
module GraphQL::Models
module Helpers
def self.orders_to_sql(orders)
expressions = orders.map do |expr|
case expr
when Arel::Nodes::SqlLiteral
expr.to_s
else
expr.to_sql
end
end
expressions.join(', ')
end
def self.load_association_with(association, result)
reflection = association.reflection
association.loaded!
if reflection.macro == :has_many
association.target.slice!(0..-1)
association.target.concat(result)
result.each do |m|
association.set_inverse_instance(m)
end
else
association.target = result
association.set_inverse_instance(result) if result
end
end
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/reflection.rb | lib/graphql/models/reflection.rb | # frozen_string_literal: true
# Exposes utility methods for getting metadata out of active record models
module GraphQL::Models
module Reflection
class << self
# Returns the possible values for an attribute on a model by examining inclusion validators
def possible_values(model_class, attribute)
# Get all of the inclusion validators
validators = model_class.validators_on(attribute).select { |v| v.is_a?(ActiveModel::Validations::InclusionValidator) }
# Ignore any inclusion validators that are using the 'if' or 'unless' options
validators = validators.reject { |v| v.options.include?(:if) || v.options.include?(:unless) || v.options[:in].blank? }
return nil unless validators.any?
validators.map { |v| v.options[:in] }.reduce(:&)
end
# Determines if the attribute (or association) is required by examining presence validators
# and the nullability of the column in the database
def is_required(model_class, attr_or_assoc)
# Check for non-nullability on the column itself
return true if model_class.columns_hash[attr_or_assoc.to_s]&.null == false
# Check for a presence validator on the association
return true if model_class.validators_on(attr_or_assoc)
.select { |v| v.is_a?(ActiveModel::Validations::PresenceValidator) }
.reject { |v| v.options.include?(:if) || v.options.include?(:unless) }
.any?
# If it's a belongs_to association, check for nullability on the foreign key
reflection = model_class.reflect_on_association(attr_or_assoc)
return true if reflection && reflection.macro == :belongs_to && is_required(model_class, reflection.foreign_key)
false
end
# Returns a struct that tells you the input and output GraphQL types for an attribute
def attribute_graphql_type(model_class, attribute)
# See if it's an enum
if model_class.graphql_enum_types.include?(attribute)
type = model_class.graphql_enum_types[attribute]
DatabaseTypes::TypeStruct.new(type, type)
else
# See if it's a registered scalar type
active_record_type = model_class.type_for_attribute(attribute.to_s)
if active_record_type.type.nil?
raise ArgumentError, "The type for attribute #{attribute} wasn't found on #{model_class.name}"
end
result = DatabaseTypes.registered_type(active_record_type.type)
if result.nil? && GraphQL::Models.unknown_scalar
type = GraphQL::Models.unknown_scalar.call(active_record_type.type, model_class, attribute)
if type.is_a?(GraphQL::BaseType) && (type.unwrap.is_a?(GraphQL::ScalarType) || type.unwrap.is_a?(GraphQL::EnumType))
result = DatabaseTypes::TypeStruct.new(type, type)
elsif type.is_a?(DatabaseTypes::TypeStruct)
result = type
else
raise "Got unexpected value #{type.inspect} from `unknown_scalar` proc. Expected a GraphQL::ScalarType, GraphQL::EnumType, or GraphQL::Models::DatabaseTypes::TypeStruct."
end
end
if result.nil?
# rubocop:disable Metrics/LineLength
raise "Don't know how to map database type #{active_record_type.type.inspect} to a GraphQL type. Forget to register it with GraphQL::Models::DatabaseTypes? (attribute #{attribute} on #{model_class.name})"
# rubocop:enable Metrics/LineLength
end
# Arrays: Rails doesn't have a generalized way to detect arrays, so we use this method to do it:
if active_record_type.class.name.ends_with?('Array')
DatabaseTypes::TypeStruct.new(result.input.to_list_type, result.output.to_list_type)
else
result
end
end
end
end
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/backed_by_model.rb | lib/graphql/models/backed_by_model.rb | # frozen_string_literal: true
module GraphQL
module Models
class BackedByModel
DEFAULT_OBJECT_TO_MODEL = -> (obj) { obj }
def initialize(graph_type, model_type, base_model_type: model_type, path: [], object_to_model: DEFAULT_OBJECT_TO_MODEL, detect_nulls: true)
model_type = model_type.to_s.classify.constantize unless model_type.is_a?(Class)
base_model_type = base_model_type.to_s.classify.constantize unless model_type.is_a?(Class)
@graph_type = graph_type
@model_type = model_type
@object_to_model = object_to_model
@base_model_type = base_model_type
@path = path
@detect_nulls = detect_nulls
end
def types
GraphQL::Define::TypeDefiner.instance
end
def object_to_model(value = nil)
@object_to_model = value if value
@object_to_model
end
# Allows you to overide the automatic nullability detection. By default, nulls are detected. However, attributes inside
# of a proxy_to block are assumed to be nullable, unless the association itself has a presence validator.
def detect_nulls(value = nil)
@detect_nulls = value if !value.nil?
@detect_nulls
end
# Adds a field to the graph type that is resolved to an attribute on the model.
# @param attribute Symbol with the name of the attribute on the model
# @param description Description for the field
# @param name Name of the field to use. By default, the attribute name is camelized.
# @param nullable Set to false to force the field to be non-null. By default, nullability is automatically detected.
# @param deprecation_reason Sets the deprecation reason on the field.
def attr(attribute, name: attribute.to_s.camelize(:lower), nullable: nil, description: nil, deprecation_reason: nil, &block)
name = name.to_sym unless name.is_a?(Symbol)
# Get the description from the column, if it's not provided. Doesn't work in Rails 4 :(
unless description
column = @model_type.columns_hash[attribute.to_s]
description = column.comment if column&.respond_to?(:comment)
end
options = {
name: name,
nullable: nullable,
description: description,
deprecation_reason: deprecation_reason,
}
DefinitionHelpers.define_attribute(@graph_type, @base_model_type, @model_type, @path, attribute, @object_to_model, options, @detect_nulls, &block)
end
# Flattens an associated model into the graph type, allowing to you adds its attributes as if they existed on the parent model.
# @param association Name of the association to use. Polymorphic belongs_to associations are not supported.
def proxy_to(association, &block)
DefinitionHelpers.define_proxy(@graph_type, @base_model_type, @model_type, @path, association, @object_to_model, @detect_nulls, &block)
end
def has_one(association, name: association.to_s.camelize(:lower), nullable: nil, description: nil, deprecation_reason: nil)
name = name.to_sym unless name.is_a?(Symbol)
options = {
name: name,
nullable: nullable,
description: description,
deprecation_reason: deprecation_reason,
}
DefinitionHelpers.define_has_one(@graph_type, @base_model_type, @model_type, @path, association, @object_to_model, options, @detect_nulls)
end
def has_many_connection(association, name: association.to_s.camelize(:lower), nullable: nil, description: nil, deprecation_reason: nil, **goco_options)
name = name.to_sym unless name.is_a?(Symbol)
options = goco_options.merge({
name: name,
nullable: nullable,
description: description,
deprecation_reason: deprecation_reason,
})
DefinitionHelpers.define_has_many_connection(@graph_type, @base_model_type, @model_type, @path, association, @object_to_model, options, @detect_nulls)
end
def has_many_array(association, name: association.to_s.camelize(:lower), nullable: nil, description: nil, deprecation_reason: nil, type: nil)
name = name.to_sym unless name.is_a?(Symbol)
options = {
name: name,
type: type,
nullable: nullable,
description: description,
deprecation_reason: deprecation_reason,
}
DefinitionHelpers.define_has_many_array(@graph_type, @base_model_type, @model_type, @path, association, @object_to_model, options, @detect_nulls)
end
def field(*args, &block)
defined_field = GraphQL::Define::AssignObjectField.call(@graph_type, *args, &block)
name = defined_field.name
name = name.to_sym unless name.is_a?(Symbol)
DefinitionHelpers.register_field_metadata(@graph_type, name, {
macro: :field,
macro_type: :custom,
path: @path,
base_model_type: @base_model_type,
model_type: @model_type,
object_to_base_model: @object_to_model,
})
defined_field
end
end
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/mutation_field_map.rb | lib/graphql/models/mutation_field_map.rb | # frozen_string_literal: true
module GraphQL::Models
class MutationFieldMap
attr_accessor :model_type, :find_by, :null_behavior, :fields, :nested_maps, :legacy_nulls
# These are used when this is a proxy_to or a nested field map
attr_accessor :name, :association, :has_many, :required, :path
def initialize(model_type, find_by:, null_behavior:, legacy_nulls:)
raise ArgumentError, "model_type must be a model" if model_type && !(model_type <= ActiveRecord::Base)
raise ArgumentError, "null_behavior must be :set_null or :leave_unchanged" unless %i[set_null leave_unchanged].include?(null_behavior)
@fields = []
@nested_maps = []
@path = []
@model_type = model_type
@find_by = Array.wrap(find_by)
@null_behavior = null_behavior
@legacy_nulls = legacy_nulls
@find_by.each { |f| attr(f) }
end
def types
GraphQL::Define::TypeDefiner.instance
end
def attr(attribute, type: nil, name: nil, required: nil)
attribute = attribute.to_sym if attribute.is_a?(String)
if type.nil? && !model_type
raise ArgumentError, "You must specify a type for attribute #{name}, because its model type is not known until runtime."
end
if type.nil? && (attribute == :id || foreign_keys.include?(attribute))
type = types.ID
end
if type.nil? && model_type
type = Reflection.attribute_graphql_type(model_type, attribute).input
end
if required.nil?
required = model_type ? Reflection.is_required(model_type, attribute) : false
end
name ||= attribute.to_s.camelize(:lower)
name = name.to_s
detect_field_conflict(name)
# Delete the field, if it's already in the map
fields.reject! { |fd| fd[:attribute] == attribute }
fields << {
name: name,
attribute: attribute,
type: type,
required: required,
}
end
def proxy_to(association, &block)
association = association.to_sym if association.is_a?(String)
reflection = model_type&.reflect_on_association(association)
if reflection
unless %i[belongs_to has_one].include?(reflection.macro)
raise ArgumentError, "Cannot proxy to #{reflection.macro} association #{association} from #{model_type.name}"
end
klass = reflection.polymorphic? ? nil : reflection.klass
else
klass = nil
end
proxy = MutationFieldMap.new(klass, find_by: nil, null_behavior: null_behavior, legacy_nulls: legacy_nulls)
proxy.association = association
proxy.instance_exec(&block)
proxy.fields.each { |f| detect_field_conflict(f[:name]) }
proxy.nested_maps.each { |m| detect_field_conflict(m.name) }
proxy.fields.each do |field|
fields.push({
name: field[:name],
attribute: field[:attribute],
type: field[:type],
required: field[:required],
path: [association] + Array.wrap(field[:path]),
})
end
proxy.nested_maps.each do |m|
m.path.unshift(association)
nested_maps.push(m)
end
end
def nested(association, find_by: nil, null_behavior:, name: nil, &block)
unless model_type
raise ArgumentError, "Cannot use `nested` unless the model type is known at build time."
end
association = association.to_sym if association.is_a?(String)
reflection = model_type.reflect_on_association(association)
unless reflection
raise ArgumentError, "Could not find association #{association} on #{model_type.name}"
end
if reflection.polymorphic?
raise ArgumentError, "Cannot used `nested` with polymorphic association #{association} on #{model_type.name}"
end
has_many = reflection.macro == :has_many
required = Reflection.is_required(model_type, association)
map = MutationFieldMap.new(reflection.klass, find_by: find_by, null_behavior: null_behavior, legacy_nulls: legacy_nulls)
map.name = name || association.to_s.camelize(:lower)
map.association = association.to_s
map.has_many = has_many
map.required = required
detect_field_conflict(map.name)
map.instance_exec(&block)
nested_maps.push(map)
end
def leave_null_unchanged?
null_behavior == :leave_unchanged
end
private
def detect_field_conflict(name)
if fields.any? { |f| f[name] == name } || nested_maps.any? { |n| n.name == name }
raise ArgumentError, "The field #{name} is defined more than once."
end
end
def foreign_keys
@foreign_keys ||= model_type.reflections.values
.select { |r| r.macro == :belongs_to }
.map(&:foreign_key)
.map(&:to_sym)
end
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/relation_load_request.rb | lib/graphql/models/relation_load_request.rb | # frozen_string_literal: true
module GraphQL
module Models
class RelationLoadRequest
attr_reader :relation
def initialize(relation)
@relation = relation
end
####################################################################
# Public members that all load requests should implement
####################################################################
def load_type
:relation
end
def load_target
relation
end
# If the value should be an array, make sure it's an array. If it should be a single value, make sure it's single.
# Passed in result could be a single model or an array of models.
def ensure_cardinality(result)
Array.wrap(result)
end
# When the request is fulfilled, this method is called so that it can do whatever caching, etc. is needed
def fulfilled(result); end
def load
loader.load(self)
end
#################################################################
# Public members specific to a relation load request
#################################################################
def target_class
relation.klass
end
private
def loader
@loader ||= RelationLoader.for(target_class)
end
end
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/association_load_request.rb | lib/graphql/models/association_load_request.rb | # frozen_string_literal: true
module GraphQL
module Models
class AssociationLoadRequest
attr_reader :base_model, :association, :context
def initialize(base_model, association_name, context)
@base_model = base_model
@association = base_model.association(association_name)
@context = context
if reflection.is_a?(ActiveRecord::Reflection::ThroughReflection)
raise ArgumentError, "You cannot batch-load a has_many :through association. Instead, load each association individually."
end
end
def request
AttributeLoader::Request.new(
association.scope.where_values_hash,
Helpers.orders_to_sql(association.scope.arel.orders)
)
end
def load
loader.load(request).then do |result|
result = result.first unless reflection.macro == :has_many
Helpers.load_association_with(association, result)
result
end
end
#################################################################
# Public members specific to an association load request
#################################################################
def target_class
if reflection.polymorphic?
base_model.send(reflection.foreign_type).constantize
else
reflection.klass
end
end
private
def loader
@loader ||= AttributeLoader.for(target_class)
end
def reflection
association.reflection
end
end
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/database_types.rb | lib/graphql/models/database_types.rb | # frozen_string_literal: true
module GraphQL
module Models
module DatabaseTypes
TypeStruct = Struct.new(:input, :output)
def self.registered_type(database_type)
@registered_types ||= {}.with_indifferent_access
result = @registered_types[database_type]
return nil if result.nil?
if !result.input.is_a?(GraphQL::BaseType) || !result.output.is_a?(GraphQL::BaseType)
input = result.input
output = result.output
input = input.call if input.is_a?(Proc)
output = output.call if output.is_a?(Proc)
input = input.constantize if input.is_a?(String)
output = output.constantize if output.is_a?(String)
TypeStruct.new(input, output)
else
result
end
end
def self.register(database_type, output_type, input_type = output_type)
@registered_types ||= {}.with_indifferent_access
@registered_types[database_type] = TypeStruct.new(input_type, output_type)
end
end
DatabaseTypes.register(:boolean, GraphQL::BOOLEAN_TYPE)
DatabaseTypes.register(:integer, GraphQL::INT_TYPE)
DatabaseTypes.register(:float, GraphQL::FLOAT_TYPE)
DatabaseTypes.register(:string, GraphQL::STRING_TYPE)
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/instrumentation.rb | lib/graphql/models/instrumentation.rb | # frozen_string_literal: true
class GraphQL::Models::Instrumentation
# @param skip_nil_models If true, field resolvers (in proxy_to or backed_by_model blocks) will not be invoked if the model is nil.
def initialize(skip_nil_models = true)
@skip_nil_models = skip_nil_models
end
def instrument(type, field)
field_info = GraphQL::Models.field_info(type, field.name)
return field unless field_info
old_resolver = field.resolve_proc
new_resolver = -> (object, args, ctx) {
Promise.resolve(field_info.object_to_base_model.call(object)).then do |base_model|
GraphQL::Models.load_association(base_model, field_info.path, ctx).then do |model|
next nil if model.nil? && @skip_nil_models
old_resolver.call(model, args, ctx)
end
end
}
field.redefine do
resolve(new_resolver)
end
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/monkey_patches/graphql_query_context.rb | lib/graphql/models/monkey_patches/graphql_query_context.rb | # frozen_string_literal: true
class GraphQL::Query::Context
def cached_models
@cached_models ||= Set.new
end
end
class GraphQL::Query::Context::FieldResolutionContext
def cached_models
@context.cached_models
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/mutation_helpers/apply_changes.rb | lib/graphql/models/mutation_helpers/apply_changes.rb | # frozen_string_literal: true
module GraphQL::Models
module MutationHelpers
def self.apply_changes(field_map, model, inputs, context)
# This will hold a flattened list of attributes/models that we actually changed
changes = []
# Values will now contain the list of inputs that we should actually act on. Any null values should actually
# be set to null, and missing fields should be skipped.
values = if field_map.leave_null_unchanged? && field_map.legacy_nulls
prep_legacy_leave_unchanged(inputs)
elsif field_map.leave_null_unchanged?
prep_leave_unchanged(inputs)
else
prep_set_null(field_map, inputs)
end
values.each do |name, value|
field_def = field_map.fields.detect { |f| f[:name] == name }
# Skip this value unless it's a field on the model. Nested fields are handled later.
next unless field_def
# Advance to the model that we actually need to change
change_model = model_to_change(model, field_def[:path], changes, create_if_missing: !value.nil?)
next if change_model.nil?
# Apply the change to this model
apply_field_value(change_model, field_def, value, context, changes)
end
# Handle the value nested fields now.
field_map.nested_maps.each do |child_map|
next if inputs[child_map.name].nil? && field_map.leave_null_unchanged?
# Advance to the model that contains the nested fields
change_model = model_to_change(model, child_map.path, changes, create_if_missing: !inputs[child_map.name].nil?)
next if change_model.nil?
# Apply the changes to the nested models
child_changes = handle_nested_map(field_map, change_model, inputs, context, child_map)
# Merge the changes with the parent, but prepend the input field path
child_changes.each do |cc|
cc[:input_path] = [child_map.name] + Array.wrap(cc[:input_path]) if cc[:input_path]
changes.push(cc)
end
end
changes
end
def self.handle_nested_map(parent_map, parent_model, inputs, context, child_map)
next_inputs = inputs[child_map.name]
# Don't do anything if the value is null, and we leave null fields unchanged
return [] if next_inputs.nil? && parent_map.leave_null_unchanged?
changes = []
matches = match_inputs_to_models(parent_model, child_map, next_inputs, changes, context)
matches.each do |match|
next if match[:child_model].nil? && match[:child_inputs].nil?
child_changes = apply_changes(child_map, match[:child_model], match[:child_inputs], context)
if match[:input_path]
child_changes.select { |cc| cc[:input_path] }.each do |cc|
cc[:input_path] = [match[:input_path]] + Array.wrap(cc[:input_path])
end
end
changes.concat(child_changes)
end
changes
end
def self.match_inputs_to_models(model, child_map, next_inputs, changes, context)
if !child_map.has_many
child_model = model.public_send(child_map.association)
if next_inputs.nil? && !child_model.nil?
child_model.mark_for_destruction
changes.push({ model_instance: child_model, action: :destroy })
elsif child_model.nil? && !next_inputs.nil?
child_model = model.public_send("build_#{child_map.association}")
assoc = model.association(child_map.association)
refl = assoc.reflection
if refl.options.include?(:as)
inverse_name = refl.options[:as]
inverse_assoc = child_model.association(inverse_name)
inverse_assoc.inversed_from(model)
end
changes.push({ model_instance: child_model, action: :create })
end
[{ child_model: child_model, child_inputs: next_inputs }]
else
next_inputs = [] if next_inputs.nil?
# Match up each of the elements in next_inputs with one of the models, based on the `find_by` value.
associated_models = model.public_send(child_map.association)
find_by = Array.wrap(child_map.find_by).map(&:to_s)
if find_by.empty?
return match_inputs_by_position(model, child_map, next_inputs, changes, associated_models)
else
return match_inputs_by_fields(model, child_map, next_inputs, changes, associated_models, find_by, context)
end
end
end
def self.match_inputs_by_position(_model, _child_map, next_inputs, changes, associated_models)
count = [associated_models.length, next_inputs.length].max
matches = []
# This will give us an array of [number, model, inputs].
# Either the model or the inputs could be nil, but not both.
count.times.zip(associated_models.to_a, next_inputs) do |(idx, child_model, inputs)|
if child_model.nil?
child_model = associated_models.build
changes.push({ model_instance: child_model, action: :create })
end
if inputs.nil?
child_model.mark_for_destruction
changes.push({ model_instance: child_model, action: :destroy })
next
end
matches.push({ child_model: child_model, child_inputs: inputs, input_path: idx })
end
matches
end
def self.match_inputs_by_fields(_model, child_map, next_inputs, changes, associated_models, find_by, context)
# Convert the find_by into the field definitions, so that we properly unmap aliased fields
find_by_defs = find_by.map { |name| child_map.fields.detect { |f| f[:attribute].to_s == name.to_s } }
name_to_attr = find_by_defs.map { |f| [f[:name], f[:attribute].to_s] }.to_h
indexed_models = associated_models.index_by { |m| m.attributes.slice(*find_by) }
# Inputs are a little nasty, the keys have to be converted from camelCase back to snake_case
indexed_inputs = next_inputs.index_by { |ni| ni.to_h.slice(*name_to_attr.keys) }
indexed_inputs = indexed_inputs.map do |key, inputs|
attr_key = {}
key.each do |name, val|
# If the input is a Relay ID, convert it to the model's ordinary ID first. Note, this is
# less than optimal, because it has to fetch the model and then just get its id :(
field_def = find_by_defs.detect { |d| d[:name] == name }
if val && field_def[:type].unwrap == GraphQL::ID_TYPE
val = relay_id_to_model_id(val, context)
raise GraphQL::ExecutionError, "The value provided for #{field_def[:name]} does not refer to a valid model." unless val
end
attr_key[name_to_attr[name]] = val
end
[attr_key, inputs]
end
indexed_inputs = indexed_inputs.to_h
# Match each model to its input. If there is no input for it, mark that the model should be destroyed.
matches = []
indexed_models.each do |key_attrs, child_model|
inputs = indexed_inputs[key_attrs]
if inputs.nil?
child_model.mark_for_destruction
changes.push({ model_instance: child_model, action: :destroy })
else
matches.push({ child_model: child_model, child_inputs: inputs, input_path: next_inputs.index(inputs) })
end
end
# Build a new model for each input that doesn't have a model
indexed_inputs.each do |key_attrs, inputs|
next if indexed_models.include?(key_attrs)
child_model = associated_models.build
changes.push({ model_instance: child_model, action: :create })
matches.push({ child_model: child_model, child_inputs: inputs, input_path: next_inputs.index(inputs) })
end
matches
end
# Returns the instance of the model that will be changed for this field. If new models are created along the way,
# they are added to the list of changes.
def self.model_to_change(starting_model, path, changes, create_if_missing: true)
model_to_change = starting_model
Array.wrap(path).each do |ps|
next_model = model_to_change.public_send(ps)
return nil if next_model.nil? && !create_if_missing
unless next_model
next_model = model_to_change.public_send("build_#{ps}")
# Even though we may not be changing anything on this model, record it as a change, since it's a new model.
changes.push({ model_instance: next_model, action: :create })
end
model_to_change = next_model
end
model_to_change
end
def self.apply_field_value(model, field_def, value, context, changes)
# Special case: If this is an ID field, get the ID from the target model
if value.present? && field_def[:type].unwrap == GraphQL::ID_TYPE
value = relay_id_to_model_id(value, context)
unless value
raise GraphQL::ExecutionError, "The value provided for #{field_def[:name]} does not refer to a valid model."
end
end
unless model.public_send(field_def[:attribute]) == value
model.public_send("#{field_def[:attribute]}=", value)
changes.push({
model_instance: model,
input_path: field_def[:name],
attribute: field_def[:attribute],
action: model.new_record? ? :create : :update,
})
end
end
# If the field map has the option leave_null_unchanged, and legacy_nulls is true, then there's an `unsetFields` string
# array that contains the name of inputs that should be treated as if they are null. We handle that by removing null
# inputs, and then adding back any unsetFields with null values.
def self.prep_legacy_leave_unchanged(inputs)
# String key hash
values = inputs.to_h.compact
unset = Array.wrap(values['unsetFields'])
values.delete('unsetFields')
unset.each do |name|
values[name] = nil
end
values
end
def self.prep_leave_unchanged(inputs)
inputs.to_h
end
# Field map has the option to set_null. Any field that has the value null, or is missing, will be set to null.
def self.prep_set_null(field_map, inputs)
values = inputs.to_h.compact
field_map.fields.reject { |f| values.include?(f[:name]) }.each { |f| values[f[:name]] = nil }
field_map.nested_maps.reject { |m| values.include?(m.name) }.each { |m| values[m.name] = nil }
values
end
def self.relay_id_to_model_id(relay_id, context)
target_model = GraphQL::Models.model_from_id.call(relay_id, context)
target_model&.id
end
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/mutation_helpers/print_input_fields.rb | lib/graphql/models/mutation_helpers/print_input_fields.rb | # frozen_string_literal: true
module GraphQL::Models
module MutationHelpers
def self.print_input_fields(field_map, definer, map_name_prefix)
definer.instance_exec do
field_map.fields.each do |f|
field_type = f[:type]
if f[:required] && !field_map.leave_null_unchanged?
field_type = field_type.to_non_null_type unless field_type.non_null?
end
input_field(f[:name], field_type)
end
if field_map.leave_null_unchanged? && field_map.legacy_nulls
field_names = field_map.fields.reject { |f| f[:required] }.map { |f| f[:name].to_s }
field_names += field_map.nested_maps.reject(&:required).map { |fld| fld.name.to_s }
field_names = field_names.sort
unless field_names.empty?
enum = GraphQL::EnumType.define do
name "#{map_name_prefix}UnsettableFields"
field_names.each { |n| value(n, n.to_s.titleize, value: n) }
end
input_field('unsetFields', types[!enum])
end
end
end
# Build the input types for the nested input maps
field_map.nested_maps.each do |child_map|
type = build_input_type(child_map, "#{map_name_prefix}#{child_map.name.to_s.classify}")
if child_map.has_many
type = type.to_non_null_type.to_list_type
end
if child_map.required && !field_map.leave_null_unchanged?
type = type.to_non_null_type
end
definer.instance_exec do
input_field(child_map.name, type)
end
end
end
def self.build_input_type(field_map, name)
type = GraphQL::InputObjectType.define do
name(name)
GraphQL::Models::MutationHelpers.print_input_fields(field_map, self, name)
end
end
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/mutation_helpers/authorization.rb | lib/graphql/models/mutation_helpers/authorization.rb | # frozen_string_literal: true
module GraphQL::Models
module MutationHelpers
def self.authorize_changes(context, all_changes)
changed_models = all_changes.group_by { |c| c[:model_instance] }
changed_models.each do |model, changes|
changes.map { |c| c[:action] }.uniq.each do |action|
GraphQL::Models.authorize!(context, action, model)
end
end
end
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/mutation_helpers/validation.rb | lib/graphql/models/mutation_helpers/validation.rb | # frozen_string_literal: true
module GraphQL::Models
module MutationHelpers
def self.validate_changes(inputs, field_map, root_model, context, all_changes)
invalid_fields = {}
unknown_errors = []
changed_models = all_changes.group_by { |c| c[:model_instance] }
changed_models.reject { |m, _v| m.valid? }.each do |model, changes|
attrs_to_field = changes
.select { |c| c[:attribute] && c[:input_path] }
.map { |c| [c[:attribute], c[:input_path]] }
.to_h
model.errors.each do |error|
attribute = error.attribute
message = error.message
# Cheap check, see if this is a field that the user provided a value for...
if attrs_to_field.include?(attribute)
add_error(attribute, message, attrs_to_field[attribute], invalid_fields)
else
# Didn't provide a value, expensive check... trace down the input field
path = detect_input_path_for_attribute(model, attribute, inputs, field_map, root_model, context)
if path
add_error(attribute, message, path, invalid_fields)
else
unknown_errors.push({
modelType: model.class.name,
modelRid: model.id,
attribute: attribute,
message: message,
})
end
end
end
end
unless invalid_fields.empty? && unknown_errors.empty?
raise ValidationError.new(invalid_fields, unknown_errors)
end
end
def self.add_error(_attribute, message, path, invalid_fields)
path = Array.wrap(path)
current = invalid_fields
path[0..-2].each do |ps|
current = current[ps] ||= {}
end
current[path[-1]] = message
end
# Given a model and an attribute, returns the path of the input field that would modify that attribute
def self.detect_input_path_for_attribute(target_model, attribute, inputs, field_map, starting_model, context)
# Case 1: The input field is inside of this field map.
candidate_fields = field_map.fields.select { |f| f[:attribute] == attribute }
candidate_fields.each do |field|
# Walk to this field. If the model we get is the same as the target model, we found a match.
candidate_model = model_to_change(starting_model, field[:path], [], create_if_missing: false)
return Array.wrap(field[:name]) if candidate_model == target_model
end
# Case 2: The input field *is* a nested map
candidate_maps = field_map.nested_maps.select { |m| m.association == attribute.to_s }
candidate_maps.each do |map|
# Walk to this field. If the model we get is the same as the target model, we found a match.
candidate_model = model_to_change(starting_model, map.path, [], create_if_missing: false)
return Array.wrap(map.name) if candidate_model == target_model
end
# Case 3: The input field is somewhere inside of a nested field map.
field_map.nested_maps.each do |child_map|
# If we don't have the values for this map, it can't be the right one.
next if inputs[child_map.name].blank?
# Walk to the model that contains the nested field
candidate_model = model_to_change(starting_model, child_map.path, [], create_if_missing: false)
# If the model for this map doesn't exist, it can't be the one we need, because the target_model does exist.
next if candidate_model.nil?
# Match up the inputs with the models, and then check each of them.
candidate_matches = match_inputs_to_models(candidate_model, child_map, inputs[child_map.name], [], context)
candidate_matches.each do |m|
result = detect_input_path_for_attribute(target_model, attribute, m[:child_inputs], child_map, m[:child_model], context)
next if result.nil?
path = Array.wrap(result)
path.unshift(m[:input_path]) if m[:input_path]
return path
end
end
nil
end
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/mutation_helpers/validation_error.rb | lib/graphql/models/mutation_helpers/validation_error.rb | # frozen_string_literal: true
module GraphQL::Models
module MutationHelpers
class ValidationError < GraphQL::ExecutionError
attr_accessor :invalid_arguments, :unknown_errors
def initialize(invalid_arguments, unknown_errors)
@invalid_arguments = invalid_arguments
@unknown_errors = unknown_errors
end
def to_h
values = {
'message' => "Some of your changes could not be saved.",
'kind' => "INVALID_ARGUMENTS",
'invalidArguments' => invalid_arguments,
'unknownErrors' => unknown_errors,
}
if ast_node
values['locations'] = [{
"line" => ast_node.line,
"column" => ast_node.col,
},]
end
values
end
def to_s
"Some of your changes could not be saved."
end
end
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/definition_helpers/attributes.rb | lib/graphql/models/definition_helpers/attributes.rb | # frozen_string_literal: true
module GraphQL
module Models
module DefinitionHelpers
def self.resolve_nullability(graphql_type, model_class, attribute_or_association, detect_nulls, options)
# If detect_nulls is true, it means that everything on the path (ie, between base_model_class and model_class) is non null.
# So for example, if we're five levels deep inside of proxy_to blocks, but every single association along the way has
# a presence validator, then `detect_nulls` is false. Thus, we can take it one step further and enforce nullability on the
# attribute itself.
nullable = options[:nullable]
if nullable.nil?
nullable = !(detect_nulls && Reflection.is_required(model_class, attribute_or_association))
end
if nullable == false
graphql_type = graphql_type.to_non_null_type
else
graphql_type
end
end
def self.define_attribute(graph_type, base_model_class, model_class, path, attribute, object_to_model, options, detect_nulls, &block)
attribute_graphql_type = Reflection.attribute_graphql_type(model_class, attribute).output
attribute_graphql_type = resolve_nullability(attribute_graphql_type, model_class, attribute, detect_nulls, options)
field_name = options[:name]
DefinitionHelpers.register_field_metadata(graph_type, field_name, {
macro: :attr,
macro_type: :attribute,
path: path,
attribute: attribute,
base_model_class: base_model_class,
model_class: model_class,
object_to_base_model: object_to_model,
})
graph_type.fields[field_name.to_s] = GraphQL::Field.define do
name field_name.to_s
type attribute_graphql_type
description options[:description] if options.include?(:description)
deprecation_reason options[:deprecation_reason] if options.include?(:deprecation_reason)
resolve -> (model, _args, _context) do
model&.public_send(attribute)
end
instance_exec(&block) if block
end
end
end
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
goco-inc/legacy-graphql-activerecord | https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/definition_helpers/associations.rb | lib/graphql/models/definition_helpers/associations.rb | # frozen_string_literal: true
module GraphQL
module Models
module DefinitionHelpers
def self.define_proxy(graph_type, base_model_type, model_type, path, association, object_to_model, detect_nulls, &block)
reflection = model_type.reflect_on_association(association)
raise ArgumentError, "Association #{association} wasn't found on model #{model_type.name}" unless reflection
raise ArgumentError, "Cannot proxy to polymorphic association #{association} on model #{model_type.name}" if reflection.polymorphic?
raise ArgumentError, "Cannot proxy to #{reflection.macro} association #{association} on model #{model_type.name}" unless %i[has_one belongs_to].include?(reflection.macro)
return unless block_given?
proxy = BackedByModel.new(
graph_type,
reflection.klass,
base_model_type: base_model_type,
path: [*path, association],
object_to_model: object_to_model,
detect_nulls: detect_nulls && Reflection.is_required(model_type, association)
)
proxy.instance_exec(&block)
end
def self.resolve_has_one_type(reflection)
############################################
## Ordinary has_one/belongs_to associations
############################################
if reflection.polymorphic?
# For polymorphic associations, we look for a validator that limits the types of entities that could be
# used, and use it to build a union. If we can't find one, raise an error.
model_type = reflection.active_record
valid_types = Reflection.possible_values(model_type, reflection.foreign_type)
if valid_types.blank?
raise ArgumentError, "Cannot include polymorphic #{reflection.name} association on model #{model_type.name}, because it does not define an inclusion validator on #{reflection.foreign_type}"
end
graph_types = valid_types.map { |t| GraphQL::Models.get_graphql_type(t) }.compact
GraphQL::UnionType.define do
name "#{model_type.name.demodulize}#{reflection.foreign_type.classify}"
description "Objects that can be used as #{reflection.foreign_type.titleize.downcase} on #{model_type.name.titleize.downcase}"
possible_types graph_types
end
else
GraphQL::Models.get_graphql_type!(reflection.klass)
end
end
# Adds a field to the graph type which is resolved by accessing a has_one association on the model. Traverses
# across has_one associations specified in the path. The resolver returns a promise.
def self.define_has_one(graph_type, base_model_type, model_type, path, association, object_to_model, options, detect_nulls)
reflection = model_type.reflect_on_association(association)
raise ArgumentError, "Association #{association} wasn't found on model #{model_type.name}" unless reflection
raise ArgumentError, "Cannot include #{reflection.macro} association #{association} on model #{model_type.name} with has_one" unless %i[has_one belongs_to].include?(reflection.macro)
# Define the field for the association itself
camel_name = options[:name]
association_graphql_type = -> {
result = resolve_has_one_type(reflection)
resolve_nullability(result, model_type, association, detect_nulls, options)
}
DefinitionHelpers.register_field_metadata(graph_type, camel_name, {
macro: :has_one,
macro_type: :association,
path: path,
association: association,
base_model_type: base_model_type,
model_type: model_type,
object_to_base_model: object_to_model,
})
graph_type.fields[camel_name.to_s] = GraphQL::Field.define do
name camel_name.to_s
type association_graphql_type
description options[:description] if options.include?(:description)
deprecation_reason options[:deprecation_reason] if options.include?(:deprecation_reason)
resolve -> (model, _args, context) do
return nil unless model
DefinitionHelpers.load_and_traverse(model, [association], context)
end
end
# Define the field for the associated model's ID
id_field_name = :"#{camel_name}Id"
id_field_type = resolve_nullability(GraphQL::ID_TYPE, model_type, association, detect_nulls, options)
DefinitionHelpers.register_field_metadata(graph_type, id_field_name, {
macro: :has_one,
macro_type: :association,
path: path,
association: association,
base_model_type: base_model_type,
model_type: model_type,
object_to_base_model: object_to_model,
})
can_use_optimized = reflection.macro == :belongs_to
if !reflection.polymorphic? && reflection.klass.column_names.include?('type')
can_use_optimized = false
end
graph_type.fields[id_field_name.to_s] = GraphQL::Field.define do
name id_field_name.to_s
type id_field_type
deprecation_reason options[:deprecation_reason] if options.include?(:deprecation_reason)
resolve -> (model, _args, context) do
return nil unless model
if can_use_optimized
id = model.public_send(reflection.foreign_key)
return nil if id.nil?
type = model.association(association).klass.name
GraphQL::Models.id_for_model.call(type, id)
else
# We have to actually load the model and then get it's ID
DefinitionHelpers.load_and_traverse(model, [association], context).then(&:gid)
end
end
end
end
def self.define_has_many_array(graph_type, base_model_type, model_type, path, association, object_to_model, options, detect_nulls)
reflection = model_type.reflect_on_association(association)
raise ArgumentError, "Association #{association} wasn't found on model #{model_type.name}" unless reflection
raise ArgumentError, "Cannot include #{reflection.macro} association #{association} on model #{model_type.name} with has_many_array" unless [:has_many].include?(reflection.macro)
association_type = -> {
result = options[:type] || GraphQL::Models.get_graphql_type!(reflection.klass)
if !result.is_a?(GraphQL::ListType)
result = result.to_non_null_type.to_list_type
end
# The has_many associations are a little special. Instead of checking for a presence validator, we instead assume
# that the outer type should be non-null, unless detect_nulls is false. In other words, we prefer an empty
# array for the association, rather than null.
if (options[:nullable].nil? && detect_nulls) || options[:nullable] == false
result = result.to_non_null_type
end
result
}
id_field_type = GraphQL::ID_TYPE.to_non_null_type.to_list_type
if (options[:nullable].nil? && detect_nulls) || options[:nullable] == false
id_field_type = id_field_type.to_non_null_type
end
camel_name = options[:name]
DefinitionHelpers.register_field_metadata(graph_type, camel_name, {
macro: :has_many_array,
macro_type: :association,
path: path,
association: association,
base_model_type: base_model_type,
model_type: model_type,
object_to_base_model: object_to_model,
})
graph_type.fields[camel_name.to_s] = GraphQL::Field.define do
name camel_name.to_s
type association_type
description options[:description] if options.include?(:description)
deprecation_reason options[:deprecation_reason] if options.include?(:deprecation_reason)
resolve -> (model, _args, context) do
return nil unless model
DefinitionHelpers.load_and_traverse(model, [association], context).then do |result|
Array.wrap(result)
end
end
end
# Define the field for the associated model's ID
id_field_name = :"#{camel_name.to_s.singularize}Ids"
DefinitionHelpers.register_field_metadata(graph_type, id_field_name, {
macro: :has_one,
macro_type: :association,
path: path,
association: association,
base_model_type: base_model_type,
model_type: model_type,
object_to_base_model: object_to_model,
})
graph_type.fields[id_field_name.to_s] = GraphQL::Field.define do
name id_field_name.to_s
type id_field_type
deprecation_reason options[:deprecation_reason] if options.include?(:deprecation_reason)
resolve -> (model, _args, context) do
return nil unless model
DefinitionHelpers.load_and_traverse(model, [association], context).then do |result|
Array.wrap(result).map(&:gid)
end
end
end
end
def self.define_has_many_connection(graph_type, base_model_type, model_type, path, association, object_to_model, options, detect_nulls)
reflection = model_type.reflect_on_association(association)
raise ArgumentError, "Association #{association} wasn't found on model #{model_type.name}" unless reflection
raise ArgumentError, "Cannot include #{reflection.macro} association #{association} on model #{model_type.name} with has_many_connection" unless [:has_many].include?(reflection.macro)
connection_type = -> {
result = GraphQL::Models.get_graphql_type!(reflection.klass).connection_type
if (options[:nullable].nil? && detect_nulls) || options[:nullable] == false
result = result.to_non_null_type
end
result
}
camel_name = options[:name].to_s
DefinitionHelpers.register_field_metadata(graph_type, camel_name, {
macro: :has_many_connection,
macro_type: :association,
path: path,
association: association,
base_model_type: base_model_type,
model_type: model_type,
object_to_base_model: object_to_model,
})
connection_field = graph_type.fields[camel_name] = GraphQL::Field.define do
name(camel_name)
type(connection_type)
description options[:description] if options.include?(:description)
deprecation_reason options[:deprecation_reason] if options.include?(:deprecation_reason)
resolve -> (model, _args, _context) do
return nil unless model
model.public_send(association)
end
end
connection_field.connection = true
connection_field
end
end
end
end
| ruby | MIT | 025be0879466ee2e6d7324f4dd59b6a306e0e211 | 2026-01-04T17:48:42.035378Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/spec_helper.rb | spec/spec_helper.rb | # This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# The `.rspec` file also contains a few flags that are not defaults but that
# users commonly want.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
# These two settings work together to allow you to limit a spec run
# to individual examples or groups you care about by tagging them with
# `:focus` metadata. When nothing is tagged with `:focus`, all examples
# get run.
config.filter_run :focus
config.run_all_when_everything_filtered = true
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
# config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = true
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = 'doc'
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
# config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/integration/integration_spec.rb | spec/integration/integration_spec.rb | require 'spec_helper'
RSpec.describe 'Fix DB Schema Conflicts' do
let(:expected_lines) { reference_db_schema.lines }
it 'generates a sorted schema with no extra spacing' do
`cd spec/test-app && rm -f db/schema.rb && rake db:migrate`
generated_lines = File.readlines('spec/test-app/db/schema.rb')
generated_lines.zip(expected_lines).each do |generated, expected|
next if expected.nil?
next if expected.start_with?('ActiveRecord::Schema.define')
expect(generated).to eq(expected)
end
end
end
def reference_db_schema
<<-RUBY
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20160322223258) do
create_table "companies", force: :cascade do |t|
t.string "addr1"
t.string "addr2"
t.string "city"
t.datetime "created_at", null: false
t.string "name"
t.string "phone"
t.string "state"
t.datetime "updated_at", null: false
t.string "zip"
end
add_index "companies", ["city"], name: "index_companies_on_city"
add_index "companies", ["name"], name: "index_companies_on_name"
add_index "companies", ["state"], name: "index_companies_on_state"
create_table "people", force: :cascade do |t|
t.integer "age"
t.date "birthdate"
t.datetime "created_at", null: false
t.string "first_name"
t.string "last_name"
t.datetime "updated_at", null: false
end
RUBY
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/unit/autocorrect_configuration_spec.rb | spec/unit/autocorrect_configuration_spec.rb | require 'spec_helper'
require 'fix_db_schema_conflicts/autocorrect_configuration'
RSpec.describe FixDBSchemaConflicts::AutocorrectConfiguration do
subject(:autocorrect_config) { described_class }
it 'for versions up to 0.49.0' do
installed_rubocop(version: '0.39.0')
expect(autocorrect_config.load).to eq('.rubocop_schema.yml')
end
it 'for versions 0.49.0 and above' do
installed_rubocop(version: '0.49.0')
expect(autocorrect_config.load).to eq('.rubocop_schema.49.yml')
end
it 'for versions 0.53.0 and above' do
installed_rubocop(version: '0.53.0')
expect(autocorrect_config.load).to eq('.rubocop_schema.53.yml')
end
it 'for versions 0.77.0 and above' do
installed_rubocop(version: '0.77.0')
expect(autocorrect_config.load).to eq('.rubocop_schema.77.yml')
end
def installed_rubocop(version:)
allow(Gem).to receive_message_chain(:loaded_specs, :[], :version)
.and_return(Gem::Version.new(version))
end
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/app/helpers/application_helper.rb | spec/test-app/app/helpers/application_helper.rb | module ApplicationHelper
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/app/controllers/application_controller.rb | spec/test-app/app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/app/models/person.rb | spec/test-app/app/models/person.rb | class Person < ActiveRecord::Base
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/app/models/company.rb | spec/test-app/app/models/company.rb | class Company < ActiveRecord::Base
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/db/seeds.rb | spec/test-app/db/seeds.rb | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/db/schema.rb | spec/test-app/db/schema.rb | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20160322223258) do
create_table "companies", force: :cascade do |t|
t.string "addr1"
t.string "addr2"
t.string "city"
t.datetime "created_at", null: false
t.string "name"
t.string "phone"
t.string "state"
t.datetime "updated_at", null: false
t.string "zip"
end
add_index "companies", ["city"], name: "index_companies_on_city"
add_index "companies", ["name"], name: "index_companies_on_name"
add_index "companies", ["state"], name: "index_companies_on_state"
create_table "people", force: :cascade do |t|
t.integer "age"
t.date "birthdate"
t.datetime "created_at", null: false
t.string "first_name"
t.string "last_name"
t.datetime "updated_at", null: false
end
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/db/migrate/20160322223225_create_people.rb | spec/test-app/db/migrate/20160322223225_create_people.rb | class CreatePeople < ActiveRecord::Migration
def change
create_table :people do |t|
t.string :first_name
t.string :last_name
t.integer :age
t.date :birthdate
t.timestamps null: false
end
end
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/db/migrate/20160322223258_create_companies.rb | spec/test-app/db/migrate/20160322223258_create_companies.rb | class CreateCompanies < ActiveRecord::Migration
def change
create_table :companies do |t|
t.string :name
t.string :addr1
t.string :addr2
t.string :city
t.string :state
t.string :zip
t.string :phone
t.timestamps null: false
end
add_index :companies, :name
add_index :companies, :city
add_index :companies, :state
end
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/test/test_helper.rb | spec/test-app/test/test_helper.rb | ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/test/models/person_test.rb | spec/test-app/test/models/person_test.rb | require 'test_helper'
class PersonTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/test/models/company_test.rb | spec/test-app/test/models/company_test.rb | require 'test_helper'
class CompanyTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/config/application.rb | spec/test-app/config/application.rb | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module TestApp
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/config/environment.rb | spec/test-app/config/environment.rb | # Load the Rails application.
require File.expand_path('../application', __FILE__)
# Initialize the Rails application.
Rails.application.initialize!
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/config/routes.rb | spec/test-app/config/routes.rb | Rails.application.routes.draw do
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/config/boot.rb | spec/test-app/config/boot.rb | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' # Set up gems listed in the Gemfile.
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/config/initializers/filter_parameter_logging.rb | spec/test-app/config/initializers/filter_parameter_logging.rb | # Be sure to restart your server when you modify this file.
# Configure sensitive parameters which will be filtered from the log file.
Rails.application.config.filter_parameters += [:password]
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/config/initializers/session_store.rb | spec/test-app/config/initializers/session_store.rb | # Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_test-app_session'
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/config/initializers/wrap_parameters.rb | spec/test-app/config/initializers/wrap_parameters.rb | # Be sure to restart your server when you modify this file.
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json] if respond_to?(:wrap_parameters)
end
# To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do
# self.include_root_in_json = true
# end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/config/initializers/inflections.rb | spec/test-app/config/initializers/inflections.rb | # Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format. Inflections
# are locale specific, and you may define rules for as many different
# locales as you wish. All of these examples are active by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.acronym 'RESTful'
# end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/config/initializers/cookies_serializer.rb | spec/test-app/config/initializers/cookies_serializer.rb | # Be sure to restart your server when you modify this file.
Rails.application.config.action_dispatch.cookies_serializer = :json
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/config/initializers/assets.rb | spec/test-app/config/initializers/assets.rb | # Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
# Add additional assets to the asset load path
# Rails.application.config.assets.paths << Emoji.images_path
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# Rails.application.config.assets.precompile += %w( search.js )
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/config/initializers/backtrace_silencers.rb | spec/test-app/config/initializers/backtrace_silencers.rb | # Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/config/initializers/mime_types.rb | spec/test-app/config/initializers/mime_types.rb | # Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/config/environments/test.rb | spec/test-app/config/environments/test.rb | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure static file server for tests with Cache-Control for performance.
config.serve_static_files = true
config.static_cache_control = 'public, max-age=3600'
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Randomize the order test cases are executed.
config.active_support.test_order = :random
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/config/environments/development.rb | spec/test-app/config/environments/development.rb | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/spec/test-app/config/environments/production.rb | spec/test-app/config/environments/production.rb | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/lib/fix-db-schema-conflicts.rb | lib/fix-db-schema-conflicts.rb | require 'fix_db_schema_conflicts/schema_dumper.rb'
module FixDBSchemaConflicts
require 'fix_db_schema_conflicts/railtie' if defined?(Rails)
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/lib/fix_db_schema_conflicts/version.rb | lib/fix_db_schema_conflicts/version.rb | module FixDBSchemaConflicts
VERSION='3.1.1'
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/lib/fix_db_schema_conflicts/railtie.rb | lib/fix_db_schema_conflicts/railtie.rb | require 'fix-db-schema-conflicts'
require 'rails'
module FixDBSchemaConflicts
class Railtie < Rails::Railtie
railtie_name :fix_db_schema_conflicts
rake_tasks do
load "fix_db_schema_conflicts/tasks/db.rake"
end
end
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/lib/fix_db_schema_conflicts/schema_dumper.rb | lib/fix_db_schema_conflicts/schema_dumper.rb | require 'delegate'
module FixDBSchemaConflicts
module SchemaDumper
class ConnectionWithSorting < SimpleDelegator
def extensions
__getobj__.extensions.sort
end
def columns(table)
__getobj__.columns(table).sort_by(&:name)
end
def indexes(table)
__getobj__.indexes(table).sort_by(&:name)
end
def foreign_keys(table)
__getobj__.indexes(table).sort_by(&:name)
end
end
def extensions(*args)
with_sorting do
super(*args)
end
end
def table(*args)
with_sorting do
super(*args)
end
end
def with_sorting
old, @connection = @connection, ConnectionWithSorting.new(@connection)
result = yield
@connection = old
result
end
end
end
ActiveRecord::SchemaDumper.send(:prepend, FixDBSchemaConflicts::SchemaDumper)
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
jakeonrails/fix-db-schema-conflicts | https://github.com/jakeonrails/fix-db-schema-conflicts/blob/ae9135e0bb1fb142dd483f883da0064b8be17732/lib/fix_db_schema_conflicts/autocorrect_configuration.rb | lib/fix_db_schema_conflicts/autocorrect_configuration.rb | module FixDBSchemaConflicts
class AutocorrectConfiguration
def self.load
new.load
end
def load
if less_than_rubocop?(49)
'.rubocop_schema.yml'
elsif less_than_rubocop?(53)
'.rubocop_schema.49.yml'
elsif less_than_rubocop?(77)
'.rubocop_schema.53.yml'
else
'.rubocop_schema.77.yml'
end
end
private
def less_than_rubocop?(ver)
Gem.loaded_specs['rubocop'].version < Gem::Version.new("0.#{ver}.0")
end
end
end
| ruby | MIT | ae9135e0bb1fb142dd483f883da0064b8be17732 | 2026-01-04T17:48:46.828270Z | false |
blowmage/minitest-rails-capybara | https://github.com/blowmage/minitest-rails-capybara/blob/b2664ae1290f194f1e547342c6f0012a4859e717/test/rails_helper.rb | test/rails_helper.rb | require "minitest/autorun"
require "action_controller"
require "action_controller/railtie"
class TestApp < Rails::Application
config.secret_token = "821c600ece97fc4ba952d67655b4b475"
config.eager_load = false
initialize!
routes.draw do
root to: "hello#world"
end
end
class HelloController < ActionController::Base
def world
render html: "<!DOCTYPE html><title>TestApp</title>
<h1>Hello <span>World</span></h1>
<nav><ul><li><a href='/'>home</a></li></ul></nav>
<p><label>Email Address<input type='text'></label></p>
<button>random button</button>
<label>going<input type='checkbox' checked='checked'></label>
<label>avoid<input type='checkbox'></label>".html_safe
end
end
Rails.application = TestApp
require "rails/test_help"
require "minitest/rails/capybara"
Capybara.session_name = nil
Capybara.default_driver = nil
Capybara.use_default_driver
Capybara.app = TestApp
| ruby | MIT | b2664ae1290f194f1e547342c6f0012a4859e717 | 2026-01-04T17:48:44.113676Z | false |
blowmage/minitest-rails-capybara | https://github.com/blowmage/minitest-rails-capybara/blob/b2664ae1290f194f1e547342c6f0012a4859e717/test/test_spec_type.rb | test/test_spec_type.rb | require "rails_helper"
class TestCapybaraSpecType < Minitest::Test
def assert_capybara actual
assert_equal Capybara::Rails::TestCase, actual
end
def refute_capybara actual
refute_equal Capybara::Rails::TestCase, actual
end
def test_spec_type_resolves_for_matching_feature_strings
assert_capybara Minitest::Spec.spec_type("WidgetFeatureTest")
assert_capybara Minitest::Spec.spec_type("Widget Feature Test")
assert_capybara Minitest::Spec.spec_type("WidgetFeature")
assert_capybara Minitest::Spec.spec_type("Widget Feature")
# And is not case sensitive
assert_capybara Minitest::Spec.spec_type("widgetfeaturetest")
assert_capybara Minitest::Spec.spec_type("widget feature test")
assert_capybara Minitest::Spec.spec_type("widgetfeature")
assert_capybara Minitest::Spec.spec_type("widget feature")
end
def test_spec_type_wont_match_non_space_characters_feature
refute_capybara Minitest::Spec.spec_type("Widget Feature\tTest")
refute_capybara Minitest::Spec.spec_type("Widget Feature\rTest")
refute_capybara Minitest::Spec.spec_type("Widget Feature\nTest")
refute_capybara Minitest::Spec.spec_type("Widget Feature\fTest")
refute_capybara Minitest::Spec.spec_type("Widget FeatureXTest")
end
def test_spec_type_resolves_for_matching_browser_strings
assert_capybara Minitest::Spec.spec_type("WidgetBrowserTest")
assert_capybara Minitest::Spec.spec_type("Widget Browser Test")
assert_capybara Minitest::Spec.spec_type("WidgetBrowser")
assert_capybara Minitest::Spec.spec_type("Widget Browser")
# And is not case sensitive
assert_capybara Minitest::Spec.spec_type("widgetbrowsertest")
assert_capybara Minitest::Spec.spec_type("widget browser test")
assert_capybara Minitest::Spec.spec_type("widgetbrowser")
assert_capybara Minitest::Spec.spec_type("widget browser")
end
def test_spec_type_wont_match_non_space_characters_browser
refute_capybara Minitest::Spec.spec_type("Widget Browser\tTest")
refute_capybara Minitest::Spec.spec_type("Widget Browser\rTest")
refute_capybara Minitest::Spec.spec_type("Widget Browser\nTest")
refute_capybara Minitest::Spec.spec_type("Widget Browser\fTest")
refute_capybara Minitest::Spec.spec_type("Widget BrowserXTest")
end
def test_spec_type_resolves_for_additional_desc_capybara
refute_capybara Minitest::Spec.spec_type("Unmatched String")
assert_capybara Minitest::Spec.spec_type("Unmatched String", :capybara)
assert_capybara Minitest::Spec.spec_type("Unmatched String", :capybara, :other)
assert_capybara Minitest::Spec.spec_type("Unmatched String", :other, :capybara)
end
end
| ruby | MIT | b2664ae1290f194f1e547342c6f0012a4859e717 | 2026-01-04T17:48:44.113676Z | false |
blowmage/minitest-rails-capybara | https://github.com/blowmage/minitest-rails-capybara/blob/b2664ae1290f194f1e547342c6f0012a4859e717/test/test_sanity.rb | test/test_sanity.rb | require "minitest/autorun"
require "minitest-rails-capybara"
class TestMinitestRailsCapybara < Minitest::Unit::TestCase
def test_sanity
assert Minitest::Rails::Capybara::VERSION
end
end
| ruby | MIT | b2664ae1290f194f1e547342c6f0012a4859e717 | 2026-01-04T17:48:44.113676Z | false |
blowmage/minitest-rails-capybara | https://github.com/blowmage/minitest-rails-capybara/blob/b2664ae1290f194f1e547342c6f0012a4859e717/test/test_dsl.rb | test/test_dsl.rb | require "rails_helper"
describe "Capybara DSL Feature Test" do
it "can call using_wait_time" do
ret = "ZOMG! using_wait_time was called!"
Capybara.stub :using_wait_time, ret do
assert_equal ret, using_wait_time(6) {}
end
end
it "can call page" do
ret = "ZOMG! page called current_session!"
Capybara.stub :current_session, ret do
assert_equal ret, page
end
end
it "can call using_session" do
ret = "ZOMG! using_session was called!"
Capybara.stub :using_session, ret do
using_session(:name)
end
end
end
| ruby | MIT | b2664ae1290f194f1e547342c6f0012a4859e717 | 2026-01-04T17:48:44.113676Z | false |
blowmage/minitest-rails-capybara | https://github.com/blowmage/minitest-rails-capybara/blob/b2664ae1290f194f1e547342c6f0012a4859e717/test/test_assertions_expectation.rb | test/test_assertions_expectation.rb | require "rails_helper"
describe "Capybara Assertions and Expectations Feature Test" do
describe "have_content" do
it "has page with content" do
visit root_path
assert_content page, "Hello World"
refute_content page, "Goobye All!"
page.must_have_content "Hello World"
page.wont_have_content "Goobye All!"
end
end
describe "have_selector" do
it "has page with heading" do
visit root_path
assert_selector page, "h1"
refute_selector page, "h3"
page.must_have_selector "h1"
page.wont_have_selector "h3"
end
end
describe "have_link" do
it "has a link to home" do
visit root_path
assert_link page, "home"
refute_link page, "away"
page.must_have_link "home"
page.wont_have_link "away"
end
end
describe "have_field" do
it "has a button to submit" do
visit root_path
assert_field page, "Email Address"
refute_field page, "Bank Account"
page.must_have_field "Email Address"
page.wont_have_field "Bank Account"
end
end
describe "have_button" do
it "has a button to login" do
visit root_path
assert_button page, "random button"
refute_button page, "missing button"
page.must_have_button "random button"
page.wont_have_button "missing button"
end
end
describe "have_checked_field" do
it "has a button to submit" do
visit root_path
assert_checked_field page, "going"
refute_checked_field page, "avoid"
page.must_have_checked_field "going"
page.wont_have_checked_field "avoid"
end
end
describe "have_unchecked_field" do
it "has a button to submit" do
visit root_path
assert_unchecked_field page, "avoid"
refute_unchecked_field page, "going"
page.must_have_unchecked_field "avoid"
page.wont_have_unchecked_field "going"
end
end
end
| ruby | MIT | b2664ae1290f194f1e547342c6f0012a4859e717 | 2026-01-04T17:48:44.113676Z | false |
blowmage/minitest-rails-capybara | https://github.com/blowmage/minitest-rails-capybara/blob/b2664ae1290f194f1e547342c6f0012a4859e717/test/test_spec.rb | test/test_spec.rb | require "rails_helper"
feature "Capybara Spec DSL Feature Test" do
scenario "works unnested" do
assert true
end
feature "when nested" do
scenario "works nested" do
assert true
end
end
given(:thing) { "I am a thing." }
scenario "given works unnested" do
assert_equal "I am a thing.", thing
end
feature "given nested" do
given(:widget) { "I am a widget." }
scenario "works nested" do
assert_equal "I am a thing.", thing
end
scenario "widget works too" do
assert_equal "I am a widget.", widget
end
end
feature "metadata" do
scenario "default driver" do
assert_equal Capybara.default_driver, Capybara.current_driver
end
scenario "javascript driver", js: true do
assert_equal Capybara.javascript_driver, Capybara.current_driver
end
end
end
| ruby | MIT | b2664ae1290f194f1e547342c6f0012a4859e717 | 2026-01-04T17:48:44.113676Z | false |
blowmage/minitest-rails-capybara | https://github.com/blowmage/minitest-rails-capybara/blob/b2664ae1290f194f1e547342c6f0012a4859e717/lib/minitest-rails-capybara.rb | lib/minitest-rails-capybara.rb | require "minitest-rails"
module Minitest
module Rails
module Capybara
VERSION = "3.0.2"
end
end
end
| ruby | MIT | b2664ae1290f194f1e547342c6f0012a4859e717 | 2026-01-04T17:48:44.113676Z | false |
blowmage/minitest-rails-capybara | https://github.com/blowmage/minitest-rails-capybara/blob/b2664ae1290f194f1e547342c6f0012a4859e717/lib/minitest/rails/capybara.rb | lib/minitest/rails/capybara.rb | require "minitest/rails"
# Load minitest-capybara and minitest-matchers
require "minitest-capybara"
require "capybara/rails"
require "minitest/metadata"
module Capybara
module Rails
class Helpers # :nodoc:
include ::Rails.application.routes.url_helpers
include ::Rails.application.routes.mounted_helpers if ::Rails.application.routes.respond_to? :mounted_helpers
def initialize
self.default_url_options = ::Rails.application.routes.default_url_options
self.default_url_options[:host] ||= "test.local"
end
end
class TestCase < ::ActiveSupport::TestCase
include Capybara::DSL
include Capybara::Assertions
include Minitest::Metadata
# Register by name
register_spec_type(/(Feature|Browser)( ?Test)?\z/i, self)
register_spec_type(self) do |desc, *addl|
addl.include? :capybara
end
# Enable Capybara's spec DSL
class << self
alias :background :before
alias :scenario :it
alias :given :let
end
# Configure the driver using metadata
before do
if metadata[:js] == true
Capybara.current_driver = Capybara.javascript_driver
end
end
after do
Capybara.reset_sessions!
Capybara.use_default_driver
end
# Defer rails helpers methods to a different object
def __rails_helpers__ # :nodoc:
@__rails_helpers__ ||= ::Capybara::Rails::Helpers.new
end
def respond_to?(method, include_private = false) # :nodoc:
__rails_helpers__.respond_to?(method, include_private) || super
end
def method_missing(sym, *args, &block) # :nodoc:
if __rails_helpers__.respond_to?(sym, true)
__rails_helpers__.__send__(sym, *args, &block)
else
super
end
end
end
end
end
module Kernel # :nodoc:
def feature desc, &blk
describe "#{desc} Feature Test", &blk
end
end
module Capybara
module Assertions
##
# Assertion that there is button
#
# see Capybara::Assertions#refute_button
# see Capybara::Assertions#assert_no_button
# see Capybara::expectations#must_have_button
# see Capybara::expectations#wont_have_button
# :method: assert_button
##
# Assertion that there is no button
#
# see Capybara::Assertions#assert_button
# see Capybara::expectations#must_have_button
# see Capybara::expectations#wont_have_button
# :method: refute_button
# :alias: assert_no_button
##
# Assertion that there is checked_field
#
# see Capybara::Assertions#refute_checked_field
# see Capybara::Assertions#assert_no_checked_field
# see Capybara::expectations#must_have_checked_field
# see Capybara::expectations#wont_have_checked_field
# :method: assert_checked_field
##
# Assertion that there is no checked_field
#
# see Capybara::Assertions#assert_checked_field
# see Capybara::expectations#must_have_checked_field
# see Capybara::expectations#wont_have_checked_field
# :method: refute_checked_field
# :alias: assert_no_checked_field
##
# Assertion that there is content
#
# see Capybara::Assertions#refute_content
# see Capybara::Assertions#assert_no_content
# see Capybara::expectations#must_have_content
# see Capybara::expectations#wont_have_content
# :method: assert_content
##
# Assertion that there is no content
#
# see Capybara::Assertions#assert_content
# see Capybara::expectations#must_have_content
# see Capybara::expectations#wont_have_content
# :method: refute_content
# :alias: assert_no_content
##
# Assertion that there is css
#
# see Capybara::Assertions#refute_css
# see Capybara::Assertions#assert_no_css
# see Capybara::expectations#must_have_css
# see Capybara::expectations#wont_have_css
# :method: assert_css
##
# Assertion that there is no css
#
# see Capybara::Assertions#assert_css
# see Capybara::expectations#must_have_css
# see Capybara::expectations#wont_have_css
# :method: refute_css
# :alias: assert_no_css
##
# Assertion that there is field
#
# see Capybara::Assertions#refute_field
# see Capybara::Assertions#assert_no_field
# see Capybara::expectations#must_have_field
# see Capybara::expectations#wont_have_field
# :method: assert_field
##
# Assertion that there is no field
#
# see Capybara::Assertions#assert_field
# see Capybara::expectations#must_have_field
# see Capybara::expectations#wont_have_field
# :method: refute_field
# :alias: assert_no_field
##
# Assertion that there is link
#
# see Capybara::Assertions#refute_link
# see Capybara::Assertions#assert_no_link
# see Capybara::expectations#must_have_link
# see Capybara::expectations#wont_have_link
# :method: assert_link
##
# Assertion that there is no link
#
# see Capybara::Assertions#assert_link
# see Capybara::expectations#must_have_link
# see Capybara::expectations#wont_have_link
# :method: refute_link
# :alias: assert_no_link
##
# Assertion that there is select
#
# see Capybara::Assertions#refute_select
# see Capybara::Assertions#assert_no_select
# see Capybara::expectations#must_have_select
# see Capybara::expectations#wont_have_select
# :method: assert_select
##
# Assertion that there is no select
#
# see Capybara::Assertions#assert_select
# see Capybara::expectations#must_have_select
# see Capybara::expectations#wont_have_select
# :method: refute_select
# :alias: assert_no_select
##
# Assertion that there is selector
#
# see Capybara::Assertions#refute_selector
# see Capybara::Assertions#assert_no_selector
# see Capybara::expectations#must_have_selector
# see Capybara::expectations#wont_have_selector
# :method: assert_selector
##
# Assertion that there is no selector
#
# see Capybara::Assertions#assert_selector
# see Capybara::expectations#must_have_selector
# see Capybara::expectations#wont_have_selector
# :method: refute_selector
# :alias: assert_no_selector
##
# Assertion that there is table
#
# see Capybara::Assertions#refute_table
# see Capybara::Assertions#assert_no_table
# see Capybara::expectations#must_have_table
# see Capybara::expectations#wont_have_table
# :method: assert_table
##
# Assertion that there is no table
#
# see Capybara::Assertions#assert_table
# see Capybara::expectations#must_have_table
# see Capybara::expectations#wont_have_table
# :method: refute_table
# :alias: assert_no_table
##
# Assertion that there is text
#
# see Capybara::Assertions#refute_text
# see Capybara::Assertions#assert_no_text
# see Capybara::expectations#must_have_text
# see Capybara::expectations#wont_have_text
# :method: assert_text
##
# Assertion that there is no text
#
# see Capybara::Assertions#assert_text
# see Capybara::expectations#must_have_text
# see Capybara::expectations#wont_have_text
# :method: refute_text
# :alias: assert_no_text
##
# Assertion that there is unchecked_field
#
# see Capybara::Assertions#refute_unchecked_field
# see Capybara::Assertions#assert_no_unchecked_field
# see Capybara::expectations#must_have_unchecked_field
# see Capybara::expectations#wont_have_unchecked_field
# :method: assert_unchecked_field
##
# Assertion that there is no unchecked_field
#
# see Capybara::Assertions#assert_unchecked_field
# see Capybara::expectations#must_have_unchecked_field
# see Capybara::expectations#wont_have_unchecked_field
# :method: refute_unchecked_field
# :alias: assert_no_unchecked_field
##
# Assertion that there is xpath
#
# see Capybara::Assertions#refute_xpath
# see Capybara::Assertions#assert_no_xpath
# see Capybara::expectations#must_have_xpath
# see Capybara::expectations#wont_have_xpath
# :method: assert_xpath
##
# Assertion that there is no xpath
#
# see Capybara::Assertions#assert_xpath
# see Capybara::expectations#must_have_xpath
# see Capybara::expectations#wont_have_xpath
# :method: refute_xpath
# :alias: assert_no_xpath
end
module Expectations
##
# Expectation that there is button
#
# see Capybara::Expectations#wont_have_button
# see Capybara::Assertions#assert_button
# see Capybara::Assertions#refute_button
# see Capybara::Assertions#assert_no_button
# :method: must_have_button
##
# Expectation that there is no button
#
# see Capybara::Expectations#must_have_button
# see Capybara::Assertions#assert_button
# see Capybara::Assertions#refute_button
# see Capybara::Assertions#assert_no_button
# :method: wont_have_button
##
# Expectation that there is checked_field
#
# see Capybara::Expectations#wont_have_checked_field
# see Capybara::Assertions#assert_checked_field
# see Capybara::Assertions#refute_checked_field
# see Capybara::Assertions#assert_no_checked_field
# :method: must_have_checked_field
##
# Expectation that there is no checked_field
#
# see Capybara::Expectations#must_have_checked_field
# see Capybara::Assertions#assert_checked_field
# see Capybara::Assertions#refute_checked_field
# see Capybara::Assertions#assert_no_checked_field
# :method: wont_have_checked_field
##
# Expectation that there is content
#
# see Capybara::Expectations#wont_have_content
# see Capybara::Assertions#assert_content
# see Capybara::Assertions#refute_content
# see Capybara::Assertions#assert_no_content
# :method: must_have_content
##
# Expectation that there is no content
#
# see Capybara::Expectations#must_have_content
# see Capybara::Assertions#assert_content
# see Capybara::Assertions#refute_content
# see Capybara::Assertions#assert_no_content
# :method: wont_have_content
##
# Expectation that there is css
#
# see Capybara::Expectations#wont_have_css
# see Capybara::Assertions#assert_css
# see Capybara::Assertions#refute_css
# see Capybara::Assertions#assert_no_css
# :method: must_have_css
##
# Expectation that there is no css
#
# see Capybara::Expectations#must_have_css
# see Capybara::Assertions#assert_css
# see Capybara::Assertions#refute_css
# see Capybara::Assertions#assert_no_css
# :method: wont_have_css
##
# Expectation that there is field
#
# see Capybara::Expectations#wont_have_field
# see Capybara::Assertions#assert_field
# see Capybara::Assertions#refute_field
# see Capybara::Assertions#assert_no_field
# :method: must_have_field
##
# Expectation that there is no field
#
# see Capybara::Expectations#must_have_field
# see Capybara::Assertions#assert_field
# see Capybara::Assertions#refute_field
# see Capybara::Assertions#assert_no_field
# :method: wont_have_field
##
# Expectation that there is link
#
# see Capybara::Expectations#wont_have_link
# see Capybara::Assertions#assert_link
# see Capybara::Assertions#refute_link
# see Capybara::Assertions#assert_no_link
# :method: must_have_link
##
# Expectation that there is no link
#
# see Capybara::Expectations#must_have_link
# see Capybara::Assertions#assert_link
# see Capybara::Assertions#refute_link
# see Capybara::Assertions#assert_no_link
# :method: wont_have_link
##
# Expectation that there is select
#
# see Capybara::Expectations#wont_have_select
# see Capybara::Assertions#assert_select
# see Capybara::Assertions#refute_select
# see Capybara::Assertions#assert_no_select
# :method: must_have_select
##
# Expectation that there is no select
#
# see Capybara::Expectations#must_have_select
# see Capybara::Assertions#assert_select
# see Capybara::Assertions#refute_select
# see Capybara::Assertions#assert_no_select
# :method: wont_have_select
##
# Expectation that there is selector
#
# see Capybara::Expectations#wont_have_selector
# see Capybara::Assertions#assert_selector
# see Capybara::Assertions#refute_selector
# see Capybara::Assertions#assert_no_selector
# :method: must_have_selector
##
# Expectation that there is no selector
#
# see Capybara::Expectations#must_have_selector
# see Capybara::Assertions#assert_selector
# see Capybara::Assertions#refute_selector
# see Capybara::Assertions#assert_no_selector
# :method: wont_have_selector
##
# Expectation that there is table
#
# see Capybara::Expectations#wont_have_table
# see Capybara::Assertions#assert_table
# see Capybara::Assertions#refute_table
# see Capybara::Assertions#assert_no_table
# :method: must_have_table
##
# Expectation that there is no table
#
# see Capybara::Expectations#must_have_table
# see Capybara::Assertions#assert_table
# see Capybara::Assertions#refute_table
# see Capybara::Assertions#assert_no_table
# :method: wont_have_table
##
# Expectation that there is text
#
# see Capybara::Expectations#wont_have_text
# see Capybara::Assertions#assert_text
# see Capybara::Assertions#refute_text
# see Capybara::Assertions#assert_no_text
# :method: must_have_text
##
# Expectation that there is no text
#
# see Capybara::Expectations#must_have_text
# see Capybara::Assertions#assert_text
# see Capybara::Assertions#refute_text
# see Capybara::Assertions#assert_no_text
# :method: wont_have_text
##
# Expectation that there is unchecked_field
#
# see Capybara::Expectations#wont_have_unchecked_field
# see Capybara::Assertions#assert_unchecked_field
# see Capybara::Assertions#refute_unchecked_field
# see Capybara::Assertions#assert_no_unchecked_field
# :method: must_have_unchecked_field
##
# Expectation that there is no unchecked_field
#
# see Capybara::Expectations#must_have_unchecked_field
# see Capybara::Assertions#assert_unchecked_field
# see Capybara::Assertions#refute_unchecked_field
# see Capybara::Assertions#assert_no_unchecked_field
# :method: wont_have_unchecked_field
##
# Expectation that there is xpath
#
# see Capybara::Expectations#wont_have_xpath
# see Capybara::Assertions#assert_xpath
# see Capybara::Assertions#refute_xpath
# see Capybara::Assertions#assert_no_xpath
# :method: must_have_xpath
##
# Expectation that there is no xpath
#
# see Capybara::Expectations#must_have_xpath
# see Capybara::Assertions#assert_xpath
# see Capybara::Assertions#refute_xpath
# see Capybara::Assertions#assert_no_xpath
# :method: wont_have_xpath
end
end
| ruby | MIT | b2664ae1290f194f1e547342c6f0012a4859e717 | 2026-01-04T17:48:44.113676Z | false |
blowmage/minitest-rails-capybara | https://github.com/blowmage/minitest-rails-capybara/blob/b2664ae1290f194f1e547342c6f0012a4859e717/lib/generators/minitest/feature/feature_generator.rb | lib/generators/minitest/feature/feature_generator.rb | require "minitest-rails"
require "generators/minitest"
module Minitest
module Generators
class FeatureGenerator < Base
def self.source_root
@_minitest_capybara_source_root ||= File.expand_path(File.join(File.dirname(__FILE__), "templates"))
end
class_option :spec, type: :boolean, default: true, desc: "Use Minitest::Spec DSL"
check_class_collision suffix: "Test"
def create_test_files
if options[:spec]
template "feature_spec.rb", File.join("test/features", class_path, "#{file_name}_test.rb")
else
template "feature_test.rb", File.join("test/features", class_path, "#{file_name}_test.rb")
end
end
end
end
end
| ruby | MIT | b2664ae1290f194f1e547342c6f0012a4859e717 | 2026-01-04T17:48:44.113676Z | false |
blowmage/minitest-rails-capybara | https://github.com/blowmage/minitest-rails-capybara/blob/b2664ae1290f194f1e547342c6f0012a4859e717/lib/generators/minitest/feature/templates/feature_test.rb | lib/generators/minitest/feature/templates/feature_test.rb | require "test_helper"
class <%= class_name %>Test < Capybara::Rails::TestCase
# test "sanity" do
# visit root_path
# assert_content page, "Hello World"
# refute_content page, "Goodbye All!"
# end
end
| ruby | MIT | b2664ae1290f194f1e547342c6f0012a4859e717 | 2026-01-04T17:48:44.113676Z | false |
blowmage/minitest-rails-capybara | https://github.com/blowmage/minitest-rails-capybara/blob/b2664ae1290f194f1e547342c6f0012a4859e717/lib/generators/minitest/feature/templates/feature_spec.rb | lib/generators/minitest/feature/templates/feature_spec.rb | require "test_helper"
feature "<%= class_name %>" do
# scenario "the test is sound" do
# visit root_path
# page.must_have_content "Hello World"
# page.wont_have_content "Goodbye All!"
# end
end
| ruby | MIT | b2664ae1290f194f1e547342c6f0012a4859e717 | 2026-01-04T17:48:44.113676Z | false |
nhoizey/jekyll-postfiles | https://github.com/nhoizey/jekyll-postfiles/blob/14c161dece423ecf731c04fb84ad486ac7f19275/spec/jekyll_postfiles_spec.rb | spec/jekyll_postfiles_spec.rb | require "spec_helper"
describe Jekyll::PostFiles do
let(:page) { make_page }
let(:site) { make_site }
let(:post) { make_post }
let(:context) { make_context(:page => page, :site => site) }
let(:url) { "" }
before do
Jekyll.logger.log_level = :error
site.process
end
it "copies image from global assets folder" do
expect(Pathname.new(File.expand_path('assets/jekyll.png', dest_dir))).to exist
end
it "copies image from post folder" do
expect(Pathname.new(File.expand_path('2016/06/09/cloudflare.png', dest_dir))).to exist
end
end
| ruby | MIT | 14c161dece423ecf731c04fb84ad486ac7f19275 | 2026-01-04T17:48:46.711514Z | false |
nhoizey/jekyll-postfiles | https://github.com/nhoizey/jekyll-postfiles/blob/14c161dece423ecf731c04fb84ad486ac7f19275/spec/spec_helper.rb | spec/spec_helper.rb | $LOAD_PATH.unshift File.expand_path("../lib", __dir__)
require "jekyll"
require "jekyll-postfiles"
ENV["JEKYLL_LOG_LEVEL"] = "error"
def dest_dir
File.expand_path("../tmp/dest", __dir__)
end
def source_dir
File.expand_path("fixtures", __dir__)
end
CONFIG_DEFAULTS = {
"source" => source_dir,
"destination" => dest_dir,
"gems" => ["jekyll-postfiles"],
}.freeze
def make_page(options = {})
page = Jekyll::Page.new site, CONFIG_DEFAULTS["source"], "", "page.md"
page.data = options
page
end
def make_post(options = {})
filename = File.expand_path("_posts/2016-06-09-cloudflare/2016-06-09-so-long-cloudflare-and-thanks-for-all-the-fissh.md", CONFIG_DEFAULTS["source"])
config = { :site => site, :collection => site.collections["posts"] }
page = Jekyll::Document.new filename, config
page.merge_data!(options)
page
end
def make_site(options = {})
config = Jekyll.configuration CONFIG_DEFAULTS.merge(options)
Jekyll::Site.new(config)
end
def make_context(registers = {}, environments = {})
Liquid::Context.new(environments, {}, { :site => site, :page => page }.merge(registers))
end
| ruby | MIT | 14c161dece423ecf731c04fb84ad486ac7f19275 | 2026-01-04T17:48:46.711514Z | false |
nhoizey/jekyll-postfiles | https://github.com/nhoizey/jekyll-postfiles/blob/14c161dece423ecf731c04fb84ad486ac7f19275/lib/jekyll-postfiles.rb | lib/jekyll-postfiles.rb | # frozen_string_literal: true
require "jekyll/postfiles"
| ruby | MIT | 14c161dece423ecf731c04fb84ad486ac7f19275 | 2026-01-04T17:48:46.711514Z | false |
nhoizey/jekyll-postfiles | https://github.com/nhoizey/jekyll-postfiles/blob/14c161dece423ecf731c04fb84ad486ac7f19275/lib/jekyll/postfiles.rb | lib/jekyll/postfiles.rb | # frozen_string_literal: true
require "jekyll"
require "pathname"
module Jekyll
module PostFiles
# there's a bug in the regex Document::DATE_FILENAME_MATCHER:
# %r!^(?:.+/)*(\d{2,4}-\d{1,2}-\d{1,2})-(.*)(\.[^.]+)$!
# used by:
# jekyll/lib/jekyll/readers/post_reader.rb#read_posts
# which ultimately populates:
# site.posts.docs
#
# the original code's intention was to match:
# all files with a date in the name
# but it accidentally matches also:
# all files immediately within a directory whose name contains a date
#
# our plugin changes the regex, to:
# avoid false positive when directory name matches date regex
Hooks.register :site, :after_reset do |_site|
# Suppress warning messages.
original_verbose = $VERBOSE
$VERBOSE = nil
Document.const_set("DATE_FILENAME_MATCHER", PostFileGenerator::FIXED_DATE_FILENAME_MATCHER)
# Activate warning messages again.
$VERBOSE = original_verbose
end
class PostFile < StaticFile
# Initialize a new PostFile.
#
# site - The Site.
# base - The String path to the <source> - /srv/jekyll
# dir - The String path between <source> and the file - _posts/somedir
# name - The String filename of the file - cool.svg
# dest - The String path to the containing folder of the document which is output - /dist/blog/[:tag/]*:year/:month/:day
def initialize(site, base, dir, name, dest)
super(site, base, dir, name)
@name = name
@dest = dest
end
# Obtain destination path.
#
# dest - The String path to the destination dir.
#
# Returns destination file path.
def destination(_dest)
File.join(@dest, @name)
end
end
class PostFileGenerator < Generator
FIXED_DATE_FILENAME_MATCHER = %r!^(?:.+/)*(\d{2,4}-\d{1,2}-\d{1,2})-([^/]*)(\.[^.]+)$!.freeze
# _posts/
# 2018-01-01-whatever.md # there's a date on this filename, so it will be treated as a post
# # it's a direct descendant of _posts, so we do not treat it as an asset root
# somedir/
# 2018-05-01-some-post.md # there's a date on this filename, so it will be treated as a post.
# # moreover, we will treat its dir as an asset root
# cool.svg # there's no date on this filename, so it will be treated as an asset
# undated.md # there's no date on this filename, so it will be treated as an asset
# img/
# cool.png # yes, even deeply-nested files are eligible to be copied.
def generate(site)
site_srcroot = Pathname.new site.source
posts_src_dir = site_srcroot + "_posts"
drafts_src_dir = site_srcroot + "_drafts"
# Jekyll.logger.warn("[PostFiles]", "_posts: #{posts_src_dir}")
# Jekyll.logger.warn("[PostFiles]", "docs: #{site.posts.docs.map(&:path)}")
docs_with_dirs = site.posts.docs
.reject do |doc|
Pathname.new(doc.path).dirname.instance_eval do |dirname|
[posts_src_dir, drafts_src_dir].reduce(false) do |acc, dir|
acc || dirname.eql?(dir)
end
end
end
# Jekyll.logger.warn("[PostFiles]", "postdirs: #{docs_with_dirs.map{|doc| Pathname.new(doc.path).dirname}}")
assets = docs_with_dirs.map do |doc|
dest_dir = Pathname.new(doc.destination("")).dirname
Pathname.new(doc.path).dirname.instance_eval do |postdir|
Dir[postdir + "**/*"]
.reject { |fname| fname =~ FIXED_DATE_FILENAME_MATCHER }
.reject { |fname| File.directory? fname }
.map do |fname|
asset_abspath = Pathname.new fname
srcroot_to_asset = asset_abspath.relative_path_from(site_srcroot)
srcroot_to_assetdir = srcroot_to_asset.dirname
asset_basename = srcroot_to_asset.basename
assetdir_abs = site_srcroot + srcroot_to_assetdir
postdir_to_assetdir = assetdir_abs.relative_path_from(postdir)
PostFile.new(site, site_srcroot, srcroot_to_assetdir.to_path, asset_basename, (dest_dir + postdir_to_assetdir).to_path)
end
end
end.flatten
site.static_files.concat(assets)
end
end
end
end
| ruby | MIT | 14c161dece423ecf731c04fb84ad486ac7f19275 | 2026-01-04T17:48:46.711514Z | false |
nhoizey/jekyll-postfiles | https://github.com/nhoizey/jekyll-postfiles/blob/14c161dece423ecf731c04fb84ad486ac7f19275/lib/jekyll/postfiles/version.rb | lib/jekyll/postfiles/version.rb | # frozen_string_literal: true
module Jekyll
module PostFiles
VERSION = "3.1.0"
end
end
| ruby | MIT | 14c161dece423ecf731c04fb84ad486ac7f19275 | 2026-01-04T17:48:46.711514Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/spec/indent_block_spec.rb | spec/indent_block_spec.rb | require 'spec_helper'
describe Minidown do
describe 'indent should parse as code block' do
it 'should parse correct' do
str =<<HERE
Here is a Python code example
without syntax highlighting:
def foo:
if not bar:
return true
HERE
Minidown.render(str).should == "<p>Here is a Python code example<br>without syntax highlighting:</p><pre><code>def foo:\n if not bar:\n return true</code></pre>"
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/spec/h1_and_h2_spec.rb | spec/h1_and_h2_spec.rb | require 'spec_helper'
describe Minidown do
describe '======== or -------' do
it 'should parse as text' do
%w{===== =====hello ------nihao}.each do |str|
Minidown.render(str).should == "<p>#{str}</p>"
end
end
it 'should parse as h1' do
%w{======= ==== === = ==}.each do |s|
str =<<HERE
h1
#{s}
HERE
if s.size < 3
Minidown.render(str).should == "<p>h1<br>#{s}</p>"
else
Minidown.render(str).should == "<h1>h1</h1>"
end
end
end
it 'should parse as h2' do
%w{------- ---- --- - --}.each do |s|
str =<<HERE
h2
#{s}
HERE
if s.size < 3
Minidown.render(str).should == "<p>h2<br>#{s}</p>"
else
Minidown.render(str).should == "<h2>h2</h2>"
end
end
end
it 'should parse newtext' do
%w{------ =======}.each do |s|
str =<<HERE
title
#{s}should show text
HERE
tag = (s[0] == '-' ? 'h2' : 'h1')
Minidown.render(str).should == "<#{tag}>title</#{tag}><p>should show text</p>"
end
end
it 'should not parse as h2 if preline is h tag' do
str = "#### [ruby](http://ruby-lang.org/)\n---"
Minidown.render(str).should == "<h4><a href=\"http://ruby-lang.org/\">ruby</a></h4><hr>"
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/spec/code_block_spec.rb | spec/code_block_spec.rb | require 'spec_helper'
describe Minidown do
describe 'code_block' do
it 'should parse correct' do
str =<<HERE
```
should in code block
in block
```
HERE
Minidown.render(str).should == "<pre><code>should in code block\n\nin block</code></pre>"
end
it 'should allow tildes as well as backquotes' do
str =<<HERE
~~~
should in code block
in block
~~~
HERE
Minidown.render(str).should == "<pre><code>should in code block\n\nin block</code></pre>"
end
it 'should allow arbitrary number of `' do
str =<<HERE
````````````
should in code block
in block
````````````
HERE
Minidown.render(str).should == "<pre><code>should in code block\n\nin block</code></pre>"
end
it 'should allow arbitrary number of tildes' do
str =<<HERE
~~~~~~~~~~~
should in code block
in block
~~~~~~~~~~~
HERE
Minidown.render(str).should == "<pre><code>should in code block\n\nin block</code></pre>"
end
it 'should ignore space' do
str =<<HERE
```
should in code block
in block
```
HERE
Minidown.render(str).should == "<pre><code>should in code block\nin block</code></pre>"
end
it 'should have lang attribute' do
str =<<HERE
``` ruby
should in code block
in block
```
HERE
Minidown.render(str).should == "<pre><code class=\"ruby\">should in code block\n\nin block</code></pre>"
end
it 'should have lang attribute with tildes' do
str =<<HERE
~~~ ruby
should in code block
in block
~~~
HERE
Minidown.render(str).should == "<pre><code class=\"ruby\">should in code block\n\nin block</code></pre>"
end
it 'should allow escape' do
str =<<HERE
\\```
should in code block
in block
\\```
HERE
Minidown.render(str).should == "<p>```<br>should in code block</p><p>in block<br>```</p>"
str =<<HERE
\\~~~
should in code block
in block
\\~~~
HERE
Minidown.render(str).should == "<p>~~~<br>should in code block</p><p>in block<br>~~~</p>"
end
it 'should not escape content' do
str =<<HERE
```
\\+
\\.
\\-
\\*
<>
```
HERE
Minidown.render(str).should == "<pre><code>\\+\n\\.\n\\-\n\\*\n<></code></pre>"
str =<<HERE
~~~
\\+
\\.
\\-
\\*
<>
~~~
HERE
Minidown.render(str).should == "<pre><code>\\+\n\\.\n\\-\n\\*\n<></code></pre>"
end
it 'should escape html tag' do
str ='```
<a>hello</a>
```'
Minidown.render(str).should == "<pre><code><a>hello</a></code></pre>"
str ='~~~
<a>hello</a>
~~~'
Minidown.render(str).should == "<pre><code><a>hello</a></code></pre>"
end
it 'should not auto convert' do
str = '```
jjyruby@gmail.com
```'
Minidown.render(str).should == '<pre><code>jjyruby@gmail.com</code></pre>'
str = '~~~
jjyruby@gmail.com
~~~'
Minidown.render(str).should == '<pre><code>jjyruby@gmail.com</code></pre>'
end
describe "work with code block handler" do
it "work with handler" do
str = '``` ruby
puts "We love ruby!"
```'
handler = ->(lang, content){"`#{content}` is write in #{lang}"}
Minidown.render(str, code_block_handler: handler).should == '`puts "We love ruby!"` is write in ruby'
end
it "lang should return empty if not specific language" do
str = '```
not specific language
```'
handler = ->(lang, content){ "#{content}, so lang is #{lang.inspect}" }
Minidown.render(str, code_block_handler: handler).should == 'not specific language, so lang is nil'
end
it "handler should pass raw content" do
str = '```
<script>
```'
handler = ->(lang, content){ content.gsub("<", "{").gsub(">", "}") }
Minidown.render(str, code_block_handler: handler).should == '{script}'
end
it "should not escape <>" do
test_cases = %w{<script> <> < >}
handler = ->(lang, content){ content }
parser = Minidown::Parser.new(code_block_handler: handler)
test_cases.each do |case_s|
str = "```\n#{case_s}\n```"
parser.render(str).should == case_s
end
end
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/spec/raw_html_spec.rb | spec/raw_html_spec.rb | require 'spec_helper'
describe Minidown do
describe 'raw html spec' do
it 'should render correctly' do
Minidown.render('<a></a>').should == "<p><a></a></p>"
end
it 'should render mutilple line well' do
str = '<table>
<tr>
<td>first</td>
</tr>
<tr>
<td>second</td>
</tr>
</table>'
Minidown.render(str).should == "<p><table><tr><td>first</td></tr><tr><td>second</td></tr></table></p>"
end
it 'can be escaped' do
Minidown.render("\\<a\\>\\</a\\>\\\\<br\\\\>").should == "<p><a></a>\\<br\\></p>"
end
it 'should allow mix with markdown' do
str = 'Table for two
-------------
<table>
<tr>
<th>ID</th><th>Name</th><th>Rank</th>
</tr>
<tr>
<td>1</td><td>Tom Preston-Werner</td><td>Awesome</td>
</tr>
<tr>
<td>2</td><td>Albert Einstein</td><td>Nearly as awesome</td>
</tr>
</table>'
Minidown.render(str).should == "<h2>Table for two</h2><p><table><tr><th>ID</th><th>Name</th><th>Rank</th></tr><tr><td>1</td><td>Tom Preston-Werner</td><td>Awesome</td></tr><tr><td>2</td><td>Albert Einstein</td><td>Nearly as awesome</td></tr></table></p>"
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/spec/li_spec.rb | spec/li_spec.rb | require 'spec_helper'
describe Minidown do
describe 'ul' do
it 'should basic parse correct' do
%w{* + -}.each do |s|
str = "#{s} ul"
Minidown.render(str).should == '<ul><li>ul</li></ul>'
str = " #{s} ul"
Minidown.render(str).should == '<ul><li>ul</li></ul>'
str = "#{s} li1\n#{s} li2\n#{s} li3"
Minidown.render(str).should == '<ul><li>li1</li><li>li2</li><li>li3</li></ul>'
end
end
it 'should not parse' do
%w{* + -}.each do |s|
str = "#{s}ul"
Minidown.render(str).should == "<p>#{str}</p>"
end
end
it 'escape' do
%w{* + -}.each do |s|
str = "\\#{s} li"
Minidown.render(str).should == "<p>#{str.gsub("\\", '')}</p>"
str = "#{s}\\ li"
Minidown.render(str).should == "<p>#{str}</p>"
end
end
it 'auto new line' do
str = '+ li1
newline
- li2
newline'
Minidown.render(str).should == "<ul><li><p>li1</p>\n<p>newline</p></li><li>li2\nnewline</li></ul>"
end
it '<p> in li' do
str = '* li1
newline
* li2
newline'
Minidown.render(str).should == "<ul><li><p>li1<br>newline</p></li><li><p>li2<br>newline</p></li></ul>"
end
it 'should parse' do
str = 'line
* li2'
Minidown.render(str).should == "<p>line</p><ul><li>li2</li></ul>"
end
it 'two ul' do
str = '- li1
newline
* li2
newline'
Minidown.render(str).should == '<ul><li><p>li1<br>newline</p></li><li><p>li2<br>newline</p></li></ul>'
end
it 'can work with indent' do
str =<<HERE
* here a line
noindent
HERE
Minidown.render(str).should == "<ul><li>here a line\nnoindent</li></ul>"
str =<<HERE
* here a line
noindent
HERE
Minidown.render(str).should == "<ul><li><p>here a line</p>\n<p>noindent</p></li></ul>"
end
it 'can work with block' do
str =<<HERE
* A list item with a blockquote:
> This is a blockquote
> inside a list item.
HERE
Minidown.render(str).should == "<ul><li>A list item with a blockquote:\n<blockquote><p>This is a blockquote</p><p>inside a list item.</p></blockquote></li></ul>"
end
it 'can not work with block without indent' do
str =<<HERE
* A list item with a blockquote:
> This is a blockquote
> inside a list item.
HERE
Minidown.render(str).should == "<ul><li>A list item with a blockquote:</li></ul><blockquote><p>This is a blockquote</p><p>inside a list item.</p></blockquote>"
end
it 'newline' do
str =<<HERE
* A list
Newline
HERE
Minidown.render(str).should == "<ul><li>A list</li></ul><p>Newline</p>"
end
it 'should parse correct' do
str = '* Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,
viverra nec, fringilla in, laoreet vitae, risus.
* Donec sit amet nisl. Aliquam semper ipsum sit amet velit.
Suspendisse id sem consectetuer libero luctus adipiscing.
---
Hi.'
Minidown.render(str).should == "<ul><li><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>\n<p>Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,</p>\n<p>viverra nec, fringilla in, laoreet vitae, risus.</p></li><li><p>Donec sit amet nisl. Aliquam semper ipsum sit amet velit.</p>\n<p>Suspendisse id sem consectetuer libero luctus adipiscing.</p></li></ul><hr><p>Hi.</p>"
end
it 'list with indent' do
str ='* first
start with
#and indent'
Minidown.render(str).should == "<ul><li>first\nstart with</li></ul><h1>and indent</h1>"
end
it 'nested should parse correct' do
str = '* 1
* 2
* 3
* 4
* 5
* 6
* 7'
Minidown.render(str).should == '<ul><li>1
<ul><li>2 </li><li>3</li></ul></li><li>4
<ul><li>5</li><li>6</li><li>7</li></ul></li></ul>'
end
end
describe 'ol' do
before :each do
@random_nums = 5.times.map{rand 42..4242}
end
it 'should basic parse correct' do
5.times.map{(42..4242).to_a.sample 3}.each do |n, n2, n3|
str = "#{n}. ol"
Minidown.render(str).should == '<ol><li>ol</li></ol>'
str = "#{n}. li1\n#{n2}. li2\n#{n3}. li3"
Minidown.render(str).should == '<ol><li>li1</li><li>li2</li><li>li3</li></ol>'
end
end
it 'should not parse' do
@random_nums.each do |s|
str = "#{s}ol"
Minidown.render(str).should == "<p>#{str}</p>"
str = " #{s} ol"
Minidown.render(str).should == "<p>#{str}</p>"
end
end
it 'escape' do
@random_nums.each do |s|
str = "\\#{s}. li"
Minidown.render(str).should == "<p>#{str}</p>"
str = "#{s}.\\ li"
Minidown.render(str).should == "<p>#{str}</p>"
str = "#{s}\\. li"
Minidown.render(str).should == "<p>#{s}. li</p>"
end
end
it 'auto new line' do
str = '1. li1
newline
2. li2
newline'
Minidown.render(str).should == "<ol><li><p>li1</p>\n<p>newline</p></li><li>li2\nnewline</li></ol>"
end
it '<p> in li' do
str = '1. li1
newline
2. li2
newline'
Minidown.render(str).should == '<ol><li><p>li1<br>newline</p></li><li><p>li2<br>newline</p></li></ol>'
end
it 'should not parse' do
str = 'line
1. li2'
Minidown.render(str).should == "<p>line</p><ol><li>li2</li></ol>"
end
it 'two line' do
str = '1. li1
newline
2. li2
newline'
Minidown.render(str).should == '<ol><li><p>li1<br>newline</p></li><li><p>li2<br>newline</p></li></ol>'
end
it 'can work with indent' do
str =<<HERE
1. here a line
noindent
HERE
Minidown.render(str).should == "<ol><li>here a line\nnoindent</li></ol>"
str =<<HERE
1. here a line
noindent
HERE
Minidown.render(str).should == "<ol><li><p>here a line</p>\n<p>noindent</p></li></ol>"
end
it 'can work with block' do
str =<<HERE
1. A list item with a blockquote:
> This is a blockquote
> inside a list item.
HERE
Minidown.render(str).should == "<ol><li>A list item with a blockquote:\n<blockquote><p>This is a blockquote</p><p>inside a list item.</p></blockquote></li></ol>"
end
it 'can not work with block without indent' do
str =<<HERE
1. A list item with a blockquote:
> This is a blockquote
> inside a list item.
HERE
Minidown.render(str).should == "<ol><li>A list item with a blockquote:</li></ol><blockquote><p>This is a blockquote</p><p>inside a list item.</p></blockquote>"
end
it 'newline' do
str =<<HERE
1. A list
Newline
HERE
Minidown.render(str).should == "<ol><li>A list</li></ol><p>Newline</p>"
end
it 'should parse correct' do
str = '1. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,
viverra nec, fringilla in, laoreet vitae, risus.
2. Donec sit amet nisl. Aliquam semper ipsum sit amet velit.
Suspendisse id sem consectetuer libero luctus adipiscing.
---
Hi.'
Minidown.render(str).should == "<ol><li><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>\n<p>Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,</p>\n<p>viverra nec, fringilla in, laoreet vitae, risus.</p></li><li><p>Donec sit amet nisl. Aliquam semper ipsum sit amet velit.</p>\n<p>Suspendisse id sem consectetuer libero luctus adipiscing.</p></li></ol><hr><p>Hi.</p>"
end
it 'list with indent' do
str ='1. first
start with
#and indent'
Minidown.render(str).should == "<ol><li>first\nstart with</li></ol><h1>and indent</h1>"
end
it 'nested should parse correct' do
str = '1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
7. 7'
Minidown.render(str).should == '<ol><li>1
<ol><li>2 </li><li>3</li></ol></li><li>4
<ol><li>5</li><li>6</li><li>7</li></ol></li></ol>'
end
end
describe 'other case' do
it 'should parse nest ul' do
str = '+ ul 1
+ ul 2
+ ul 3
+ ul 4
+ ul 5
+ ul 6'
Minidown.render(str).should == '<ul><li>ul 1</li><li>ul 2
<ul><li>ul 3</li><li>ul 4
<ul><li>ul 5</li></ul></li><li>ul 6</li></ul></li></ul>'
end
it 'should parse nest ol' do
str = '1. ol 1
2. ol 2
1. ol 3
123. ol 4
2. ol 5
3. ol 6'
Minidown.render(str).should == '<ol><li>ol 1</li><li>ol 2
<ol><li>ol 3</li><li>ol 4
<ol><li>ol 5</li></ol></li><li>ol 6</li></ol></li></ol>'
end
it 'should parse correct' do
str = '+ ul 1
+ ul 2
+ ul 3
+ ul 4
+ ul 5
+ ul 6
1. ul a
1. ul b
1. ul c
1. ul d'
Minidown.render(str).should == '<ul><li>ul 1</li><li>ul 2
<ul><li>ul 3</li><li>ul 4
<ul><li>ul 5</li></ul></li><li>ul 6</li></ul></li></ul><ol><li>ul a</li><li>ul b</li><li>ul c</li><li>ul d</li></ol>'
end
it 'mixed list should parsed correct' do
str = '* ul1
1. ol
2. ol
3. ol
* ul2
* ul3
1. ol
2. ol
3. ol
4. ol
5. ol
+ ul4
+ ul5
1. ol
2. ol
3. ol'
Minidown.render(str).should == '<ul><li><p>ul1<br><ol><li>ol</li><li>ol</li><li>ol</li></ol></p></li><li><p>ul2</p></li><li><p>ul3<br><ol><li>ol</li><li>ol</li><li>ol</li><li>ol</li><li>ol</li></ol></p></li><li><p>ul4</p></li><li>ul5
<ol><li>ol</li><li>ol</li><li>ol</li></ol></li></ul>'
end
it 'list within block' do
str = '> block with list
- list within block
- list within block'
Minidown.render(str).should == '<blockquote><p>block with list</p><ul><li>list within block</li><li>list within block</li></ul></blockquote>'
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/spec/blank_line_spec.rb | spec/blank_line_spec.rb | require 'spec_helper'
describe Minidown do
describe 'blank line' do
it 'should parse as nothing' do
['', "\n", "\n\n", "\n\n\n\n"].each do |str|
Minidown.render(str).should == ''
end
end
it 'should be ignore when blank is the first line' do
str = "\na"
Minidown.render(str).should == "<p>a</p>"
str = "\n\n h"
Minidown.render(str).should == "<p> h</p>"
["\n \n", "\n \n\n\n"].each do |str|
Minidown.render(str).should == "#{str.split(Minidown::Utils::Regexp[:lines]).last}".strip
end
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/spec/table_spec.rb | spec/table_spec.rb | require 'spec_helper'
describe Minidown do
describe 'table' do
it 'should parse correct' do
str =<<HERE
First Header | Second Header
------------- | -------------
Content Cell | Content Cell
Content Cell | Content Cell
HERE
Minidown.render(str).should == '<table><thead><tr><th>First Header</th><th>Second Header</th></tr></thead><tbody><tr><td>Content Cell</td><td>Content Cell</td></tr><tr><td>Content Cell</td><td>Content Cell</td></tr></tbody></table>'
end
it 'should parse correct with pipe end' do
str =<<HERE
| First Header | Second Header |
| ------------- | ------------- |
| Content Cell | Content Cell |
| Content Cell | Content Cell |
HERE
Minidown.render(str).should == '<table><thead><tr><th>First Header</th><th>Second Header</th></tr></thead><tbody><tr><td>Content Cell</td><td>Content Cell</td></tr><tr><td>Content Cell</td><td>Content Cell</td></tr></tbody></table>'
end
it 'should allow inline markdown' do
str = <<HERE
| Name | Description |
| ------------- | ----------- |
| Help | ~~Display the~~ help window.|
| Close | _Closes_ a window |
HERE
Minidown.render(str).should == '<table><thead><tr><th>Name</th><th>Description</th></tr></thead><tbody><tr><td>Help</td><td><del>Display the</del> help window.</td></tr><tr><td>Close</td><td><em>Closes</em> a window</td></tr></tbody></table>'
end
it 'should allow define align' do
str = <<HERE
| Left-Aligned | Center Aligned | Right Aligned |
| :------------ |:---------------:| -----:|
| col 3 is | some wordy text | $1600 |
| col 2 is | centered | $12 |
| zebra stripes | are neat | $1 |
HERE
Minidown.render(str).should == '<table><thead><tr><th align="left">Left-Aligned</th><th align="center">Center Aligned</th><th align="right">Right Aligned</th></tr></thead><tbody><tr><td align="left">col 3 is</td><td align="center">some wordy text</td><td align="right">$1600</td></tr><tr><td align="left">col 2 is</td><td align="center">centered</td><td align="right">$12</td></tr><tr><td align="left">zebra stripes</td><td align="center">are neat</td><td align="right">$1</td></tr></tbody></table>'
end
it 'should allow escape' do
str =<<HERE
\\| First Header | Second Header |
| ------------- | ------------- |
| Content Cell | Content Cell |
| Content Cell | Content Cell |
HERE
Minidown.render(str).should == '<p>| First Header | Second Header |<br>| ------------- | ------------- |<br>| Content Cell | Content Cell |<br>| Content Cell | Content Cell |</p>'
end
it 'should not parse as table' do
str = "|not|table|"
Minidown.render(str).should == '<p>|not|table|</p>'
str = "not|table"
Minidown.render(str).should == '<p>not|table</p>'
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/spec/start_with_shape_spec.rb | spec/start_with_shape_spec.rb | require 'spec_helper'
describe Minidown do
describe '###### title' do
it 'should parse "#" as text' do
Minidown.render('#').should == '<p>#</p>'
end
it 'should parse "#####"' do
(2..7).map{|n| '#' * n}.each do |str|
tag = "h#{str.size - 1}"
Minidown.render(str).should == "<#{tag}>#</#{tag}>"
end
end
it 'should ignore blank' do
str =<<HERE
#### h4 ######
HERE
Minidown.render(str).should == "<h4>h4</h4>"
end
end
describe 'should not parse escaped' do
it 'start with escape' do
%w{\####### \###### \#### \### \## \#}.each do |str|
Minidown.render(str).should == "<p>#{str[1..-1]}</p>"
end
end
it 'some other case' do
str = '#\##'
Minidown.render(str).should == "<h1>\\</h1>"
str = '##\##\\'
Minidown.render(str).should == "<h2>##\\</h2>"
str = '# \# #'
Minidown.render(str).should == "<h1>#</h1>"
str = '#\#'
Minidown.render(str).should == "<h1>\\</h1>"
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/spec/paragraph_spec.rb | spec/paragraph_spec.rb | require 'spec_helper'
describe Minidown do
describe 'paragraph' do
it 'should correct' do
str = 'line1
line2
new paragraph
some space
same paragraph
new p'
Minidown.render(str).should == '<p>line1<br>line2</p><p>new paragraph<br> some space<br>same paragraph</p><p>new p</p>'
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/spec/start_with_gt_spec.rb | spec/start_with_gt_spec.rb | require 'spec_helper'
describe Minidown do
describe 'start with <' do
it 'should parse as blockquote' do
[">block", "> block", "> block", "> block"].each do |str|
Minidown.render(str).should == "<blockquote><p>#{str[1..-1].strip}</p></blockquote>"
end
end
it 'should parse correct' do
str =<<HERE
> here block
> here too
HERE
Minidown.render(str).should == '<blockquote><p>here block</p><p>here too</p></blockquote>'
end
it 'should parse region' do
str =<<HERE
> here block
here too
yes
all is block
bbbbbbbbb
newline
HERE
Minidown.render(str).should == '<blockquote><p>here block<br>here too<br> yes<br> all is block<br>bbbbbbbbb</p></blockquote><p>newline</p>'
end
it 'should parse nest' do
str =<<HERE
> here block
here too
> yes
all is block
>> two level
two too
> still level two
still in block
newline
HERE
Minidown.render(str).should == '<blockquote><p>here block<br> here too<br>yes<br> all is block</p><blockquote><p>two level<br>two too<br>still level two<br>still in block</p></blockquote></blockquote><p>newline</p>'
end
end
describe 'can use other syntax' do
it 'use with #' do
str = '> ## here h2'
Minidown.render(str).should == '<blockquote><h2>here h2</h2></blockquote>'
end
it 'should render mutil <p>' do
str = '>line1
line2
###h3 ###
another p'
Minidown.render(str).should == '<blockquote><p>line1<br>line2</p><h3>h3</h3><p>another p</p></blockquote>'
end
end
describe 'should allow escape' do
it 'should render correct' do
str = '>\>block'
Minidown.render(str).should == '<blockquote><p>>block</p></blockquote>'
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/spec/text_element_spec.rb | spec/text_element_spec.rb | require 'spec_helper'
describe Minidown do
describe 'text element' do
it 'escape' do
str = "<>"
Minidown.render(str).should == "<p><></p>"
end
it 'escape special symbol' do
str = '\\\\
\\`
\\*
\\_
\\{
\\}
\\[
\\]
\\(
\\)
\\#
\\+
\\-
\\.
\\!'
Minidown.render(str).should == '<p>\
`
*
_
{
}
[
]
(
)
#
+
-
.
!</p>'.split.join('<br>')
end
it 'escape escape symbol' do
str = %q{\\\\`
\\\\*
\\\\_
\\\\{
\\\\}
\\\\[
\\\\]
\\\\(
\\\\)
\\\\#
\\\\+
\\\\-
\\\\.
\\\\!}
Minidown.render(str).should == %q{<p>\\`
\\*
\\_
\\{
\\}
\\[
\\]
\\(
\\)
\\#
\\+
\\-
\\.
\\!</p>}.split.join('<br>')
end
it 'html tag' do
str = "<a href=\"http://github.com\">github</a>"
Minidown.render(str).should == "<p>#{str}</p>"
end
context 'link' do
it 'should parse correct' do
str = %Q{This is [an example](http://example.com/ "Title") inline link.
[This link](http://example.net/) has no title attribute.}
Minidown.render(str).should == %Q{<p>This is <a href="http://example.com/" title="Title">an example</a> inline link.</p><p><a href="http://example.net/">This link</a> has no title attribute.</p>}
str = '[link a](https://a.example.com) and [link b](https://b.example.com)'
Minidown.render(str).should == "<p><a href=\"https://a.example.com\">link a</a> and <a href=\"https://b.example.com\">link b</a></p>"
end
it 'should allow related path' do
str = "See my [About](/about/) page for details."
Minidown.render(str).should == %Q{<p>See my <a href=\"/about/\">About</a> page for details.</p>}
end
it 'should allow reference' do
str =<<HERE
I get 10 times more traffic from [Google] [1] than from
[Yahoo] [2] or [MSN] [3].
[1]: http://google.com/ "Google"
[2]: http://search.yahoo.com/ "Yahoo Search"
[3]: http://search.msn.com/ "MSN Search"
HERE
str2 =<<HERE
I get 10 times more traffic from [Google][] than from
[Yahoo][] or [MSN][].
[google]: http://google.com/ "Google"
[yahoo]: http://search.yahoo.com/ "Yahoo Search"
[msn]: http://search.msn.com/ "MSN Search"
HERE
[str, str2].each do |s|
Minidown.render(s).should == '<p>I get 10 times more traffic from <a href="http://google.com/" title="Google">Google</a> than from<br><a href="http://search.yahoo.com/" title="Yahoo Search">Yahoo</a> or <a href="http://search.msn.com/" title="MSN Search">MSN</a>.</p>'
end
end
it 'can ignore title' do
str =<<HERE
I get 10 times more traffic from [Google][] than from
[Yahoo][] or [MSN][].
[google]: http://google.com/ "Google"
[yahoo]: http://search.yahoo.com/
[msn]: http://search.msn.com/ "MSN Search"
HERE
Minidown.render(str).should == '<p>I get 10 times more traffic from <a href="http://google.com/" title="Google">Google</a> than from<br><a href="http://search.yahoo.com/">Yahoo</a> or <a href="http://search.msn.com/" title="MSN Search">MSN</a>.</p>'
end
end
context 'auto link' do
it 'should parse link' do
str = "https://github.com/jjyr/minidown"
Minidown.render(str).should == "<p><a href=\"#{str}\">#{str}</a></p>"
end
it 'can parse multi link' do
str = "https://github.com/jjyr/minidown https://github.com"
Minidown.render(str).should == "<p><a href=\"https://github.com/jjyr/minidown\">https://github.com/jjyr/minidown</a> <a href=\"https://github.com\">https://github.com</a></p>"
end
it 'should not parse link in tag' do
str = "<a href=\"https://github.com/jjyr/minidown\">minidown</a>"
Minidown.render(str).should == "<p>#{str}</p>"
end
it 'should not parse link without scheme' do
str = "github.com/jjyr/minidown"
Minidown.render(str).should == "<p>#{str}</p>"
end
it 'should parse email address' do
str = "jjyruby@gmail.com"
Minidown.render(str).should == "<p><a href=\"mailto:#{str}\">#{str}</a></p>"
end
it 'can parse multi email' do
str = "jjyruby@gmail.com jjyruby@gmail.com"
Minidown.render(str).should == "<p><a href=\"mailto:jjyruby@gmail.com\">jjyruby@gmail.com</a> <a href=\"mailto:jjyruby@gmail.com\">jjyruby@gmail.com</a></p>"
end
it 'should play with normal text' do
str = "Hi, jjyruby@gmail.com is my email."
Minidown.render(str).should == "<p>Hi, <a href=\"mailto:jjyruby@gmail.com\">jjyruby@gmail.com</a> is my email.</p>"
str = "Hi, <jjyruby@gmail.com> is my email."
Minidown.render(str).should == "<p>Hi, <a href=\"mailto:jjyruby@gmail.com\">jjyruby@gmail.com</a> is my email.</p>"
end
it 'should not parse email in tag' do
str = "<a href=\"mailto:jjyruby@gmail.com\">jjyr</a>"
Minidown.render(str).should == "<p>#{str}</p>"
end
it 'should parse with <>' do
str = "<https://github.com/jjyr/minidown>"
Minidown.render(str).should == "<p><a href=\"#{str[1..-2]}\">#{str[1..-2]}</a></p>"
end
it 'should not parse with <> if url invalid' do
str = "<github.com/jjyr/minidown>"
Minidown.render(str).should == "<p>#{str}</p>"
end
it 'should parse email' do
str = "<jjyruby@gmail.com>"
Minidown.render(str).should == "<p><a href=\"mailto:jjyruby@gmail.com\">jjyruby@gmail.com</a></p>"
end
end
context '~~del~~' do
it 'should parse correct' do
['del', 'd', 'i am del'].each do |w|
str = "~~#{w}~~"
Minidown.render(str).should == "<p><del>#{w}</del></p>"
end
end
it 'should allow mutil in oneline' do
str = '~~i am del~~ and ~~i am another del~~'
Minidown.render(str).should == '<p><del>i am del</del> and <del>i am another del</del></p>'
end
it 'should not allow space' do
str = '~~ del ~~'
Minidown.render(str).should == '<p>~~ del ~~</p>'
end
it 'should allow escape' do
str = "\\~~del~~"
Minidown.render(str).should == '<p>~~del~~</p>'
end
end
context '*_ em & strong' do
it 'parse as em' do
['*', '_'].each do |c|
Minidown.render("#{c}em#{c}").should == '<p><em>em</em></p>'
end
end
it 'should work well with text' do
Minidown.render("a _close_ a window").should == '<p>a <em>close</em> a window</p>'
Minidown.render("a *close* a window").should == '<p>a <em>close</em> a window</p>'
end
it 'can not mass' do
Minidown.render("*em_").should == '<p>*em_</p>'
end
it 'parse as strong' do
['**', '__'].each do |c|
Minidown.render("#{c}strong#{c}").should == '<p><strong>strong</strong></p>'
end
end
it '* can work in string' do
Minidown.render("this*em*string").should == '<p>this<em>em</em>string</p>'
end
it '_ can not work in string' do
Minidown.render("_here_method").should == '<p>_here_method</p>'
Minidown.render("_here_method_").should == '<p><em>here_method</em></p>'
end
it 'should parse correct' do
Minidown.render("_ *what*_").should == '<p>_ <em>what</em>_</p>'
end
it 'should allow escape' do
Minidown.render("\\*\\_\\*").should == '<p>*_*</p>'
end
it 'should work well' do
str = "*View the [source of this content](http://github.github.com/github-flavored-markdown/sample_content.html).*"
Minidown.render(str).should == "<p><em>View the <a href=\"http://github.github.com/github-flavored-markdown/sample_content.html\">source of this content</a>.</em></p>"
end
end
context 'inline code' do
it 'should parse correct' do
str = "Use the `printf()` function."
Minidown.render(str).should == "<p>Use the <code>printf()</code> function.</p>"
end
it 'should can use multi `' do
str = "``There is a literal backtick (`) here.``"
Minidown.render(str).should == "<p><code>There is a literal backtick (`) here.</code></p>"
str = 'A single backtick in a code span: `` ` ``
A backtick-delimited string in a code span: `` `foo` ``'
Minidown.render(str).should == '<p>A single backtick in a code span: <code>`</code></p><p>A backtick-delimited string in a code span: <code>`foo`</code></p>'
end
it 'can parse multi inline code' do
str = "`hello` `world`"
Minidown.render(str).should == "<p><code>hello</code> <code>world</code></p>"
end
it 'should auto escape' do
str = "Please don't use any `<blink>` tags."
Minidown.render(str).should == "<p>Please don't use any <code><blink></code> tags.</p>"
end
it 'should not auto convert' do
str = "`jjyruby@gmail.com`"
Minidown.render(str).should == '<p><code>jjyruby@gmail.com</code></p>'
end
end
context 'image syntax' do
it 'should parse correct' do
str = ''
Minidown.render(str).should == "<p><img src=\"/path/to/img.jpg\" alt=\"Alt text\"></img></p>"
end
it 'should have title' do
str = ""
Minidown.render(str).should == "<p><img src=\"/path/to/img.jpg\" alt=\"Alt text\" title=\"title\"></img></p>"
end
it 'should allow reference' do
str =<<HERE
![Image 1][img1]
![Image 2][img2]
![Image 3][img3]
[img1]: url/to/image1 "Image 1"
[img2]: url/to/image2
[img3]: url/to/image3 "Image 3"
HERE
Minidown.render(str).should == "<p><img src=\"url/to/image1\" alt=\"Image 1\" title=\"Image 1\"></img><br><img src=\"url/to/image2\" alt=\"Image 2\"></img><br><img src=\"url/to/image3\" alt=\"Image 3\" title=\"Image 3\"></img></p>"
end
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/spec/dividing_line_spec.rb | spec/dividing_line_spec.rb | require 'spec_helper'
describe Minidown do
describe 'dividing line' do
it 'parsed correct' do
str = '***'
Minidown.render(str).should == '<hr>'
str = '---'
Minidown.render(str).should == '<hr>'
str = ' *** '
Minidown.render(str).should == '<hr>'
str = ' * * * '
Minidown.render(str).should == '<hr>'
str = ' -- - '
Minidown.render(str).should == '<hr>'
str = '----'
Minidown.render(str).should == '<hr>'
end
it 'should not parse if any other character' do
str = 'f---'
Minidown.render(str).should == '<p>f---</p>'
str = '* * *z'
Minidown.render(str).should == '<ul><li><em> </em>z</li></ul>'
end
it 'should allow escape' do
str = "\\----"
Minidown.render(str).should == '<p>----</p>'
str = "\\* * *"
Minidown.render(str).should == '<p>* <em> </em></p>'
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/spec/task_list_spec.rb | spec/task_list_spec.rb | require 'spec_helper'
describe Minidown do
describe 'task list' do
it 'should parse correct' do
str =<<HERE
- [ ] a task list item
- [ ] list syntax required
- [ ] normal **formatting**,
@mentions, #1234 refs
- [ ] incomplete
- [x] completed
HERE
Minidown.render(str).should == '<ul class="task-list"><li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled=""> a task list item</li><li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled=""> list syntax required</li><li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled=""><p> normal <strong>formatting</strong>,</p>
<p>@mentions, #1234 refs</p></li><li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled=""> incomplete</li><li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" checked="" disabled=""> completed</li></ul>'
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/spec/spec_helper.rb | spec/spec_helper.rb | require 'minidown'
require 'pry'
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/spec/minidown_spec.rb | spec/minidown_spec.rb | require 'spec_helper'
describe Minidown do
it 'Minidown.render should == Parser#render' do
Minidown.render("hello").should == Minidown::Parser.new.render("hello")
end
it 'allow options' do
options = {}
Minidown.render("hello", options).should == Minidown::Parser.new(options).render("hello")
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown.rb | lib/minidown.rb | require "minidown/version"
require 'minidown/parser'
require 'minidown/utils'
require 'minidown/elements'
require 'minidown/document'
module Minidown
class << self
def render str, options = {}
Parser.new(options).render str
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/element.rb | lib/minidown/element.rb | require 'minidown/html_helper'
module Minidown
class Element
attr_accessor :content, :doc, :nodes, :children
include HtmlHelper
def raw_content
@content
end
def raw_content= str
@content = str
end
def unparsed_lines
doc.lines
end
def initialize doc, content
@doc = doc
@nodes = doc.nodes
@content = content
@children = []
end
def parse
raise NotImplementedError, 'method parse not implemented'
end
def to_html
raise NotImplementedError, 'method to_html not implemented'
end
def blank?
false
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/version.rb | lib/minidown/version.rb | module Minidown
VERSION = "2.1.1"
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/elements.rb | lib/minidown/elements.rb | require 'minidown/element'
require 'minidown/elements/raw_html_element'
require 'minidown/elements/html_element'
require 'minidown/elements/line_element'
require 'minidown/elements/text_element'
require 'minidown/elements/block_element'
require 'minidown/elements/table_element'
require 'minidown/elements/paragraph_element'
require 'minidown/elements/list_element'
require 'minidown/elements/list_group_element'
require 'minidown/elements/unorder_list_element'
require 'minidown/elements/order_list_element'
require 'minidown/elements/code_block_element'
require 'minidown/elements/dividing_line_element'
require 'minidown/elements/indent_code_element'
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/utils.rb | lib/minidown/utils.rb | module Minidown
module Utils
Regexp = {
lines: /\n|\r\n/,
blank_line: /\A\s*\z/,
raw_html: /\A\s*(\<(?=[^\<\>]).+(?<=[^\<\>])\>)*\s*\z/,
h1_or_h2: /\A([=-]{3,})(.*)/,
start_with_shape: /\A(\#{1,6})\s*(.+?)\s*#*\z/,
start_with_quote: /\A\>\s*(.+)/,
unorder_list: /\A(\s*)[*\-+]\s+(.+)/,
order_list: /\A(\s*)\d+\.\s+(.+)/,
code_block: /\A\s*[`~]{3,}\s*(\S*)/,
table: /\A\|?([^\|]+(?:\|[^\|]*)*)\|?\s*\z/,
dividing_line: /\A(\s*[*-]\s*){3,}\z/,
indent_code: /\A\s{4}(.+)/,
pipe_symbol: /\|/
}.freeze
class << self
def escape_html str
sanitized_str = str.dup
sanitized_str.gsub! "<".freeze, "<".freeze
sanitized_str.gsub! ">".freeze, ">".freeze
sanitized_str
end
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/parser.rb | lib/minidown/parser.rb | module Minidown
class Parser
def initialize options = {}
@options = options.freeze
end
def render str
parse(str).to_html
end
protected
def parse str
lines = str.split Utils::Regexp[:lines]
doc = Document.new lines, @options
doc.parse
doc
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/document.rb | lib/minidown/document.rb | module Minidown
class Document
attr_accessor :lines, :nodes, :links_ref, :options
attr_reader :within_block
RefRegexp = {
link_ref_define: /\A\s*\[(.+)\]\:\s+(\S+)\s*(.*)/,
link_title: /((?<=\").+?(?=\"))/
}
TagRegexp ={
h1h6: /\Ah[1-6]\z/
}
def initialize lines, options = {}
@options = options
@lines = lines
@nodes = []
@within_block = false
@links_ref = {}
end
def parse
parse_references
while line = @lines.shift
parse_line line
end
end
def to_html
@html ||= (doc = ''
@nodes.each{|e| doc << e.to_html}
doc)
end
# define short methods
{text: TextElement, html_tag: HtmlElement, newline: LineElement, block: BlockElement, paragraph: ParagraphElement, ul: UnorderListElement, ol: OrderListElement, code_block: CodeBlockElement, dividing_line: DividingLineElement, indent_code: IndentCodeElement}.each do |name, klass|
define_method name do |*args|
klass.new(self, *args).parse
end
end
def parse_references
while line = @lines.pop
line.gsub! RefRegexp[:link_ref_define] do
id, url = $1, $2
$3 =~ RefRegexp[:link_title]
title = $1
links_ref[id.downcase] = {url: url, title: title}
''
end
unless line.empty?
@lines << line
break
end
end
end
def parse_line line
regexp = Minidown::Utils::Regexp
case
when regexp[:blank_line] =~ line
# blankline
newline line
when !pre_blank? && (result = regexp[:h1_or_h2] =~ line; next_line = $2; result) && ParagraphElement === nodes.last
# ======== or -------
break_if_list line do
lines.unshift next_line if next_line && !next_line.empty?
html_tag nodes.pop, (line[0] == '='.freeze ? 'h1'.freeze : 'h2'.freeze)
end
when regexp[:start_with_shape] =~ line
# ####h4
break_if_list line do
text $2
html_tag nodes.pop, "h#{$1.size}"
end
when regexp[:start_with_quote] =~ line
# > blockquote
inblock{block $1}
when regexp[:dividing_line] =~ line
# * * * - - -
break_if_list line do
dividing_line line
end
when regexp[:unorder_list] =~ line
# * + -
indent, str = $1.size, $2
inblock{ul str, indent}
when regexp[:order_list] =~ line
# 1. order
indent, str = $1.size, $2
inblock{ol str, indent}
when regexp[:code_block] =~ line
# ``` or ~~~
inblock{code_block $1}
when !@within_block && pre_blank? && regexp[:indent_code] =~ line
# code
indent_code $1
when regexp[:pipe_symbol] =~ line && regexp[:table] =~ line
# column1 | column2 | ...
table = TableElement.new self, line, $1
raw_column_spec = @lines.shift
if table.check_column_spec raw_column_spec
inblock{table.parse}
else
@lines.unshift raw_column_spec if raw_column_spec
paragraph line
end
else
# paragraph
paragraph line
end
end
private
def pre_blank?
node = @nodes.last
node.nil? || node.blank?
end
def inblock
if @within_block
yield
else
@within_block = true
yield
@within_block = false
end
end
def break_if_list line
node = nodes.last
if @within_block && (UnorderListElement === node || OrderListElement === node)
@lines.unshift line
nodes << nil
else
yield
end
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/html_helper.rb | lib/minidown/html_helper.rb | module Minidown
module HtmlHelper
def build_tag name, attr = nil
content = ''
yield content if block_given?
if attr
attr = attr.map{|k, v| "#{k}=\"#{v}\""}.join ' '.freeze
"<#{name} #{attr}>#{content}</#{name}>"
else
"<#{name}>#{content}</#{name}>"
end
end
def br_tag
'<br>'
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/elements/html_element.rb | lib/minidown/elements/html_element.rb | module Minidown
class HtmlElement < Element
attr_reader :name
def initialize doc, content, name
super doc, content
@name = name
end
def parse
nodes << self
end
def to_html
build_tag @name do |tag|
# self.content is some Element
self.content = content.text if ParagraphElement === self.content
tag << self.content.to_html
end
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/elements/dividing_line_element.rb | lib/minidown/elements/dividing_line_element.rb | module Minidown
class DividingLineElement < Element
def parse
nodes << self
end
def to_html
'<hr>'
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/elements/list_group_element.rb | lib/minidown/elements/list_group_element.rb | module Minidown
class ListGroupElement < Element
IndentRegexp = /\A\s{4,}(.+)/
StartWithBlankRegexp = /\A\s+(.+)/
attr_accessor :lists, :indent_level
def parse
nodes << self
while line = unparsed_lines.shift
#handle nested list
if (line =~ UnorderListElement::NestRegexp && list_class = UnorderListElement) || (line =~ OrderListElement::NestRegexp && list_class = OrderListElement)
li, str = $1.size, $2
if li > @indent_level
list_class.new(doc, str, li).parse
@lists.last.contents << nodes.pop
next
elsif li == @indent_level
list_class.new(doc, str, li).parse
child = nodes.pop
if LineElement === nodes.last
@lists.last.p_tag_content = child.lists.first.p_tag_content = true
end
if child.is_a?(ListGroupElement)
nodes.push *child.children
@lists.push *child.lists
else
@lists.last.contents << child
end
next
else
unparsed_lines.unshift line
break
end
end
doc.parse_line line
child = nodes.pop
case child
when self.class
if LineElement === nodes.last
@lists.last.p_tag_content = child.lists.first.p_tag_content = true
end
nodes.push *child.children
@lists.push *child.lists
break
when ParagraphElement
contents = @lists.last.contents
if line =~ StartWithBlankRegexp
doc.parse_line $1
node = nodes.pop
if TextElement === node || ParagraphElement === node
if TextElement === contents.last
contents.push(contents.pop.paragraph)
end
node = node.paragraph if TextElement === node
end
else
if @blank
unparsed_lines.unshift line
break
end
node = child.text
end
contents << node if node
when LineElement
next_line = unparsed_lines.first
if next_line.nil? || next_line.empty? || StartWithBlankRegexp === next_line || self.class.const_get(:ListRegexp) === next_line
child.display = false
nodes << child
else
unparsed_lines.unshift line
break
end
else
@put_back << child if child
break
end
@blank = (LineElement === child)
end
children_range = (nodes.index(self) + 1)..-1
children.push *nodes[children_range]
nodes[children_range] = []
nodes.push *@put_back
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/elements/table_element.rb | lib/minidown/elements/table_element.rb | module Minidown
class TableElement < Element
AlignSpecRegexp = /\A\|?\s*([\-:]\-+[\-:]\s*(?:\|\s*[\-:]\-+[\-:]\s*)*)\|?\s*\z/
def initialize doc, content, raw_head
super doc, content
@raw_head = raw_head
@heads = @raw_head.split('|'.freeze).map! &:strip
@column_count = @heads.count
end
def check_column_spec raw_column_spec
if @valid.nil?
@valid = Utils::Regexp[:pipe_symbol] =~ raw_column_spec && AlignSpecRegexp =~ raw_column_spec && (column_spec_str = $1) && (@column_specs = column_spec_str.split('|'.freeze).map! &:strip) && @column_specs.count == @column_count
else
@valid
end
end
def parse
if @valid
nodes << self
@bodys = []
@column_specs.map! do |column_spec|
if column_spec[0] == column_spec[-1]
column_spec[0] == ':'.freeze ? 'center'.freeze : nil
else
column_spec[0] == ':'.freeze ? 'left'.freeze : 'right'.freeze
end
end
while line = unparsed_lines.shift
if Utils::Regexp[:table] =~ line && (cells = $1.split('|'.freeze).map! &:strip) && @column_count == cells.count
@bodys << cells
else
unparsed_lines.unshift line
break
end
end
else
raise 'table column specs not valid'
end
end
def to_html
attrs = @column_specs.map do |align|
{align: align}.freeze if align
end
build_tag 'table'.freeze do |table|
thead = build_tag 'thead'.freeze do |thead|
tr = build_tag 'tr'.freeze do |tr|
@heads.each_with_index do |cell, i|
th = build_tag 'th'.freeze, attrs[i] do |th|
th << cell
end
tr << th
end
end
thead << tr
end
table << thead
tbody = build_tag 'tbody'.freeze do |tbody|
@bodys.each do |row|
tr = build_tag 'tr'.freeze do |tr|
row.each_with_index do |cell, i|
td = build_tag 'td'.freeze, attrs[i] do |td|
td << TextElement.new(doc, cell).to_html
end
tr << td
end
end
tbody << tr
end
end
table << tbody
end
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/elements/indent_code_element.rb | lib/minidown/elements/indent_code_element.rb | module Minidown
class IndentCodeElement < Element
def initialize *_
super
@lines = [content]
end
def parse
while line = unparsed_lines.shift
case line
when Utils::Regexp[:indent_code]
@lines << $1
else
unparsed_lines.unshift line
break
end
end
unparsed_lines.unshift '```'
unparsed_lines.unshift *@lines
unparsed_lines.unshift '```'
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
jjyr/minidown | https://github.com/jjyr/minidown/blob/675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a/lib/minidown/elements/raw_html_element.rb | lib/minidown/elements/raw_html_element.rb | module Minidown
class RawHtmlElement < Element
def parse
nodes << self
end
def to_html
content
end
end
end
| ruby | MIT | 675e535bf6e559c4a2ae4174fbf1c7a160f8ed5a | 2026-01-04T17:48:47.033200Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.