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 |
|---|---|---|---|---|---|---|---|---|
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi.rb | lib/nandi.rb | # frozen_string_literal: true
require "nandi/config"
require "nandi/renderers"
require "nandi/compiled_migration"
require "active_support/core_ext/string/inflections"
module Nandi
class Error < StandardError; end
class << self
def compile(files:, db_name: nil)
compiled = files.
map { |f| CompiledMigration.build(file_name: f, db_name: db_name) }
yield compiled
end
def configure
yield config
config.validate!
end
def validator
Nandi::Validator
end
def config
@config ||= Config.new
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/generators/nandi/index/index_generator.rb | lib/generators/nandi/index/index_generator.rb | # frozen_string_literal: true
require "rails/generators"
require "nandi/formatting"
require "nandi/multi_db_generator"
module Nandi
class IndexGenerator < Rails::Generators::Base
include Nandi::Formatting
include Nandi::MultiDbGenerator
argument :tables, type: :string
argument :columns, type: :string
class_option :index_name, type: :string
source_root File.expand_path("templates", __dir__)
attr_reader :add_index_name, :index_name, :table, :columns
def add_index
tables_list = tables.split(",")
@columns = columns.split(",")
tables_list.each_with_index do |table, idx|
next if table.empty?
@table = table.to_sym
@add_index_name = "add_index_on_#{columns.join('_')}_to_#{table}"
@index_name = (
override_index_name || "idx_#{table}_on_#{columns.join('_')}"
).to_sym
template(
"add_index.rb",
"#{base_path}/#{timestamp(idx)}_#{add_index_name}.rb",
)
end
end
private
def timestamp(offset = 0)
(Time.now.utc + offset).strftime("%Y%m%d%H%M%S")
end
def override_index_name
options["index_name"]&.to_sym
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/generators/nandi/index/templates/add_index.rb | lib/generators/nandi/index/templates/add_index.rb | # frozen_string_literal: true
class <%= add_index_name.camelize %> < Nandi::Migration
def up
add_index <%= format_value(table) %>,
%i<%= format_value(columns).tr('"', '') %>,
name: <%= format_value(index_name) %>
end
def down
remove_index <%= format_value(table) %>,
%i<%= format_value(columns).tr('"', '') %>
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/generators/nandi/compile/compile_generator.rb | lib/generators/nandi/compile/compile_generator.rb | # frozen_string_literal: true
require "rails/generators"
require "nandi"
require "nandi/migration"
require "nandi/file_matcher"
require "nandi/lockfile"
module Nandi
class CompileGenerator < Rails::Generators::Base
source_root File.expand_path("templates", __dir__)
class_option :database,
type: :string,
default: nil,
desc: "Database to compile. " \
"If not specified, compiles for all databases"
class_option :files,
type: :string,
default: Nandi.config.compile_files,
desc: <<-DESC
Files to compile. May be one of the following:
-- 'all' compiles all files
-- 'git-diff' only changed
-- a full or partial version timestamp, eg '20190101010101', '20190101'
-- a timestamp range , eg '>=20190101010101'
DESC
def compile_migration_files
databases.each do |db_name|
Nandi.compile(files: files(db_name), db_name: db_name) do |results|
results.each do |result|
Nandi::Lockfile.for(db_name).add(
file_name: result.file_name,
source_digest: result.source_digest,
compiled_digest: result.compiled_digest,
)
unless result.migration_unchanged?
create_file result.output_path, result.body, force: true
end
end
end
Nandi::Lockfile.for(db_name).persist!
end
end
private
def databases
return [options[:database].to_sym] if options[:database]
Nandi.config.databases.names
end
def safe_migrations_dir(db_name)
File.expand_path(Nandi.config.migration_directory(db_name))
end
def files(db_name)
safe_migration_files = Dir.chdir(safe_migrations_dir(db_name)) { Dir["*.rb"] }
FileMatcher.call(files: safe_migration_files, spec: options["files"])
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/generators/nandi/foreign_key/foreign_key_generator.rb | lib/generators/nandi/foreign_key/foreign_key_generator.rb | # frozen_string_literal: true
require "rails/generators"
require "nandi/formatting"
require "nandi/multi_db_generator"
module Nandi
class ForeignKeyGenerator < Rails::Generators::Base
include Nandi::Formatting
include Nandi::MultiDbGenerator
argument :table, type: :string
argument :target, type: :string
class_option :name, type: :string
class_option :column, type: :string
class_option :type, type: :string, default: "bigint"
class_option :no_create_column, type: :boolean
class_option :validation_timeout, type: :numeric, default: 15 * 60 * 1000
source_root File.expand_path("templates", __dir__)
attr_reader :add_reference_name,
:add_foreign_key_name,
:validate_foreign_key_name
def add_reference
return if options["no_create_column"]
self.table = table.to_sym
@add_reference_name = "add_reference_on_#{table}_to_#{target}"
template(
"add_reference.rb",
"#{base_path}/#{timestamp}_#{add_reference_name}.rb",
)
end
def add_foreign_key
self.table = table.to_sym
self.target = target.to_sym
@add_foreign_key_name = "add_foreign_key_on_#{table}_to_#{target}"
template(
"add_foreign_key.rb",
"#{base_path}/#{timestamp(1)}_#{add_foreign_key_name}.rb",
)
end
def validate_foreign_key
self.table = table.to_sym
self.target = target.to_sym
@validate_foreign_key_name = "validate_foreign_key_on_#{table}_to_#{target}"
template(
"validate_foreign_key.rb",
"#{base_path}/#{timestamp(2)}_#{validate_foreign_key_name}.rb",
)
end
private
def type
options["type"].to_sym
end
def reference_name
:"#{target.singularize}_id"
end
def timestamp(offset = 0)
(Time.now.utc + offset).strftime("%Y%m%d%H%M%S")
end
def name
options["name"]&.to_sym || :"#{@table}_#{@target}_fk"
end
def column
options["column"]&.to_sym
end
def any_options?
options["name"] || options["column"]
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/generators/nandi/foreign_key/templates/add_foreign_key.rb | lib/generators/nandi/foreign_key/templates/add_foreign_key.rb | # frozen_string_literal: true
class <%= add_foreign_key_name.camelize %> < Nandi::Migration
def up
add_foreign_key <%= format_value(table) %>, <%= format_value(target) %><% if any_options? %>,
<% if column %>column: <%= format_value(column) %><% end %><% if column && name %>,<% end %>
<% if name %>name: <%= format_value(name) %><% end %> <% end %>
end
def down
drop_constraint <%= format_value(table) %>, <%= format_value(name) %>
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/generators/nandi/foreign_key/templates/validate_foreign_key.rb | lib/generators/nandi/foreign_key/templates/validate_foreign_key.rb | # frozen_string_literal: true
class <%= validate_foreign_key_name.camelize %> < Nandi::Migration
def up
validate_constraint <%= format_value(@table) %>, <%= format_value(name) %>
end
def down; end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/generators/nandi/foreign_key/templates/add_reference.rb | lib/generators/nandi/foreign_key/templates/add_reference.rb | # frozen_string_literal: true
class <%= add_reference_name.camelize %> < Nandi::Migration
def up
add_column <%= format_value(table) %>, <%= format_value(reference_name) %>, <%= format_value(type) %>
end
def down
remove_column <%= format_value(table) %>, <%= format_value(reference_name) %>
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/generators/nandi/migration/migration_generator.rb | lib/generators/nandi/migration/migration_generator.rb | # frozen_string_literal: true
require "rails/generators"
require "nandi/multi_db_generator"
module Nandi
class MigrationGenerator < Rails::Generators::NamedBase
include Nandi::MultiDbGenerator
source_root File.expand_path("templates", __dir__)
def create_migration_file
timestamp = Time.now.utc.strftime("%Y%m%d%H%M%S")
template(
"migration.rb",
"#{base_path}/#{timestamp}_#{file_name.underscore}.rb",
)
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/generators/nandi/migration/templates/migration.rb | lib/generators/nandi/migration/templates/migration.rb | # frozen_string_literal: true
class <%= class_name %> < Nandi::Migration
def up
# Migration instructions go here, eg:
# add_column :widgets, :size, :integer
end
def down
# Reverse migration instructions go here, eg:
# remove_column :widgets, :size
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/generators/nandi/not_null_check/not_null_check_generator.rb | lib/generators/nandi/not_null_check/not_null_check_generator.rb | # frozen_string_literal: true
require "rails/generators"
require "nandi/formatting"
require "nandi/multi_db_generator"
module Nandi
class NotNullCheckGenerator < Rails::Generators::Base
include Nandi::Formatting
include Nandi::MultiDbGenerator
argument :table, type: :string
argument :column, type: :string
class_option :validation_timeout, type: :numeric, default: 15 * 60 * 1000
source_root File.expand_path("templates", __dir__)
attr_reader :add_not_null_check_name, :validate_not_null_check_name
def add_not_null_check
self.table = table.to_sym
self.column = column.to_sym
@add_not_null_check_name = "add_not_null_check_on_#{column}_to_#{table}"
template(
"add_not_null_check.rb",
"#{base_path}/#{timestamp}_#{add_not_null_check_name}.rb",
)
end
def validate_not_null_check
self.table = table.to_sym
self.column = column.to_sym
@validate_not_null_check_name = "validate_not_null_check_on_#{column}_to_#{table}"
template(
"validate_not_null_check.rb",
"#{base_path}/#{timestamp(1)}_#{validate_not_null_check_name}.rb",
)
end
private
def timestamp(offset = 0)
(Time.now.utc + offset).strftime("%Y%m%d%H%M%S")
end
def name
"#{table}_check_#{column}_not_null"
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/generators/nandi/not_null_check/templates/add_not_null_check.rb | lib/generators/nandi/not_null_check/templates/add_not_null_check.rb | # frozen_string_literal: true
class <%= add_not_null_check_name.camelize %> < Nandi::Migration
def up
add_check_constraint <%= format_value(table) %>, <%= format_value(name) %>, "<%= column %> IS NOT NULL"
end
def down
drop_constraint <%= format_value(table) %>, <%= format_value(name) %>
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/generators/nandi/not_null_check/templates/validate_not_null_check.rb | lib/generators/nandi/not_null_check/templates/validate_not_null_check.rb | # frozen_string_literal: true
class <%= validate_not_null_check_name.camelize %> < Nandi::Migration
def up
validate_constraint <%= format_value(@table) %>, <%= format_value(name) %>
end
def down; end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/generators/nandi/check_constraint/check_constraint_generator.rb | lib/generators/nandi/check_constraint/check_constraint_generator.rb | # frozen_string_literal: true
require "rails/generators"
require "nandi/formatting"
require "nandi/multi_db_generator"
module Nandi
class CheckConstraintGenerator < Rails::Generators::Base
include Nandi::Formatting
include Nandi::MultiDbGenerator
argument :table, type: :string
argument :name, type: :string
class_option :validation_timeout, type: :numeric, default: 15 * 60 * 1000
source_root File.expand_path("templates", __dir__)
attr_reader :add_check_constraint_name, :validate_check_constraint_name
def add_check_constraint
self.table = table.to_sym
self.name = name.to_sym
@add_check_constraint_name = "add_check_constraint_#{name}_on_#{table}"
template(
"add_check_constraint.rb",
"#{base_path}/#{timestamp}_#{add_check_constraint_name}.rb",
)
end
def validate_check_constraint
self.table = table.to_sym
self.name = name.to_sym
@validate_check_constraint_name = "validate_check_constraint_#{name}_on_#{table}"
template(
"validate_check_constraint.rb",
"#{base_path}/#{timestamp(1)}_#{validate_check_constraint_name}.rb",
)
end
private
def timestamp(offset = 0)
(Time.now.utc + offset).strftime("%Y%m%d%H%M%S")
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/generators/nandi/check_constraint/templates/validate_check_constraint.rb | lib/generators/nandi/check_constraint/templates/validate_check_constraint.rb | # frozen_string_literal: true
class <%= validate_check_constraint_name.camelize %> < Nandi::Migration
def up
validate_constraint <%= format_value(table) %>, <%= format_value(name) %>
end
def down; end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/generators/nandi/check_constraint/templates/add_check_constraint.rb | lib/generators/nandi/check_constraint/templates/add_check_constraint.rb | # frozen_string_literal: true
class <%= add_check_constraint_name.camelize %> < Nandi::Migration
def up
add_check_constraint <%= format_value(table) %>,
<%= format_value(name) %>,
<<~SQL
-- foo IS NOT NULL OR bar IS NOT NULL
SQL
end
def down
drop_constraint <%= format_value(table) %>, <%= format_value(name) %>
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/file_diff.rb | lib/nandi/file_diff.rb | # frozen_string_literal: true
module Nandi
class FileDiff
attr_reader :file_path, :known_digest
def initialize(file_path:, known_digest:)
@file_path = file_path
@known_digest = known_digest
end
def file_name
File.basename(file_path)
end
def body
File.read(file_path)
end
def digest
Digest::SHA256.hexdigest(body)
end
def unchanged?
!changed?
end
def changed?
known_digest != digest
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/instructions.rb | lib/nandi/instructions.rb | # frozen_string_literal: true
require "nandi/instructions/add_index"
require "nandi/instructions/remove_index"
require "nandi/instructions/create_table"
require "nandi/instructions/drop_table"
require "nandi/instructions/add_column"
require "nandi/instructions/add_reference"
require "nandi/instructions/remove_reference"
require "nandi/instructions/remove_column"
require "nandi/instructions/add_foreign_key"
require "nandi/instructions/drop_constraint"
require "nandi/instructions/remove_not_null_constraint"
require "nandi/instructions/change_column_default"
require "nandi/instructions/validate_constraint"
require "nandi/instructions/add_check_constraint"
require "nandi/instructions/irreversible_migration"
module Nandi
module Instructions; end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/version.rb | lib/nandi/version.rb | # frozen_string_literal: true
module Nandi
VERSION = "2.0.1"
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/renderers.rb | lib/nandi/renderers.rb | # frozen_string_literal: true
require "nandi/renderers/active_record"
module Nandi
module Renderers; end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/multi_db_generator.rb | lib/nandi/multi_db_generator.rb | # frozen_string_literal: true
module Nandi
module MultiDbGenerator
def self.included(base)
base.class_option :database,
default: nil,
type: :string,
desc: "Database to migrate in multi-database mode. " \
"If not specified, uses specified default or primary database"
end
private
def db_name
options["database"]&.to_sym
end
def base_path
Nandi.config.migration_directory(db_name)
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/lockfile.rb | lib/nandi/lockfile.rb | # frozen_string_literal: true
require "active_support/core_ext/hash/indifferent_access"
require "digest"
module Nandi
class Lockfile
attr_reader :db_name
class << self
# Registry pattern using class variables to maintain singleton instances
# per database. This ensures that lockfile operations for the same database
# always work with the same instance, maintaining consistency.
def for(db_name)
@instances ||= {}
# Handle nil by using :primary as default
key = db_name.nil? ? :primary : db_name.to_sym
@instances[key] ||= new(key)
end
def clear_instances!
@instances = {}
end
private_class_method :new
end
def initialize(db_name = nil)
@db_name = db_name || Nandi.config.default.name
end
def file_present?
File.exist?(path)
end
def create!
return if file_present?
File.write(path, {}.to_yaml)
end
def add(file_name:, source_digest:, compiled_digest:)
load!
@lockfile[file_name] = {
source_digest: source_digest,
compiled_digest: compiled_digest,
}
end
def get(file_name)
load!
{
source_digest: @lockfile.dig(file_name, :source_digest),
compiled_digest: @lockfile.dig(file_name, :compiled_digest),
}
end
def load!
return @lockfile if @lockfile
create! unless file_present?
@lockfile = YAML.safe_load_file(path).with_indifferent_access
end
def persist!
load!
# This is a somewhat ridiculous trick to avoid merge conflicts in git.
#
# Normally, new migrations are added to the bottom of the Nandi lockfile.
# This is relatively unfriendly to git's merge algorithm, and means that
# if someone merges a pull request with a completely unrelated migration,
# you'll have to rebase to get yours merged as the last line of the file
# will be seen as a conflict (both branches added content there).
#
# This is in contrast to something like Gemfile.lock, where changes tend
# to be distributed throughout the file. The idea behind sorting by
# SHA-256 hash is to distribute new Nandi lockfile entries evenly, but
# also stably through the file. It needs to be stable or we'd have even
# worse merge conflict problems (e.g. if we randomised the order on
# writing the file, the whole thing would conflict pretty much every time
# it was regenerated).
content = @lockfile.to_h.deep_stringify_keys.sort_by do |k, _|
Digest::SHA256.hexdigest(k)
end.to_h.to_yaml
File.write(path, content)
end
private
def path
Nandi.config.lockfile_path(@db_name)
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/migration_violations.rb | lib/nandi/migration_violations.rb | # frozen_string_literal: true
module Nandi
class MigrationViolations
def initialize
@ungenerated_files = []
@handwritten_files = []
@out_of_date_files = []
@hand_edited_files = []
end
def add_ungenerated(missing_files, directory)
return if missing_files.empty?
full_paths = build_full_paths(missing_files, directory)
@ungenerated_files.concat(full_paths)
end
def add_handwritten(handwritten_files, directory)
return if handwritten_files.empty?
full_paths = build_full_paths(handwritten_files, directory)
@handwritten_files.concat(full_paths)
end
def add_out_of_date(changed_files, directory)
return if changed_files.empty?
full_paths = build_full_paths(changed_files, directory)
@out_of_date_files.concat(full_paths)
end
def add_hand_edited(altered_files, directory)
return if altered_files.empty?
full_paths = build_full_paths(altered_files, directory)
@hand_edited_files.concat(full_paths)
end
def any?
[@ungenerated_files, @handwritten_files, @out_of_date_files, @hand_edited_files].any?(&:any?)
end
def to_error_message
error_messages = []
error_messages << ungenerated_error if @ungenerated_files.any?
error_messages << handwritten_error if @handwritten_files.any?
error_messages << out_of_date_error if @out_of_date_files.any?
error_messages << hand_edited_error if @hand_edited_files.any?
error_messages.join("\n\n")
end
private
def build_full_paths(filenames, directory)
filenames.map { |filename| File.join(directory, filename) }
end
def format_file_list(files)
" - #{files.sort.join("\n - ")}"
end
def ungenerated_error
<<~ERROR.strip
The following migrations are pending generation:
#{format_file_list(@ungenerated_files)}
Please run `rails generate nandi:compile` to generate your migrations.
ERROR
end
def handwritten_error
<<~ERROR.strip
The following migrations have been written by hand, not generated:
#{format_file_list(@handwritten_files)}
Please use Nandi to generate your migrations. In exeptional cases, hand-written
ActiveRecord migrations can be added to the .nandiignore file. Doing so will
require additional review that will slow your PR down.
ERROR
end
def out_of_date_error
<<~ERROR.strip
The following migrations have changed but not been recompiled:
#{format_file_list(@out_of_date_files)}
Please recompile your migrations to make sure that the changes you expect are
applied.
ERROR
end
def hand_edited_error
<<~ERROR.strip
The following migrations have had their generated content altered:
#{format_file_list(@hand_edited_files)}
Please don't hand-edit generated migrations. If you want to write a regular
ActiveRecord::Migration, please do so and add it to .nandiignore. Note that
this will require additional review that will slow your PR down.
ERROR
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/safe_migration_enforcer.rb | lib/nandi/safe_migration_enforcer.rb | # frozen_string_literal: true
require "digest"
require "rails"
require "rails/generators"
require "nandi/file_diff"
require "nandi/file_matcher"
require "nandi/lockfile"
require "nandi/migration_violations"
module Nandi
class SafeMigrationEnforcer
class MigrationLintingFailed < StandardError; end
DEFAULT_SAFE_MIGRATION_DIR = "db/safe_migrations"
DEFAULT_AR_MIGRATION_DIR = "db/migrate"
DEFAULT_FILE_SPEC = "all"
attr_reader :violations
def initialize(require_path: nil,
safe_migration_dir: DEFAULT_SAFE_MIGRATION_DIR,
ar_migration_dir: DEFAULT_AR_MIGRATION_DIR,
files: DEFAULT_FILE_SPEC)
@files = files
require require_path unless require_path.nil?
configure_legacy_mode_if_needed(safe_migration_dir, ar_migration_dir)
@violations = MigrationViolations.new
end
def run
collect_violations
if violations.any?
raise MigrationLintingFailed, violations.to_error_message
end
true
end
private
def configure_legacy_mode_if_needed(safe_dir, ar_dir)
legacy_mode = safe_dir != DEFAULT_SAFE_MIGRATION_DIR ||
ar_dir != DEFAULT_AR_MIGRATION_DIR
return unless legacy_mode
Nandi.configure do |c|
c.migration_directory = safe_dir
c.output_directory = ar_dir
end
end
def collect_violations
Nandi.config.databases.each do |_, database|
check_database_violations(database)
end
end
def check_database_violations(database)
safe_migrations = matching_migrations(database.migration_directory)
ar_migrations = matching_migrations(database.output_directory)
# Check ungenerated migrations and get remaining files
remaining_safe, remaining_ar = check_ungenerated_migrations(
safe_migrations, ar_migrations, database
)
# Check handwritten migrations and get remaining files
remaining_safe, remaining_ar = check_handwritten_migrations(
remaining_safe, remaining_ar, database
)
# Check out-of-date migrations
check_out_of_date_migrations(remaining_safe, database)
# Check hand-edited migrations
check_hand_edited_migrations(remaining_ar, database)
end
def check_ungenerated_migrations(safe_migrations, ar_migrations, database)
missing_files = safe_migrations - ar_migrations
violations.add_ungenerated(missing_files, database.migration_directory)
# Return remaining files after removing processed ones
[safe_migrations - missing_files, ar_migrations]
end
def check_handwritten_migrations(safe_migrations, ar_migrations, database)
handwritten_files = ar_migrations - safe_migrations
violations.add_handwritten(handwritten_files, database.output_directory)
# Return remaining files after removing processed ones
[safe_migrations, ar_migrations - handwritten_files]
end
def check_out_of_date_migrations(safe_migrations, database)
out_of_date_files = find_changed_files(
safe_migrations,
database,
:source_digest,
database.migration_directory,
)
violations.add_out_of_date(out_of_date_files, database.migration_directory)
end
def check_hand_edited_migrations(ar_migrations, database)
hand_edited_files = find_changed_files(
ar_migrations,
database,
:compiled_digest,
database.output_directory,
)
violations.add_hand_edited(hand_edited_files, database.output_directory)
end
def find_changed_files(filenames, database, digest_key, directory)
filenames.filter_map do |filename|
digests = Nandi::Lockfile.for(database.name).get(filename)
file_diff = Nandi::FileDiff.new(
file_path: File.join(directory, filename),
known_digest: digests[digest_key],
)
filename if file_diff.changed?
end
end
def matching_migrations(directory)
return Set.new unless Dir.exist?(directory)
filenames = Dir.glob(File.join(directory, "*.rb")).map { |path| File.basename(path) }
FileMatcher.call(files: filenames, spec: @files)
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/formatting.rb | lib/nandi/formatting.rb | # frozen_string_literal: true
module Nandi
module Formatting
class UnsupportedValueError < StandardError; end
module ClassMethods
# Define an accessor method that will retrieve a value
# from a cell's model and format it with the format_value
# method below.
# @param name [String] the attribute on model to retrieve
# @example formatting the foo property
# class MyCell < Cells::ViewModel
# include Nandi::Formatting
#
# formatted_property :foo
# end
def formatted_property(name)
define_method(name) do
format_value(model.send(name))
end
end
end
# Create a string representation of the value that is a valid
# and correct Ruby literal for that value. Please note that the
# exact representation is not guaranteed to be the same between
# different platforms and Ruby versions. The guarantee is merely
# that calling this method with any supported type will produce
# a string that produces an equal value when it is passed to
# Kernel::eval
# @param value [Hash, Array, String, Symbol, Integer, Float, NilClass]
# value to format
def format_value(value, opts = {})
case value
when Hash
format_hash(value, opts)
when Array
"[#{value.map { |v| format_value(v, opts) }.join(', ')}]"
when String, Symbol, Integer, Float, NilClass, TrueClass, FalseClass
value.inspect
else
raise UnsupportedValueError,
"Cannot format value of type #{value.class.name}"
end
end
def self.included(base)
base.extend(ClassMethods)
end
private
def format_hash(value, opts)
if opts[:as_argument]
hash_pairs(value).join(", ")
else
"{\n #{hash_pairs(value).join(",\n ")}\n}"
end
end
def hash_pairs(value)
value.map do |k, v|
key = if k.is_a?(Symbol)
symbol_key(k)
else
"#{format_value(k)} =>"
end
"#{key} #{format_value(v)}"
end
end
def symbol_key(key)
canonical = key.inspect
"#{canonical[1..]}:"
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/multi_database.rb | lib/nandi/multi_database.rb | # frozen_string_literal: true
module Nandi
class MultiDatabase
class Database
# Most DDL changes take a very strict lock, but execute very quickly. For these
# the statement timeout should be very tight, so that if there's an unexpected
# delay the query queue does not back up.
DEFAULT_ACCESS_EXCLUSIVE_STATEMENT_TIMEOUT = 1_500
DEFAULT_ACCESS_EXCLUSIVE_LOCK_TIMEOUT = 5_000
DEFAULT_ACCESS_EXCLUSIVE_STATEMENT_TIMEOUT_LIMIT =
DEFAULT_ACCESS_EXCLUSIVE_STATEMENT_TIMEOUT
DEFAULT_ACCESS_EXCLUSIVE_LOCK_TIMEOUT_LIMIT =
DEFAULT_ACCESS_EXCLUSIVE_LOCK_TIMEOUT
DEFAULT_CONCURRENT_TIMEOUT_LIMIT = 3_600_000
DEFAULT_MIGRATION_DIRECTORY = "db/safe_migrations"
DEFAULT_OUTPUT_DIRECTORY = "db/migrate"
# The default lock timeout for migrations that take ACCESS EXCLUSIVE
# locks. Can be overridden by way of the `set_lock_timeout` class
# method in a given migration. Default: 1500ms.
# @return [Integer]
attr_accessor :access_exclusive_lock_timeout
# The default statement timeout for migrations that take ACCESS EXCLUSIVE
# locks. Can be overridden by way of the `set_statement_timeout` class
# method in a given migration. Default: 1500ms.
# @return [Integer]
attr_accessor :access_exclusive_statement_timeout
# The maximum lock timeout for migrations that take an ACCESS EXCLUSIVE
# lock and therefore block all reads and writes. Default: 5,000ms.
# @return [Integer]
attr_accessor :access_exclusive_statement_timeout_limit
# The maximum statement timeout for migrations that take an ACCESS
# EXCLUSIVE lock and therefore block all reads and writes. Default: 1500ms.
# @return [Integer]
attr_accessor :access_exclusive_lock_timeout_limit
# The minimum statement timeout for migrations that take place concurrently.
# Default: 3,600,000ms (ie, 3 hours).
# @return [Integer]
attr_accessor :concurrent_statement_timeout_limit
# The minimum lock timeout for migrations that take place concurrently.
# Default: 3,600,000ms (ie, 3 hours).
# @return [Integer]
attr_accessor :concurrent_lock_timeout_limit
# The directory for output files. Default: `db/migrate`
# @return [String]
attr_accessor :output_directory
attr_reader :name, :default, :raw_config
attr_accessor :migration_directory,
:lockfile_name
def initialize(name:, config:)
@name = name
@raw_config = config
@default = @name == :primary || config[:default] == true
# Paths and files
@migration_directory = config[:migration_directory] || "db/#{path_prefix(name, default)}safe_migrations"
@output_directory = config[:output_directory] || "db/#{path_prefix(name, default)}migrate"
@lockfile_name = config[:lockfile_name] || ".#{path_prefix(name, default)}nandilock.yml"
timeout_limits(config)
end
private
def timeout_limits(config)
@access_exclusive_lock_timeout =
config[:access_exclusive_lock_timeout] || DEFAULT_ACCESS_EXCLUSIVE_LOCK_TIMEOUT
@access_exclusive_statement_timeout =
config[:access_exclusive_statement_timeout] || DEFAULT_ACCESS_EXCLUSIVE_STATEMENT_TIMEOUT
@access_exclusive_lock_timeout_limit =
config[:access_exclusive_lock_timeout_limit] || DEFAULT_ACCESS_EXCLUSIVE_LOCK_TIMEOUT_LIMIT
@access_exclusive_statement_timeout_limit =
config[:access_exclusive_statement_timeout_limit] || DEFAULT_ACCESS_EXCLUSIVE_STATEMENT_TIMEOUT_LIMIT
@concurrent_lock_timeout_limit =
config[:concurrent_lock_timeout_limit] || DEFAULT_CONCURRENT_TIMEOUT_LIMIT
@concurrent_statement_timeout_limit =
config[:concurrent_statement_timeout_limit] || DEFAULT_CONCURRENT_TIMEOUT_LIMIT
end
def path_prefix(name, default)
default ? "" : "#{name}_"
end
end
def initialize
@databases = {}
end
def config(name = nil)
# If name isnt specified, return config for the default database. This mimics behavior
# of the rails migration commands.
return default if name.nil?
name = name.to_sym
db_config = @databases[name]
raise ArgumentError, "Missing database configuration for #{name}" if db_config.nil?
db_config
end
def default
@databases.values.find(&:default)
end
def register(name, config)
name = name.to_sym
# Allow re-registration with identical config (for Rails reloading)
return @databases[name] if @databases.key?(name) && @databases[name].raw_config == config
raise ArgumentError, "Database #{name} already registered" if @databases.key?(name)
@databases[name] = Database.new(name: name, config: config)
end
def names
@databases.keys
end
def validate!
enforce_default_db_for_multi_database!
enforce_names_for_multi_database!
validate_unique_migration_directories!
validate_unique_output_directories!
end
delegate :each, :map, to: :@databases
private
def enforce_default_db_for_multi_database!
# If there is a `primary` database, we take that as the default database
# following rails behavior. If not, we will validate that there is one specified
# default database using the `default: true` option.
if @databases.values.none?(&:default)
raise ArgumentError, "Missing default database. Specify a default database using the `default: true` option " \
"or by registering `primary` as a database name."
end
if @databases.values.count(&:default) > 1
raise ArgumentError, "Multiple default databases specified: " \
"#{@databases.values.select(&:default).map(&:name).join(', ')}"
end
end
def validate_unique_migration_directories!
paths = @databases.values.map(&:migration_directory).uniq.filter(&:present?)
if paths.length != @databases.values.length
raise ArgumentError,
"Unique migration directories must be specified for each database"
end
end
def validate_unique_output_directories!
paths = @databases.values.map(&:output_directory).uniq.filter(&:present?)
if paths.length != @databases.values.length
raise ArgumentError,
"Unique output directories must be specified for each database"
end
end
def enforce_names_for_multi_database!
# If we're in multi-db mode, enforce that all databases have a name
return if @databases.count <= 1
unknown_names = @databases.keys.select(&:nil?)
if unknown_names.any?
raise ArgumentError, "Databases must have a name in multi-db mode"
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/timeout_policies.rb | lib/nandi/timeout_policies.rb | # frozen_string_literal: true
require "nandi/validation/failure_helpers"
require "nandi/migration"
require "nandi/timeout_policies/access_exclusive"
require "nandi/timeout_policies/concurrent"
module Nandi
module TimeoutPolicies
CONCURRENT_OPERATIONS = %i[add_index remove_index].freeze
class Noop
class << self
include Nandi::Validation::FailureHelpers
def validate(_)
success
end
end
end
def self.policy_for(instruction)
case instruction.lock
when Nandi::Migration::LockWeights::ACCESS_EXCLUSIVE
AccessExclusive
else
share_policy_for(instruction)
end
end
def self.share_policy_for(instruction)
if CONCURRENT_OPERATIONS.include?(instruction.procedure)
Concurrent
else
Noop
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/validator.rb | lib/nandi/validator.rb | # frozen_string_literal: true
require "dry/monads"
require "nandi/validation"
require "nandi/timeout_policies"
module Nandi
class Validator
include Nandi::Validation::FailureHelpers
class InstructionValidator
def self.call(instruction)
new(instruction).call
end
def initialize(instruction)
@instruction = instruction
end
def call
raise NotImplementedError
end
attr_reader :instruction
end
def self.call(migration)
new(migration).call
end
def initialize(migration)
@migration = migration
end
def call
migration_invariants_respected << each_instruction_validation
end
private
def migration_invariants_respected
Validation::Result.new.tap do |result|
result << assert(
at_most_one_object_modified,
"modifying more than one table per migration",
)
result << assert(
new_indexes_are_separated_from_other_migrations,
"creating more than one index per migration",
)
result << validate_timeouts
end
end
def at_most_one_object_modified
[migration.up_instructions, migration.down_instructions].all? do |instructions|
affected_tables = instructions.map do |instruction|
instruction.respond_to?(:table) && instruction.table.to_sym
end
affected_tables.uniq.count <= 1
end
end
def new_indexes_are_separated_from_other_migrations
[migration.up_instructions, migration.down_instructions].map do |instructions|
instructions.none? { |i| i.procedure == :add_index } ||
instructions.count == 1
end.all?
end
def statement_timeout_is_within_acceptable_bounds
migration.strictest_lock != Nandi::Migration::LockWeights::ACCESS_EXCLUSIVE ||
migration.statement_timeout <=
Nandi.config.access_exclusive_statement_timeout_limit
end
def lock_timeout_is_within_acceptable_bounds
migration.strictest_lock != Nandi::Migration::LockWeights::ACCESS_EXCLUSIVE ||
migration.lock_timeout <=
Nandi.config.access_exclusive_lock_timeout_limit
end
def each_instruction_validation
instructions.inject(success) do |result, instruction|
collect_errors(Validation::EachValidator.call(instruction), result)
end
end
def validate_timeouts
Nandi::Validation::TimeoutValidator.call(migration)
end
def instructions
[*migration.up_instructions, *migration.down_instructions]
end
attr_reader :migration
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/config.rb | lib/nandi/config.rb | # frozen_string_literal: true
require "nandi/renderers"
require "nandi/lockfile"
require "nandi/multi_database"
module Nandi
class Config
DEFAULT_COMPILE_FILES = "all"
DEFAULT_LOCKFILE_DIRECTORY = File.join(Dir.pwd, "db")
# The rendering backend used to produce output. The only supported option
# at current is Nandi::Renderers::ActiveRecord, which produces ActiveRecord
# migrations.
# @return [Class]
attr_accessor :renderer
# The files to compile when the compile generator is run. Default: `all`
# May be one of the following:
# - 'all' compiles all files
# - 'git-diff' only files changed since last commit
# - a full or partial version timestamp, eg '20190101010101', '20190101'
# - a timestamp range , eg '>=20190101010101'
# @return [String]
attr_accessor :compile_files
# Directory where .nandilock.yml will be stored
# Defaults to project root
# @return [String]
attr_writer :lockfile_directory
# @api private
attr_reader :post_processor, :custom_methods
def initialize(renderer: Renderers::ActiveRecord)
@renderer = renderer
@custom_methods = {}
@compile_files = DEFAULT_COMPILE_FILES
@lockfile_directory = DEFAULT_LOCKFILE_DIRECTORY
end
# Register a block to be called on output, for example a code formatter. Whatever is
# returned will be written to the output file.
# @yieldparam migration [string] The text of a compiled migration.
def post_process(&block)
@post_processor = block
end
# Register a custom DDL method.
# @param name [Symbol] The name of the method to create. This will be monkey-patched
# into Nandi::Migration.
# @param klass [Class] The class to initialise with the arguments to the
# method. It should define a `template` instance method which will return a
# subclass of Cell::ViewModel from the Cells templating library and a
# `procedure` method that returns the name of the method. It may optionally
# define a `mixins` method, which will return an array of `Module`s to be
# mixed into any migration that uses this method.
def register_method(name, klass)
custom_methods[name] = klass
end
# Register a database to compile migrations for.
def register_database(name, config = {})
multi_db_config.register(name, config)
end
def lockfile_path(database_name = nil)
File.join(lockfile_directory, databases.config(database_name).lockfile_name)
end
# Explicitly define getters for backwards compatibility when the database isnt specified.
# rubocop:disable Layout/LineLength
def migration_directory(database_name = nil) = config(database_name).migration_directory
def output_directory(database_name = nil) = config(database_name).output_directory
def access_exclusive_lock_timeout(database_name = nil) = config(database_name).access_exclusive_lock_timeout
def access_exclusive_lock_timeout_limit(database_name = nil) = config(database_name).access_exclusive_lock_timeout_limit
def access_exclusive_statement_timeout(database_name = nil) = config(database_name).access_exclusive_statement_timeout
def access_exclusive_statement_timeout_limit(database_name = nil) = config(database_name).access_exclusive_statement_timeout_limit
def concurrent_lock_timeout_limit(database_name = nil) = config(database_name).concurrent_lock_timeout_limit
def concurrent_statement_timeout_limit(database_name = nil) = config(database_name).concurrent_statement_timeout_limit
# rubocop:enable Layout/LineLength
# Delegate setter methods to the default database for backwards compatibility
delegate :migration_directory=,
:output_directory=,
:access_exclusive_lock_timeout=,
:access_exclusive_lock_timeout_limit=,
:access_exclusive_statement_timeout=,
:access_exclusive_statement_timeout_limit=,
:concurrent_lock_timeout_limit=,
:concurrent_statement_timeout_limit=,
to: :default
delegate :validate!, :default, :config, to: :databases
alias_method :database, :config
def databases
# If we've never registered any databases, use a single database with
# default values for backwards compatibility.
@multi_db_config.nil? ? single_db_config : @multi_db_config
end
def validate!
if @single_db_config && @multi_db_config
raise ArgumentError, "Cannot use multi and single database config. Config setters are now deprecated, " \
"use only `register_database(name, config)` to configure Nandi."
end
databases.validate!
end
private
def single_db_config
# Pre-register the default database to ensure behavior is backwards compatible.
@single_db_config ||= begin
single_db_config = MultiDatabase.new
single_db_config.register(:primary, {})
single_db_config
end
end
def multi_db_config
@multi_db_config ||= MultiDatabase.new
end
def lockfile_directory
@lockfile_directory ||= Pathname.new(@lockfile_directory)
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/migration.rb | lib/nandi/migration.rb | # frozen_string_literal: true
require "nandi/instructions"
require "nandi/validator"
require "nandi/validation/failure_helpers"
module Nandi
# @abstract A migration must implement #up (the forward migration), and may
# also implement #down (the rollback sequence).
# The base class for migrations; Nandi's equivalent of ActiveRecord::Migration.
# All the statements in the migration are statically analysed together to rule
# out migrations with a high risk of causing availability issues. Additionally,
# our implementations of some statements will rule out certain common footguns
# (for example, creating an index without using the `CONCURRENTLY` parameter.)
# @example
# class CreateWidgetsTable < Nandi::Migration
# def up
# create_table :widgets do |t|
# t.column :weight, :number
# t.column :name, :text, default: "Unknown widget"
# end
# end
#
# def down
# drop_table :widgets
# end
# end
class Migration
include Nandi::Validation::FailureHelpers
module LockWeights
ACCESS_EXCLUSIVE = 1
SHARE = 0
end
class InstructionSet < SimpleDelegator
def strictest_lock
return LockWeights::SHARE if empty?
map { |i| i.respond_to?(:lock) ? i.lock : LockWeights::ACCESS_EXCLUSIVE }.max
end
end
class << self
attr_reader :lock_timeout, :statement_timeout
# For sake both of correspondence with Postgres syntax and familiarity
# with activerecord-safe_migrations's identically named macros, we
# disable this cop.
# rubocop:disable Naming/AccessorMethodName
# Override the default lock timeout for the duration of the migration.
# This may be helpful when making changes to very busy tables, when a
# lock is less likely to be immediately available.
# @param timeout [Integer] New lock timeout in ms
def set_lock_timeout(timeout)
@lock_timeout = timeout
end
# Override the default statement timeout for the duration of the migration.
# This may be helpful when making changes that are likely to take a lot
# of time, like adding a new index on a large table.
# @param timeout [Integer] New lock timeout in ms
def set_statement_timeout(timeout)
@statement_timeout = timeout
end
# rubocop:enable Naming/AccessorMethodName
end
# @param validator [Nandi::Validator]
def initialize(validator)
@validator = validator
@instructions = Hash.new { |h, k| h[k] = InstructionSet.new([]) }
validate
end
# @api private
def up_instructions
compile_instructions(:up)
end
# @api private
def down_instructions
compile_instructions(:down)
end
# The current lock timeout.
def lock_timeout
self.class.lock_timeout || default_lock_timeout
end
# The current statement timeout.
def statement_timeout
self.class.statement_timeout || default_statement_timeout
end
# @api private
def strictest_lock
@instructions.values.map(&:strictest_lock).max
end
# @abstract
def up
raise NotImplementedError
end
def down; end
# Adds a new index to the database.
#
# Nandi will:
# * add the `CONCURRENTLY` option, which means the change takes a less
# restrictive lock at the cost of not running in a DDL transaction
# * default to the `BTREE` index type, as it is commonly a good fit.
#
# Because index creation is particularly failure-prone, and because
# we cannot run in a transaction and therefore risk partially applied
# migrations that (in a Rails environment) require manual intervention,
# Nandi Validates that, if there is a add_index statement in the
# migration, it must be the only statement.
# @param table [Symbol, String] The name of the table to add the index to
# @param fields [Symbol, String, Array] The field or fields to use in the
# index
# @param kwargs [Hash] Arbitrary options to pass to the backend adapter.
# Attempts to remove `CONCURRENTLY` or change the index type will be ignored.
def add_index(table, fields, **kwargs)
current_instructions << Instructions::AddIndex.new(
**kwargs,
table: table,
fields: fields,
)
end
# Drop an index from the database.
#
# Nandi will add the `CONCURRENTLY` option, which means the change
# takes a less restrictive lock at the cost of not running in a DDL
# transaction.
#
# Because we cannot run in a transaction and therefore risk partially
# applied migrations that (in a Rails environment) require manual
# intervention, Nandi Validates that, if there is a remove_index statement
# in the migration, it must be the only statement.
# @param table [Symbol, String] The name of the table to add the index to
# @param target [Symbol, String, Array, Hash] This can be either the field (or
# array of fields) in the index to be dropped, or a hash of options, which
# must include either a `column` key (which is the same: a field or list
# of fields) or a `name` key, which is the name of the index to be dropped.
def remove_index(table, target)
current_instructions << Instructions::RemoveIndex.new(table: table, field: target)
end
# Creates a new table. Yields a ColumnsReader object as a block, to allow adding
# columns.
# @example
# create_table :widgets do |t|
# t.text :foo, default: true
# end
# @param table [String, Symbol] The name of the new table
# @yieldparam columns_reader [Nandi::Instructions::CreateTable::ColumnsReader]
def create_table(table, **kwargs, &block)
current_instructions << Instructions::CreateTable.new(
**kwargs,
table: table,
columns_block: block,
)
end
# Drops an existing table
# @param table [String, Symbol] The name of the table to drop.
def drop_table(table)
current_instructions << Instructions::DropTable.new(table: table)
end
# Adds a new column. Nandi will explicitly set the column to be NULL,
# as validating a new NOT NULL constraint can be very expensive on large
# tables and cause availability issues.
# @param table [Symbol, String] The name of the table to add the column to
# @param name [Symbol, String] The name of the column
# @param type [Symbol, String] The type of the column
# @param kwargs [Hash] Arbitrary options to be passed to the backend.
def add_column(table, name, type, **kwargs)
current_instructions << Instructions::AddColumn.new(
table: table,
name: name,
type: type,
**kwargs,
)
end
# Adds a new reference column. Nandi will validate that the foreign key flag
# is not set to true; use `add_foreign_key` and `validate_foreign_key` instead!
# @param table [Symbol, String] The name of the table to add the column to
# @param ref_name [Symbol, String] The referenced column name
# @param kwargs [Hash] Arbitrary options to be passed to the backend.
def add_reference(table, ref_name, **kwargs)
current_instructions << Instructions::AddReference.new(
table: table,
ref_name: ref_name,
**kwargs,
)
end
# Removes a reference column.
# @param table [Symbol, String] The name of the table to remove the reference from
# @param ref_name [Symbol, String] The referenced column name
# @param kwargs [Hash] Arbitrary options to be passed to the backend.
def remove_reference(table, ref_name, **kwargs)
current_instructions << Instructions::RemoveReference.new(
table: table,
ref_name: ref_name,
**kwargs,
)
end
# Remove an existing column.
# @param table [Symbol, String] The name of the table to remove the column
# from.
# @param name [Symbol, String] The name of the column
# @param extra_args [Hash] Arbitrary options to be passed to the backend.
def remove_column(table, name, **extra_args)
current_instructions << Instructions::RemoveColumn.new(
**extra_args,
table: table,
name: name,
)
end
# Add a foreign key constraint. The generated SQL will include the NOT VALID
# parameter, which will prevent immediate validation of the constraint, which
# locks the target table for writes potentially for a long time. Use the separate
# #validate_constraint method, in a separate migration; this only takes a row-level
# lock as it scans through.
# @param table [Symbol, String] The name of the table with the reference column
# @param target [Symbol, String] The name of the referenced table
# @param column [Symbol, String] The name of the reference column. If omitted, will
# default to the singular of target + "_id"
# @param name [Symbol, String] The name of the constraint to create. Defaults to
# table_target_fk
def add_foreign_key(table, target, column: nil, name: nil)
current_instructions << Instructions::AddForeignKey.new(
table: table,
target: target,
column: column,
name: name,
)
end
# Add a check constraint, in the NOT VALID state.
# @param table [Symbol, String] The name of the table with the column
# @param name [Symbol, String] The name of the constraint to create
# @param check [Symbol, String] The predicate to check
def add_check_constraint(table, name, check)
current_instructions << Instructions::AddCheckConstraint.new(
table: table,
name: name,
check: check,
)
end
# Validates an existing foreign key constraint.
# @param table [Symbol, String] The name of the table with the constraint
# @param name [Symbol, String] The name of the constraint
def validate_constraint(table, name)
current_instructions << Instructions::ValidateConstraint.new(
table: table,
name: name,
)
end
# Drops an existing constraint.
# @param table [Symbol, String] The name of the table with the constraint
# @param name [Symbol, String] The name of the constraint
def drop_constraint(table, name)
current_instructions << Instructions::DropConstraint.new(
table: table,
name: name,
)
end
# Drops an existing NOT NULL constraint. Please note that this migration is
# not safely reversible; to enforce NOT NULL like behaviour, use a CHECK
# constraint and validate it in a separate migration.
# @param table [Symbol, String] The name of the table with the constraint
# @param column [Symbol, String] The name of the column to remove NOT NULL
# constraint from
def remove_not_null_constraint(table, column)
current_instructions << Instructions::RemoveNotNullConstraint.new(
table: table,
column: column,
)
end
# Changes the default value for this column when new rows are inserted into
# the table.
# @param table [Symbol, String] The name of the table with the column
# @param column [Symbol, String] The name of the column to change
# @param value [Object] The new default value
def change_column_default(table, column, value)
current_instructions << Instructions::ChangeColumnDefault.new(
table: table,
column: column,
value: value,
)
end
# Raises an `ActiveRecord::IrreversibleMigration` error for use in
# irreversible migrations
def irreversible_migration
current_instructions << Instructions::IrreversibleMigration.new
end
# @api private
def compile_instructions(direction)
@direction = direction
public_send(direction) unless current_instructions.any?
current_instructions
end
# @api private
def validate
validator.call(self)
rescue NotImplementedError => e
Validation::Result.new << failure(e.message)
end
def disable_lock_timeout?
if self.class.lock_timeout.nil?
strictest_lock == LockWeights::SHARE
else
false
end
end
def disable_statement_timeout?
if self.class.statement_timeout.nil?
strictest_lock == LockWeights::SHARE
else
false
end
end
def name
self.class.name
end
def respond_to_missing?(name)
Nandi.config.custom_methods.key?(name) || super
end
def mixins
(up_instructions + down_instructions).inject([]) do |mixins, i|
i.respond_to?(:mixins) ? [*mixins, *i.mixins] : mixins
end.uniq
end
def method_missing(name, ...)
if Nandi.config.custom_methods.key?(name)
invoke_custom_method(name, ...)
else
super
end
end
private
attr_reader :validator
def current_instructions
@instructions[@direction]
end
def default_statement_timeout
Nandi.config.access_exclusive_statement_timeout
end
def default_lock_timeout
Nandi.config.access_exclusive_lock_timeout
end
def invoke_custom_method(name, ...)
klass = Nandi.config.custom_methods[name]
current_instructions << klass.new(...)
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/validation.rb | lib/nandi/validation.rb | # frozen_string_literal: true
require "nandi/validation/add_column_validator"
require "nandi/validation/add_reference_validator"
require "nandi/validation/add_index_validator"
require "nandi/validation/remove_index_validator"
require "nandi/validation/each_validator"
require "nandi/validation/result"
require "nandi/validation/failure_helpers"
require "nandi/validation/timeout_validator"
module Validation; end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/compiled_migration.rb | lib/nandi/compiled_migration.rb | # frozen_string_literal: true
require "nandi/file_diff"
module Nandi
class CompiledMigration
class InvalidMigrationError < StandardError; end
attr_reader :file_name, :source_file_path, :class_name, :db_config
def db_name
@db_config.name
end
def self.build(file_name:, db_name:)
new(file_name:, db_name:)
end
def initialize(file_name:, db_name:)
@file_name = file_name
@db_config = Nandi.config.database(db_name)
@source_file_path = File.join(@db_config.migration_directory, file_name)
require File.expand_path(source_file_path)
@file_name, @class_name = /\d+_([a-z0-9_]+)\.rb\z/.match(source_file_path)[0..1]
end
def validate!
validation = migration.validate
unless validation.valid?
raise InvalidMigrationError, "Migration #{source_file_path} " \
"is not valid:\n#{validation.error_list}"
end
self
end
def body
@body ||= if migration_unchanged?
File.read(output_path)
else
validate!
compiled_body
end
end
def output_path
"#{db_config.output_directory}/#{file_name}"
end
def migration
@migration ||= class_name.camelize.constantize.new(Nandi.validator)
end
def compiled_digest
Digest::SHA256.hexdigest(body)
end
def source_digest
Digest::SHA256.hexdigest(File.read(source_file_path))
end
def migration_unchanged?
return false unless File.exist?(output_path)
lockfile = Nandi::Lockfile.for(db_config.name)
source_migration_diff = Nandi::FileDiff.new(
file_path: source_file_path,
known_digest: lockfile.get(file_name).fetch(:source_digest),
)
compiled_migration_diff = Nandi::FileDiff.new(
file_path: output_path,
known_digest: lockfile.get(file_name).fetch(:compiled_digest),
)
source_migration_diff.unchanged? && compiled_migration_diff.unchanged?
end
private
def compiled_body
output = Nandi.config.renderer.generate(migration)
if Nandi.config.post_processor
Nandi.config.post_processor.call(output)
else
output
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/file_matcher.rb | lib/nandi/file_matcher.rb | # frozen_string_literal: true
module Nandi
class FileMatcher
TIMESTAMP_REGEX = /\A(?<operator>>|>=)?(?<timestamp>\d+)\z/
def self.call(*args, **kwargs)
new(*args, **kwargs).call
end
def initialize(files:, spec:)
@files = Set.new(files)
@spec = spec
end
def call
case spec
when "all"
Set.new(
files.reject { |f| ignored_filenames.include?(File.basename(f)) },
)
when "git-diff"
files.intersection(files_from_git_status)
when TIMESTAMP_REGEX
match_timestamp
end
end
private
def ignored_files
@ignored_files ||= if File.exist?(".nandiignore")
File.read(".nandiignore").lines.map(&:strip)
else
[]
end
end
def ignored_filenames
ignored_files.map { |file| File.basename(file) }
end
def match_timestamp
match = TIMESTAMP_REGEX.match(spec)
case match[:operator]
when nil
files.select do |file|
file.start_with?(match[:timestamp])
end
when ">"
migrations_after((Integer(match[:timestamp]) + 1).to_s)
when ">="
migrations_after(match[:timestamp])
end.to_set
end
def migrations_after(minimum)
files.select { |file| file >= minimum }
end
def files_from_git_status
`
git status --porcelain --short --untracked-files=all |
cut -c4- |
xargs -n1 basename
`.lines.map(&:strip)
end
attr_reader :files, :spec
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/validation/failure_helpers.rb | lib/nandi/validation/failure_helpers.rb | # frozen_string_literal: true
require "dry/monads/result"
module Nandi
module Validation
module FailureHelpers
def collect_errors(new, old)
return success if new.success? && old.success?
if old.failure?
failure(Array(old.failure) + Array(new.failure))
else
failure(Array(new.failure))
end
end
def success
Dry::Monads::Result::Success.new(nil)
end
def failure(value)
Dry::Monads::Result::Failure.new(value)
end
def assert(condition, message)
if condition
success
else
failure(message)
end
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/validation/add_index_validator.rb | lib/nandi/validation/add_index_validator.rb | # frozen_string_literal: true
require "nandi/validation/failure_helpers"
module Nandi
module Validation
class AddIndexValidator
include Nandi::Validation::FailureHelpers
def self.call(instruction)
new(instruction).call
end
def initialize(instruction)
@instruction = instruction
end
def call
assert(
not_using_hash_index?,
"add_index: Nandi does not support hash indexes. Hash indexes typically have " \
"very specialized use cases. Please revert to using a btree index, or proceed " \
"with the creation of this index without using Nandi.",
)
end
attr_reader :instruction
private
def not_using_hash_index?
instruction.extra_args[:using] != :hash
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/validation/add_column_validator.rb | lib/nandi/validation/add_column_validator.rb | # frozen_string_literal: true
require "nandi/validation/failure_helpers"
module Nandi
module Validation
class AddColumnValidator
include Nandi::Validation::FailureHelpers
def self.call(instruction)
new(instruction).call
end
def initialize(instruction)
@instruction = instruction
end
def call
collect_errors(
assert(nullable? || default_value?,
"add_column: non-null column lacks default"),
assert(!unique?, "add_column: column is unique"),
)
end
attr_reader :instruction
private
def default_value?
!instruction.extra_args[:default].nil?
end
def nullable?
instruction.extra_args.fetch(:null, true)
end
def unique?
instruction.extra_args.fetch(:unique, false)
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/validation/add_reference_validator.rb | lib/nandi/validation/add_reference_validator.rb | # frozen_string_literal: true
require "nandi/validation/failure_helpers"
module Nandi
module Validation
class AddReferenceValidator
include Nandi::Validation::FailureHelpers
def self.call(instruction)
new(instruction).call
end
def initialize(instruction)
@instruction = instruction
end
def call
foreign_key = instruction.extra_args.fetch(:foreign_key, false)
index = instruction.extra_args.fetch(:index, false)
collect_errors(
assert(
!foreign_key,
foreign_key_message,
),
assert(
!index,
index_message,
),
)
end
private
def index_message
"Indexing a reference column on creation can make the table unavailable." \
"Use the `add_index` method in a separate migration to index the column."
end
def foreign_key_message
"Adding a foreign key constraint must be done in two separate migrations. " \
"Use the `add_foreign_key` and `validate_foreign_key` methods, or the " \
"nandi:foreign_key generator, to do this."
end
attr_reader :instruction
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/validation/result.rb | lib/nandi/validation/result.rb | # frozen_string_literal: true
require "nandi/validation/failure_helpers"
module Nandi
module Validation
class Result
include Nandi::Validation::FailureHelpers
attr_reader :errors
def initialize(instruction = nil)
@instruction = instruction
@errors = success
end
def valid?
@errors.success?
end
def <<(error)
@errors = collect_errors(error, @errors)
self
end
def error_list
@errors.failure.join("\n")
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/validation/remove_index_validator.rb | lib/nandi/validation/remove_index_validator.rb | # frozen_string_literal: true
require "nandi/validation/failure_helpers"
module Nandi
module Validation
class RemoveIndexValidator
include Nandi::Validation::FailureHelpers
def self.call(instruction)
new(instruction).call
end
def initialize(instruction)
@instruction = instruction
end
def call
opts = instruction.extra_args
assert(
opts.key?(:name) || opts.key?(:column),
"remove_index: requires a `name` or `column` argument",
)
end
attr_reader :instruction
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/validation/timeout_validator.rb | lib/nandi/validation/timeout_validator.rb | # frozen_string_literal: true
require "nandi/validation/failure_helpers"
module Nandi
module Validation
class TimeoutValidator
include Nandi::Validation::FailureHelpers
def self.call(migration)
new(migration).call
end
def initialize(migration)
@migration = migration
end
def call
timeout_policies.inject(success) do |result, policy|
collect_errors(policy.validate(migration), result)
end
end
private
def timeout_policies
instructions.map do |instruction|
Nandi::TimeoutPolicies.policy_for(instruction)
end.uniq
end
def instructions
[*migration.up_instructions, *migration.down_instructions]
end
attr_reader :migration
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/validation/each_validator.rb | lib/nandi/validation/each_validator.rb | # frozen_string_literal: true
require "nandi/validation/failure_helpers"
module Nandi
module Validation
class EachValidator
include Nandi::Validation::FailureHelpers
def self.call(instruction)
new(instruction).call
end
def initialize(instruction)
@instruction = instruction
end
def call
case instruction.procedure
when :add_index
AddIndexValidator.call(instruction)
when :remove_index
RemoveIndexValidator.call(instruction)
when :add_column
AddColumnValidator.call(instruction)
when :add_reference
AddReferenceValidator.call(instruction)
else
success
end
end
attr_reader :instruction
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/timeout_policies/access_exclusive.rb | lib/nandi/timeout_policies/access_exclusive.rb | # frozen_string_literal: true
require "nandi"
require "nandi/validation/failure_helpers"
module Nandi
module TimeoutPolicies
class AccessExclusive
include Nandi::Validation::FailureHelpers
def self.validate(migration)
new(migration).validate
end
def initialize(migration)
@migration = migration
end
def validate
collect_errors(validate_statement_timeout, validate_lock_timeout)
end
private
attr_reader :migration
def validate_statement_timeout
assert(
!migration.disable_statement_timeout? &&
migration.statement_timeout <= statement_timeout_maximum,
"statement timeout must be at most #{statement_timeout_maximum}ms " \
"as it takes an ACCESS EXCLUSIVE lock",
)
end
def validate_lock_timeout
assert(
!migration.disable_lock_timeout? &&
migration.lock_timeout <= lock_timeout_maximum,
"lock timeout must be at most #{lock_timeout_maximum}ms " \
"as it takes an ACCESS EXCLUSIVE lock",
)
end
def statement_timeout_maximum
Nandi.config.access_exclusive_statement_timeout_limit
end
def lock_timeout_maximum
Nandi.config.access_exclusive_lock_timeout_limit
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/timeout_policies/concurrent.rb | lib/nandi/timeout_policies/concurrent.rb | # frozen_string_literal: true
require "nandi"
require "nandi/validation"
require "nandi/validation/failure_helpers"
module Nandi
module TimeoutPolicies
class Concurrent
include Nandi::Validation::FailureHelpers
def self.validate(migration)
new(migration).validate
end
def initialize(migration)
@migration = migration
end
def validate
collect_errors(
validate_statement_timeout,
validate_lock_timeout,
)
end
private
attr_accessor :migration
def validate_statement_timeout
assert(
migration.disable_statement_timeout? || statement_timeout_high_enough,
"statement timeout for concurrent operations " \
"must be at least #{minimum_statement_timeout}",
)
end
def validate_lock_timeout
assert(
migration.disable_lock_timeout? || lock_timeout_high_enough,
"lock timeout for concurrent operations " \
"must be at least #{minimum_lock_timeout}",
)
end
def statement_timeout_high_enough
migration.statement_timeout >= minimum_statement_timeout
end
def lock_timeout_high_enough
migration.lock_timeout >= minimum_lock_timeout
end
def minimum_lock_timeout
Nandi.config.concurrent_lock_timeout_limit
end
def minimum_statement_timeout
Nandi.config.concurrent_statement_timeout_limit
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/instructions/irreversible_migration.rb | lib/nandi/instructions/irreversible_migration.rb | # frozen_string_literal: true
module Nandi
module Instructions
class IrreversibleMigration
def lock
Nandi::Migration::LockWeights::SHARE
end
def procedure
:irreversible_migration
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/instructions/validate_constraint.rb | lib/nandi/instructions/validate_constraint.rb | # frozen_string_literal: true
module Nandi
module Instructions
class ValidateConstraint
attr_reader :table, :name
def initialize(table:, name:)
@table = table
@name = name
end
def lock
Nandi::Migration::LockWeights::SHARE
end
def procedure
:validate_constraint
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/instructions/remove_not_null_constraint.rb | lib/nandi/instructions/remove_not_null_constraint.rb | # frozen_string_literal: true
module Nandi
module Instructions
class RemoveNotNullConstraint
attr_reader :table, :column
def initialize(table:, column:)
@table = table
@column = column
end
def procedure
:remove_not_null_constraint
end
def lock
Nandi::Migration::LockWeights::ACCESS_EXCLUSIVE
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/instructions/add_column.rb | lib/nandi/instructions/add_column.rb | # frozen_string_literal: true
module Nandi
module Instructions
class AddColumn
attr_reader :table, :name, :type, :extra_args
def initialize(table:, name:, type:, **kwargs)
@table = table
@name = name
@type = type
@extra_args = kwargs
end
def procedure
:add_column
end
def lock
Nandi::Migration::LockWeights::ACCESS_EXCLUSIVE
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/instructions/add_index.rb | lib/nandi/instructions/add_index.rb | # frozen_string_literal: true
module Nandi
module Instructions
class AddIndex
def initialize(fields:, table:, **kwargs)
@fields = Array(fields)
@fields = @fields.first if @fields.one?
@table = table
@extra_args = kwargs
end
def procedure
:add_index
end
def extra_args
{
# Overridable defaults
name: name,
# Overrides and extra options
**extra_args_with_default_index_type,
# Mandatory values
algorithm: :concurrently,
}
end
def lock
Nandi::Migration::LockWeights::SHARE
end
attr_reader :table, :fields
private
def name
:"idx_#{table}_on_#{field_names}"
end
def field_names
field_names = fields.respond_to?(:map) ? fields.map(&:to_s).join("_") : fields
field_names.to_s.scan(/\w+/).join("_")
end
def extra_args_with_default_index_type
{
using: :btree,
}.merge(@extra_args)
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/instructions/drop_table.rb | lib/nandi/instructions/drop_table.rb | # frozen_string_literal: true
module Nandi
module Instructions
class DropTable
attr_reader :table
def initialize(table:)
@table = table
end
def procedure
:drop_table
end
def lock
Nandi::Migration::LockWeights::ACCESS_EXCLUSIVE
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/instructions/change_column_default.rb | lib/nandi/instructions/change_column_default.rb | # frozen_string_literal: true
module Nandi
module Instructions
class ChangeColumnDefault
attr_reader :table, :column, :value
def initialize(table:, column:, value:)
@table = table
@column = column
@value = value
end
def procedure
:change_column_default
end
def lock
Nandi::Migration::LockWeights::ACCESS_EXCLUSIVE
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/instructions/remove_column.rb | lib/nandi/instructions/remove_column.rb | # frozen_string_literal: true
module Nandi
module Instructions
class RemoveColumn
attr_reader :table, :name, :extra_args
def initialize(table:, name:, **extra_args)
@table = table
@name = name
@extra_args =
if extra_args.any?
extra_args
else
{}
end
end
def procedure
:remove_column
end
def lock
Nandi::Migration::LockWeights::ACCESS_EXCLUSIVE
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/instructions/create_table.rb | lib/nandi/instructions/create_table.rb | # frozen_string_literal: true
module Nandi
module Instructions
class CreateTable
Column = Struct.new(:name, :type, :args, keyword_init: true)
attr_reader :table, :columns, :timestamps_args, :extra_args
def initialize(table:, columns_block:, **kwargs)
@table = table
columns_reader = ColumnsReader.new
columns_block.call(columns_reader)
@columns = columns_reader.columns
@extra_args = kwargs unless kwargs.empty?
@timestamps_args = columns_reader.timestamps_args
end
def procedure
:create_table
end
def lock
Nandi::Migration::LockWeights::ACCESS_EXCLUSIVE
end
class ColumnsReader
attr_reader :columns, :timestamps_args
TYPES = %i[
bigint
binary
boolean
date
datetime
decimal
float
integer
json
string
text
time
timestamp
virtual
bigserial bit bit_varying box
cidr circle citext
daterange
hstore
inet int4range int8range interval
jsonb
line lseg ltree
macaddr money
numrange
oid
path point polygon primary_key
serial
tsrange tstzrange tsvector
uuid
xml
].freeze
def initialize
@columns = []
@timestamps_args = nil
end
def column(name, type, **args)
@columns << Column.new(name: name, type: type, args: args)
end
def timestamps(**args)
@timestamps_args = args
end
TYPES.each do |type|
define_method type do |name, **args|
column(name, type, **args)
end
end
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/instructions/remove_reference.rb | lib/nandi/instructions/remove_reference.rb | # frozen_string_literal: true
module Nandi
module Instructions
class RemoveReference
attr_reader :table, :ref_name, :extra_args
def initialize(table:, ref_name:, **kwargs)
@table = table
@ref_name = ref_name
@extra_args = kwargs
end
def procedure
:remove_reference
end
def lock
Nandi::Migration::LockWeights::ACCESS_EXCLUSIVE
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/instructions/add_foreign_key.rb | lib/nandi/instructions/add_foreign_key.rb | # frozen_string_literal: true
require "active_support/inflector"
module Nandi
module Instructions
class AddForeignKey
attr_reader :table, :target
def initialize(table:, target:, name: nil, **extra_args)
@table = table
@target = target
@extra_args = extra_args
@name = name
end
def procedure
:add_foreign_key
end
def extra_args
{
**@extra_args,
name: name,
validate: false,
}.compact
end
def lock
Nandi::Migration::LockWeights::ACCESS_EXCLUSIVE
end
private
def name
@name || :"#{table}_#{target}_fk"
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/instructions/remove_index.rb | lib/nandi/instructions/remove_index.rb | # frozen_string_literal: true
module Nandi
module Instructions
class RemoveIndex
def initialize(table:, field:)
@table = table
@field = field
end
def procedure
:remove_index
end
def extra_args
if field.is_a?(Hash)
field.merge(algorithm: :concurrently)
else
{ column: columns, algorithm: :concurrently }
end
end
def lock
Nandi::Migration::LockWeights::SHARE
end
attr_reader :table
private
attr_reader :field
def columns
columns = Array(field)
columns = columns.first if columns.one?
columns
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/instructions/add_check_constraint.rb | lib/nandi/instructions/add_check_constraint.rb | # frozen_string_literal: true
module Nandi
module Instructions
class AddCheckConstraint
attr_reader :table, :name, :check
def initialize(table:, name:, check:)
@table = table
@name = name
@check = check
end
def procedure
:add_check_constraint
end
def lock
Nandi::Migration::LockWeights::ACCESS_EXCLUSIVE
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/instructions/drop_constraint.rb | lib/nandi/instructions/drop_constraint.rb | # frozen_string_literal: true
module Nandi
module Instructions
class DropConstraint
attr_reader :table, :name
def initialize(table:, name:)
@table = table
@name = name
end
def procedure
:drop_constraint
end
def lock
Nandi::Migration::LockWeights::ACCESS_EXCLUSIVE
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/instructions/add_reference.rb | lib/nandi/instructions/add_reference.rb | # frozen_string_literal: true
module Nandi
module Instructions
class AddReference
DEFAULT_EXTRA_ARGS = { index: false }.freeze
attr_reader :table, :ref_name, :extra_args
def initialize(table:, ref_name:, **kwargs)
@table = table
@ref_name = ref_name
@extra_args = DEFAULT_EXTRA_ARGS.merge(kwargs)
end
def procedure
:add_reference
end
def lock
Nandi::Migration::LockWeights::ACCESS_EXCLUSIVE
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/renderers/active_record.rb | lib/nandi/renderers/active_record.rb | # frozen_string_literal: true
require "nandi/renderers/active_record/generate"
module Nandi
module Renderers
module ActiveRecord
def self.generate(migration)
Generate.call(migration)
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/renderers/active_record/instructions.rb | lib/nandi/renderers/active_record/instructions.rb | # frozen_string_literal: true
require "cells"
require "tilt"
require "nandi/formatting"
module Nandi
module Renderers
module ActiveRecord
module Instructions
class Base < ::Cell::ViewModel
include Nandi::Formatting
def template_options_for(_options)
{
suffix: "rb.erb",
template_class: Tilt,
}
end
self.view_paths = [
File.join(__dir__, "../../../templates"),
]
end
class RemoveIndexCell < Base
formatted_property :table
formatted_property :extra_args
end
class AddIndexCell < Base
formatted_property :table
formatted_property :fields
formatted_property :extra_args
end
class CreateTableCell < Base
formatted_property :table
formatted_property :timestamps_args
def timestamps?
!model.timestamps_args.nil?
end
def timestamps_args?
!model.timestamps_args&.empty?
end
def extra_args?
model.extra_args&.any?
end
def timestamps_args
format_value(model.timestamps_args, as_argument: true)
end
def extra_args
format_value(model.extra_args, as_argument: true)
end
def columns
model.columns.map do |c|
::Nandi::Instructions::CreateTable::Column.new(
name: format_value(c.name),
type: format_value(c.type),
).tap do |col|
col.args = format_value(c.args, as_argument: true) unless c.args.empty?
end
end
end
end
class DropTableCell < Base
formatted_property :table
end
class AddColumnCell < Base
formatted_property :table
formatted_property :name
formatted_property :type
formatted_property :extra_args
end
class AddReferenceCell < Base
formatted_property :table
formatted_property :ref_name
formatted_property :extra_args
end
class RemoveReferenceCell < Base
formatted_property :table
formatted_property :ref_name
formatted_property :extra_args
end
class RemoveColumnCell < Base
formatted_property :table
formatted_property :name
formatted_property :extra_args
end
class ChangeColumnDefaultCell < Base
formatted_property :table
formatted_property :column
formatted_property :value
end
class RemoveNotNullConstraintCell < Base
formatted_property :table
formatted_property :column
end
class AddForeignKeyCell < Base
formatted_property :table
formatted_property :target
formatted_property :extra_args
end
class AddCheckConstraintCell < Base
# Because all this stuff goes into a SQL string, we don't need to format
# the values.
property :table
property :name
property :check
end
class ValidateConstraintCell < Base
# Because all this stuff goes into a SQL string, we don't need to format
# the values.
property :table
property :name
end
class DropConstraintCell < Base
# Because all this stuff goes into a SQL string, we don't need to format
# the values.
property :table
property :name
end
class IrreversibleMigrationCell < Base; end
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
gocardless/nandi | https://github.com/gocardless/nandi/blob/bcacafc9bd79a08d4cb7f43e21a776f42d916de2/lib/nandi/renderers/active_record/generate.rb | lib/nandi/renderers/active_record/generate.rb | # frozen_string_literal: true
require "active_record"
require "cell"
require "tilt"
require "nandi/renderers/active_record/instructions"
module Nandi
module Renderers
module ActiveRecord
class Generate < ::Cell::ViewModel
def self.call(*args)
super.call
end
def partials_base
"nandi/renderers/active_record/instructions"
end
def template_options_for(_options)
{
suffix: "rb.erb",
template_class: Tilt,
}
end
self.view_paths = [
File.expand_path("../../../templates", __dir__),
]
def should_disable_ddl_transaction?
[*up_instructions, *down_instructions].
any? { |i| i.procedure.to_s.include?("index") }
end
def activerecord_version
::ActiveRecord::Migration.current_version
end
def render_partial(instruction)
if instruction.respond_to?(:template)
cell(instruction.template, instruction)
else
cell("#{partials_base}/#{instruction.procedure}", instruction)
end
end
property :up_instructions
property :down_instructions
property :name
property :mixins
property :disable_lock_timeout?
property :disable_statement_timeout?
property :lock_timeout
property :statement_timeout
end
end
end
end
| ruby | MIT | bcacafc9bd79a08d4cb7f43e21a776f42d916de2 | 2026-01-04T17:52:04.110442Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/example/step_definitions/first.step.rb | example/step_definitions/first.step.rb | Transform /^#{ORDER}$/ do |order|
order
end
Transform /^background$/ do |background|
"background"
end
#
# This step transform converts "scenario" to "scenario"
#
Transform /^scenario$/ do |scenario|
"scenario"
end
#
# This step definition is all about steps
#
Given /^this (scenario|background|#{ORDER}) step$/ do |step|
puts "step #{order}"
end | ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/example/step_definitions/french_steps.rb | example/step_definitions/french_steps.rb | # encoding: utf-8
Soit /^une calculatrice$/ do
@calc = Calculatrice.new
end
Etantdonné /^qu'on tape (.*)$/ do |n|
@calc.push n.to_i
end
Etantdonné /^que j'entre (\d+) pour le (.*) nombre/ do |n, x|
@calc.push n.to_i
end
Lorsque /^je tape sur la touche "="$/ do
@expected_result = @calc.additionner
end
Lorsqu /on tape additionner/ do
@expected_result = @calc.additionner
end
Alors /le résultat affiché doit être (\d*)/ do |result|
result.to_i.should == @expected_result
end
Alors /le résultat doit être (\d*)/ do |result|
result.to_i.should == @expected_result
end
Soit /^que je tape sur la touche "\+"$/ do
# noop
end | ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/example/step_definitions/struct.rb | example/step_definitions/struct.rb | #
# @see https://github.com/burtlo/yard-cucumber/issues/18
#
CustomerUsageBehavior = Struct.new(:weight, :days, :time, :location, :other_party, :usage_type, :direction, :quantity)
class CustomerProfile
def generate_winner(max=@total_weight)
# blah
end
end | ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/example/step_definitions/example.step.rb | example/step_definitions/example.step.rb |
Transform /^#{CUSTOMER}$/ do |customer|
"a transformed customer"
end
Transform /^an? customer$/ do |customer|
"a transformed customer"
end
Transform /^the customer$/ do |customer|
"the transformed customer"
end
Transform /^(#{ORDER}) customer$/ do |order|
"#{order} customer"
end
Transform /^#{TEDDY_BEAR}$/ do |teddy|
"the tranformed teddy bear"
end
#
# This is a complicated Transform with a comment
#
Transform /^((?:\d{1,2}[\/-]){2}(?:\d\d){1,2})?\s*(\w{3})?\s*(\d{1,2}:\d{2}\s*(?:AM|PM)?)$/ do |date,day,time|
"#{date} #{day} #{time}"
end
#
# Assign a trnasform to a variable to be interpolated later in a step definition
#
SUBSTITUTED_FILE = Transform(/^file '([^']*)'$/) do |filepath|
"Contents loaded from file"
end
Given /^that (#{CUSTOMER}) is a valid customer$/ do |customer|
pending "Customer #{customer} validation"
end
#
# This comment will likely blow {things up}!
#
When /^a customer logs in as username '([^']+)' with password '([^']+)'$/ do |username,password|
Given "that the customer is a valid customer"
pending "Customer logs in with #{username} and #{password}"
end
Then /^I expect them to have logged in (successfully|miserably)$/ do |success|
pending "Validation that the customer has logged in #{success}"
end
When /^the customer logs out$/ do
pending
end
Then /^I expect the customer to be shown the logout page$/ do
pending
end
And /^this (third) defined step definition$/ do |number|
pending
end
And /^the customer has the following details:$/ do |table|
pending "Table of data #{table.hashes}"
end
And /^edits their the (biography) to state:$/ do |section,text|
pending "text_field not present for #{section} #{bio} for this release"
end
Then /I expect (#{CUSTOMER}) to be a member of the '([^']+)' group/ do |customer,product|
pending "Customer #{customer} with product #{product}"
end
#
# Complicated step definition with optional parameters
#
Given /^(?:I create )?an? (?:(active|deactive|inactive|simulated)d?)? ?project(?:[\s,]*(?:with)? ?(?:an?|the)? (?:(?:the size? (?:at|of)? ?(\d+)|named? (?:of )?'([^']+)'|start date (?:of )?((?:(?:\d{1,2}[\/-]){2}(?:\d\d){1,2}))|end date (?:of )?((?:(?:\d{1,2}[\/-]){2}(?:\d\d){1,2}))|user range (?:of )?(\d+-\d+)|description (?:of )?'([^']+)'|nicknamed? (?:of )?'([^']+)')[,\s]*)* ?)?$/ do |state,size,name,start_date,end_date,user_range,description,nickname|
pending "#{state} #{size} #{name} #{start_date} #{end_date} #{user_range} #{description} #{nickname}"
end
#
# The highlighting replacement uses a span which had trouble when blindly using
# a gsub replacement.
#
Given /(a|\d+) ducks? that ha(?:s|ve) (a|\d+) bills?/ do |duck_count,bills_count|
pending
end
Then /I expect the (duck|bird) to (\w+)/ do |animal,verb|
pending
end
#
# This double-quoted step definition caused some problems when being rendered
#
When /^searching the log for the exact match of the message "([^"]+)"$/ do |message|
pending message
end
#
#
#
When /^the step definition has HTML escaped characters like: "([^"]+)"$/ do |characters|
pending characters
end
#
# Step using interpolated transform to replace file reference with contents of file
#
Then /^the (#{SUBSTITUTED_FILE}) will be replaced with the file contents$/ do |content|
pending "File contained #{content}"
end
#
# Some details about the helper method that might be picked up in the documentation.
#
def a_helper_method
puts "performs some operation"
end | ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/example/step_definitions/support/env.rb | example/step_definitions/support/env.rb |
module Environment
module Database
class Connection
end
end
end | ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/example/step_definitions/support/env_support.rb | example/step_definitions/support/env_support.rb |
class SupportClass
end
module Web
module Interface
class CachedReference
end
end
end | ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/example/step_definitions/support/support.rb | example/step_definitions/support/support.rb |
ORDER = /(?:first|second|third)/
TEDDY_BEAR = /teddy bear/
CUSTOMER = /(?:(?:an?|the|#{ORDER}) customer|#{TEDDY_BEAR})/ | ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard-cucumber.rb | lib/yard-cucumber.rb | require 'yard'
require 'cucumber/platform'
require 'gherkin/parser'
require File.dirname(__FILE__) + "/yard-cucumber/version.rb"
require File.dirname(__FILE__) + "/yard/code_objects/cucumber/base.rb"
require File.dirname(__FILE__) + "/yard/code_objects/cucumber/namespace_object.rb"
require File.dirname(__FILE__) + "/yard/code_objects/cucumber/feature.rb"
require File.dirname(__FILE__) + "/yard/code_objects/cucumber/scenario_outline.rb"
require File.dirname(__FILE__) + "/yard/code_objects/cucumber/scenario.rb"
require File.dirname(__FILE__) + "/yard/code_objects/cucumber/step.rb"
require File.dirname(__FILE__) + "/yard/code_objects/cucumber/tag.rb"
require File.dirname(__FILE__) + "/cucumber/city_builder.rb"
require File.dirname(__FILE__) + "/yard/code_objects/step_transformer.rb"
require File.dirname(__FILE__) + "/yard/code_objects/step_definition.rb"
require File.dirname(__FILE__) + "/yard/code_objects/step_transform.rb"
require File.dirname(__FILE__) + "/yard/parser/cucumber/feature.rb"
require File.dirname(__FILE__) + "/yard/handlers/cucumber/base.rb"
require File.dirname(__FILE__) + "/yard/handlers/cucumber/feature_handler.rb"
if RUBY19
require File.dirname(__FILE__) + "/yard/handlers/step_definition_handler.rb"
require File.dirname(__FILE__) + "/yard/handlers/step_transform_handler.rb"
require File.dirname(__FILE__) + "/yard/handlers/constant_transform_handler.rb"
end
require File.dirname(__FILE__) + "/yard/handlers/legacy/step_definition_handler.rb"
require File.dirname(__FILE__) + "/yard/handlers/legacy/step_transform_handler.rb"
#require File.dirname(__FILE__) + "/yard/parser/source_parser.rb"
require File.dirname(__FILE__) + "/yard/templates/helpers/base_helper.rb"
require File.dirname(__FILE__) + "/yard/server/adapter.rb"
require File.dirname(__FILE__) + "/yard/server/commands/list_command.rb"
require File.dirname(__FILE__) + "/yard/server/router.rb"
# This registered template works for yardoc
YARD::Templates::Engine.register_template_path File.dirname(__FILE__) + '/templates'
# The following static paths and templates are for yard server
YARD::Server.register_static_path File.dirname(__FILE__) + "/templates/default/fulldoc/html"
YARD::Server.register_static_path File.dirname(__FILE__) + "/docserver/default/fulldoc/html"
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard-cucumber/version.rb | lib/yard-cucumber/version.rb | module CucumberInTheYARD
VERSION = '4.0.0'
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/code_objects/step_transformer.rb | lib/yard/code_objects/step_transformer.rb | module YARD::CodeObjects
class StepTransformerObject < Base
include Cucumber::LocationHelper
attr_reader :constants, :keyword, :source, :value, :literal_value
attr_accessor :steps, :pending, :substeps
# This defines an escape pattern within a string or regex:
# /^the first #{CONSTANT} step$/
#
# This is used below in the value to process it if there happen to be
# constants defined here.
#
# @note this does not handle the result of method calls
# @note this does not handle multiple constants within the same escaped area
#
def escape_pattern
/#\{\s*(\w+)\s*\}/
end
#
# When requesting a step tranformer object value, process it, if it hasn't
# alredy been processed, replacing any constants that may be lurking within
# the value.
#
# Processing it means looking for any escaped characters that happen to be
# CONSTANTS that could be matched and then replaced. This is done recursively
# as CONSTANTS can be defined with more CONSTANTS.
#
def value
unless @processed
@processed = true
until (nested = constants_from_value).empty?
nested.each {|n| @value.gsub!(value_regex(n),find_value_for_constant(n)) }
end
end
@value
end
#
# Set the literal value and the value of the step definition.
#
# The literal value is as it appears in the step definition file with any
# constants. The value, when retrieved will attempt to replace those
# constants with their regex or string equivalents to hopefully match more
# steps and step definitions.
#
#
def value=(value)
@literal_value = format_source(value)
@value = format_source(value)
@steps = []
value
end
# Generate a regex with the step transformers value
def regex
@regex ||= /#{strip_regex_from(value)}/
end
# Look through the specified data for the escape pattern and return an array
# of those constants found. This defaults to the @value within step transformer
# as it is used internally, however, it can be called externally if it's
# needed somewhere.
def constants_from_value(data=@value)
data.scan(escape_pattern).flatten.collect { |value| value.strip }
end
protected
#
# Looking through all the constants in the registry and returning the value
# with the regex items replaced from the constnat if present
#
def find_value_for_constant(name)
constant = YARD::Registry.all(:constant).find{|c| c.name == name.to_sym }
log.warn "StepTransformer#find_value_for_constant : Could not find the CONSTANT [#{name}] using the string value." unless constant
constant ? strip_regex_from(constant.value) : name
end
# Return a regex of the value
def value_regex(value)
/#\{\s*#{value}\s*\}/
end
# Step the regex starting / and ending / from the value
def strip_regex_from(value)
value.gsub(/^\/|\/$/,'')
end
end
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/code_objects/step_transform.rb | lib/yard/code_objects/step_transform.rb | module YARD::CodeObjects
class StepTransformObject < StepTransformerObject;
end
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/code_objects/step_definition.rb | lib/yard/code_objects/step_definition.rb | module YARD::CodeObjects
class StepDefinitionObject < StepTransformerObject;
end
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/code_objects/cucumber/tag.rb | lib/yard/code_objects/cucumber/tag.rb | module YARD::CodeObjects::Cucumber
class Tag < NamespaceObject
attr_accessor :value, :owners, :total_scenarios
def features
@owners.find_all { |owner| owner.is_a?(Feature) }
end
def scenarios
all = @owners.find_all do |owner|
owner.is_a?(Scenario) || owner.is_a?(ScenarioOutline) || ()
end
@owners.each do |owner|
if owner.is_a?(ScenarioOutline::Examples) && !all.include?(owner.scenario)
all << owner.scenario
end
end
all
end
def indirect_scenarios
@owners.find_all { |owner| owner.is_a?(Feature) }.collect { |feature| feature.scenarios }.flatten
end
def all_scenarios
scenarios + indirect_scenarios
end
end
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/code_objects/cucumber/scenario.rb | lib/yard/code_objects/cucumber/scenario.rb | module YARD::CodeObjects::Cucumber
class Scenario < NamespaceObject
attr_accessor :value, :comments, :keyword, :description, :steps, :tags, :feature
def initialize(namespace, name)
super(namespace, name.to_s.strip)
@comments = @description = @keyword = @value = @feature = nil
@steps = []
@tags = []
end
def background?
@keyword == "Background"
end
def outline?
false
end
end
end | ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/code_objects/cucumber/feature.rb | lib/yard/code_objects/cucumber/feature.rb | module YARD::CodeObjects::Cucumber
class Feature < NamespaceObject
attr_accessor :background, :comments, :description, :keyword, :scenarios, :tags, :value
def total_scenarios
scenarios.count
end
def initialize(namespace, name)
@comments = ""
@scenarios = []
@tags = []
super(namespace, name.to_s.strip)
end
end
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/code_objects/cucumber/step.rb | lib/yard/code_objects/cucumber/step.rb | module YARD::CodeObjects::Cucumber
class Step < Base
attr_accessor :comments,
:definition,
:examples,
:keyword,
:scenario,
:table,
:text,
:transforms,
:value
def initialize(namespace, name)
super(namespace, name.to_s.strip)
@comments = @definition = @description = @keyword = @table = @text = @value = nil
@examples = {}
@transforms = []
end
def has_table?
!@table.nil?
end
def has_text?
!@text.nil?
end
def definition=(stepdef)
@definition = stepdef
unless stepdef.steps.map(&:files).include?(files)
stepdef.steps << self
end
end
def transformed?
!@transforms.empty?
end
end
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/code_objects/cucumber/base.rb | lib/yard/code_objects/cucumber/base.rb | module YARD::CodeObjects::Cucumber
module LocationHelper
def line_number
files.first.last
end
def file
files.first.first if files && !files.empty?
end
def location
"#{file}:#{line_number}"
end
end
class Base < YARD::CodeObjects::Base
include LocationHelper
def path
@value || super
end
end
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/code_objects/cucumber/scenario_outline.rb | lib/yard/code_objects/cucumber/scenario_outline.rb | module YARD::CodeObjects::Cucumber
class ScenarioOutline < NamespaceObject
attr_accessor :value, :comments, :keyword, :description, :steps, :tags, :feature
attr_accessor :scenarios, :examples
def initialize(namespace, name)
super(namespace, name.to_s.strip)
@comments = @description = @value = @feature = nil
@steps = []
@tags = []
@scenarios = []
@examples = []
end
def background?
false
end
def outline?
true
end
def examples?
@examples.find { |example| example.rows }
end
class Examples
attr_accessor :name, :line, :keyword, :comments, :rows, :tags, :scenario
# The first row of the rows contains the headers for the table
def headers
rows.first
end
# The data of the table starts at the second row. When there is no data then
# return a empty string.
def data
rows ? rows[1..-1] : ""
end
def values_for_row(row)
hash = {}
headers.each_with_index do |header, index|
hash[header] = data[row][index]
end
hash
end
def to_hash
hash = {}
rows.each_with_index do |header, index|
hash[header] = rows.collect { |row| row[index] }
end
hash
end
def initialize(parameters = {})
parameters.each { |key, value| send("#{key.to_sym}=", value) if respond_to? "#{key.to_sym}=" }
end
end
end
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/code_objects/cucumber/namespace_object.rb | lib/yard/code_objects/cucumber/namespace_object.rb | module YARD::CodeObjects::Cucumber
class NamespaceObject < YARD::CodeObjects::NamespaceObject
include LocationHelper
def value;
nil;
end
end
class Requirements < NamespaceObject;
end
class FeatureTags < NamespaceObject;
end
class StepTransformersObject < NamespaceObject;
end
class FeatureDirectory < YARD::CodeObjects::NamespaceObject
attr_accessor :description
def initialize(namespace, name)
super(namespace, name)
@description = ""
end
def location
files.first.first if files && !files.empty?
end
def expanded_path
to_s.split('::')[1..-1].join('/')
end
def value;
name;
end
def features
children.find_all { |d| d.is_a?(Feature) }
end
def subdirectories
subdirectories = children.find_all { |d| d.is_a?(FeatureDirectory) }
subdirectories + subdirectories.collect { |s| s.subdirectories }.flatten
end
end
CUCUMBER_NAMESPACE = Requirements.new(:root, "requirements") unless defined?(CUCUMBER_NAMESPACE)
CUCUMBER_TAG_NAMESPACE = FeatureTags.new(CUCUMBER_NAMESPACE, "tags") unless defined?(CUCUMBER_TAG_NAMESPACE)
CUCUMBER_STEPTRANSFORM_NAMESPACE = StepTransformersObject.new(CUCUMBER_NAMESPACE, "step_transformers") unless defined?(CUCUMBER_STEPTRANSFORM_NAMESPACE)
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/handlers/constant_transform_handler.rb | lib/yard/handlers/constant_transform_handler.rb | # There might be a nicer way to decorate this class but with my limited knowledge could only get this handler
# to be applied after the default constant handler by inheriting from the default constant handler.
# This is required so that the value assigned from the transform is not overridden in the registry by the
# default handler
class YARD::Handlers::Ruby::ConstantTransformHandler < YARD::Handlers::Ruby::ConstantHandler
include YARD::Handlers::Ruby::StructHandlerMethods
handles :assign
namespace_only
process do
begin
if statement[1][0][0] == "Transform"
name = statement[0][0][0]
# Move the docstring to the transform statement
statement[1].docstring = statement.docstring
# Set the docstring on the constant to reference the transform that will be processed
statement.docstring = "Reference to {#{YARD::CodeObjects::Cucumber::CUCUMBER_STEPTRANSFORM_NAMESPACE}::#{name} transform}"
value = statement[1][1].source
value = substitute(value)
value = convert_captures(strip_anchors(value))
instance = register ConstantObject.new(namespace, name) {|o| o.source = statement; o.value = value }
# specify the owner so that the transform can use the registered constant's name
parse_block(statement[1], {:owner => instance})
elsif statement[1][0][0] == "ParameterType"
name = statement[0][0][0]
# Move the docstring to the transform statement
statement[1].docstring = statement.docstring
# Set the docstring on the constant to reference the transform that will be processed
statement.docstring = "Reference to {#{YARD::CodeObjects::Cucumber::CUCUMBER_STEPTRANSFORM_NAMESPACE}::#{name} transform}"
value = find(statement, :label, 'regexp:').parent.children[1].source
value = substitute(value)
value = convert_captures(strip_anchors(value))
instance = register ConstantObject.new(namespace, name) {|o| o.source = statement; o.value = value }
# specify the owner so that the transform can use the registered constant's name
parse_block(statement[1], {:owner => instance})
end
rescue
# This supresses any errors where any of the statement elements are out of bounds.
# In this case the or in cases where the object being assigned is not a Transform
# the default constant handler will already have performed the relevant action
end
end
private
def find(node, node_type, value)
node.traverse { |child| return(child) if node_type == child.type && child.source == value }
self
end
# Cucumber's Transform object overrides the to_s function and strips
# the anchor tags ^$ and any captures so that id it is interpolated in a step definition
# the it can appear anywhere in the step without being effected by position or captures
def convert_captures(regexp_source)
regexp_source
.gsub(/(\()(?!\?[<:=!])/,'(?:')
.gsub(/(\(\?<)(?![=!])/,'(?:<')
end
def strip_anchors(regexp_source)
regexp_source.
gsub(/(^\(\/|\/\)$)/, '').
gsub(/(^\^|\$$)/, '')
end
# Support for interpolation in the Transform's Regex
def substitute(data)
until (nested = constants_from_value(data)).empty?
nested.each {|n| data.gsub!(value_regex(n),find_value_for_constant(n)) }
end
data
end
def constants_from_value(data)
escape_pattern = /#\{\s*(\w+)\s*\}/
data.scan(escape_pattern).flatten.collect { |value| value.strip }
end
# Return a regex of the value
def value_regex(value)
/#\{\s*#{value}\s*\}/
end
def find_value_for_constant(name)
constant = YARD::Registry.all(:constant).find{|c| c.name == name.to_sym }
log.warn "ConstantTransformHandler#find_value_for_constant : Could not find the CONSTANT [#{name}] using the string value." unless constant
constant ? strip_regex_from(constant.value) : name
end
# Step the regex starting / and ending / from the value
def strip_regex_from(value)
value.gsub(/^\/|\/$/,'')
end
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/handlers/step_definition_handler.rb | lib/yard/handlers/step_definition_handler.rb | #
# Finds and processes all the step definitions defined in the ruby source
# code. By default the english gherkin language will be parsed.
#
# To override the language you can define the step definitions in the YARD
# configuration file `~./yard/config`:
#
# @example `~/.yard/config` with LOLCatz step definitions
#
# :"yard-cucumber":
# language:
# step_definitions: [ 'WEN', 'I CAN HAZ', 'AN', 'DEN' ]
#
# @example `~/.yard/config` with French step definitions
#
# :"yard-cucumber":
# language:
# step_definitions: [ 'Soit', 'Etantdonné', 'Lorsque', 'Lorsqu', 'Alors', 'Et' ]
#
class YARD::Handlers::Ruby::StepDefinitionHandler < YARD::Handlers::Ruby::Base
def self.default_step_definitions
[ "When", "Given", "And", "Then" ]
end
def self.custom_step_definitions
YARD::Config.options["yard-cucumber"]["language"]["step_definitions"]
end
def self.custom_step_definitions_defined?
YARD::Config.options["yard-cucumber"] and
YARD::Config.options["yard-cucumber"]["language"] and
YARD::Config.options["yard-cucumber"]["language"]["step_definitions"]
end
def self.step_definitions
if custom_step_definitions_defined?
custom_step_definitions
else
default_step_definitions
end
end
step_definitions.each { |step_def| handles method_call(step_def) }
process do
instance = YARD::CodeObjects::StepDefinitionObject.new(step_transform_namespace,step_definition_name) do |o|
o.source = statement.source
o.comments = statement.comments
o.keyword = statement.method_name.source
o.value = statement.parameters.source
o.pending = pending_keyword_used?(statement.block)
end
obj = register instance
parse_block(statement[2],:owner => obj)
end
def pending_keyword
"pending"
end
def pending_command_statement?(line)
(line.type == :command || line.type == :vcall) && line.first.source == pending_keyword
end
def pending_keyword_used?(block)
code_in_block = block.last
code_in_block.find { |line| pending_command_statement?(line) }
end
def step_transform_namespace
YARD::CodeObjects::Cucumber::CUCUMBER_STEPTRANSFORM_NAMESPACE
end
def step_definition_name
"step_definition#{self.class.generate_unique_id}"
end
def self.generate_unique_id
@step_definition_count = @step_definition_count.to_i + 1
end
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/handlers/step_transform_handler.rb | lib/yard/handlers/step_transform_handler.rb |
class YARD::Handlers::Ruby::StepTransformHandler < YARD::Handlers::Ruby::Base
handles method_call(:Transform)
handles method_call(:ParameterType)
process do
nextStatement = nil
instance = YARD::CodeObjects::StepTransformObject.new(step_transform_namespace,step_transformer_name) do |o|
o.source = statement.source
o.comments = statement.comments
o.keyword = statement[0].source
if (o.keyword == 'Transform')
o.value = statement[1].source.gsub(/(^\(?\/|\/\)?$)/, '').gsub(/(^\^|\$$)/, '')
nextStatement = statement[2]
elsif (o.keyword == 'ParameterType')
o.value = find(statement, :label, 'regexp:').parent.children[1].source.gsub(/(^\(?\/|\/\)?$)/, '').gsub(/(^\^|\$$)/, '')
nextStatement = find(statement, :label, 'transformer:').parent.children[1]
end
end
obj = register instance
parse_block(nextStatement,:owner => obj)
end
def step_transform_namespace
YARD::CodeObjects::Cucumber::CUCUMBER_STEPTRANSFORM_NAMESPACE
end
def step_transformer_name
# If the owner is a constant then we get the name of the constant so that the reference from the constant will work
if (owner.is_a?(YARD::CodeObjects::ConstantObject))
owner.name
else
"step_transform#{self.class.generate_unique_id}"
end
end
def self.generate_unique_id
@step_transformer_count = @step_transformer_count.to_i + 1
end
private
def find(node, node_type, value)
node.traverse { |child| return(child) if node_type == child.type && child.source == value }
self
end
end | ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/handlers/legacy/step_definition_handler.rb | lib/yard/handlers/legacy/step_definition_handler.rb | class YARD::Handlers::Ruby::Legacy::StepDefinitionHandler < YARD::Handlers::Ruby::Legacy::Base
STEP_DEFINITION_MATCH = /^((When|Given|And|Then)\s*(\/.+\/)\s+do(?:\s*\|.+\|)?\s*)$/ unless defined?(STEP_DEFINITION_MATCH)
handles STEP_DEFINITION_MATCH
@@unique_name = 0
def process
keyword = statement.tokens.to_s[STEP_DEFINITION_MATCH,2]
step_definition = statement.tokens.to_s[STEP_DEFINITION_MATCH,3]
@@unique_name = @@unique_name + 1
stepdef_instance = StepDefinitionObject.new(YARD::CodeObjects::Cucumber::CUCUMBER_STEPTRANSFORM_NAMESPACE, "definition_#{@@unique_name}") do |o|
o.source = "#{keyword} #{step_definition} do #{statement.block.to_s =~ /^\s*\|.+/ ? '' : "\n "}#{statement.block.to_s}\nend"
o.value = step_definition
o.keyword = keyword
end
obj = register stepdef_instance
parse_block :owner => obj
rescue YARD::Handlers::NamespaceMissingError
end
#
# Step Definitions can contain defined steps within them. While it is likely that they could not
# very easily be parsed because of variables that are only calculated at runtime, it would be nice
# to at least list those in use within a step definition and if you can find a match, go ahead and
# make it
#
def find_steps_defined_in_block(block)
#log.debug "#{block} #{block.class}"
block.each_with_index do |token,index|
#log.debug "Token #{token.class} #{token.text}"
if token.is_a?(YARD::Parser::Ruby::Legacy::RubyToken::TkCONSTANT) &&
token.text =~ /^(given|when|then|and)$/i &&
block[index + 2].is_a?(YARD::Parser::Ruby::Legacy::RubyToken::TkSTRING)
log.debug "Step found in Step Definition: #{block[index + 2].text} "
end
end
end
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/handlers/legacy/step_transform_handler.rb | lib/yard/handlers/legacy/step_transform_handler.rb | class YARD::Handlers::Ruby::Legacy::StepTransformHandler < YARD::Handlers::Ruby::Legacy::Base
STEP_TRANSFORM_MATCH = /^(Transform\s*(\/.+\/)\s+do(?:\s*\|.+\|)?\s*)$/ unless defined?(STEP_TRANSFORM_MATCH)
handles STEP_TRANSFORM_MATCH
@@unique_name = 0
def process
transform = statement.tokens.to_s[STEP_TRANSFORM_MATCH,2]
@@unique_name = @@unique_name + 1
instance = StepTransformObject.new(YARD::CodeObjects::Cucumber::CUCUMBER_STEPTRANSFORM_NAMESPACE, "transform_#{@@unique_name}") do |o|
o.source = "Transform #{transform} do #{statement.block.to_s}\nend"
o.value = transform
o.keyword = "Transform"
end
obj = register instance
parse_block :owner => obj
rescue YARD::Handlers::NamespaceMissingError
end
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/handlers/cucumber/base.rb | lib/yard/handlers/cucumber/base.rb | module YARD
module Handlers
module Cucumber
class Base < Handlers::Base
class << self
include Parser::Cucumber
def handles?(node)
handlers.any? do |a_handler|
#log.debug "YARD::Handlers::Cucumber::Base#handles?(#{node.class})"
node.class == a_handler
end
end
include Parser::Cucumber
end
end
Processor.register_handler_namespace :feature, Cucumber
end
end
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/handlers/cucumber/feature_handler.rb | lib/yard/handlers/cucumber/feature_handler.rb | module YARD
module Handlers
module Cucumber
class FeatureHandler < Base
handles CodeObjects::Cucumber::Feature
def process
#
# Features have already been created when they were parsed. So there
# is no need to process the feature further. Previously this is where
# feature steps were matched to step definitions and step definitions
# were matched to step transforms. This only worked if the feature
# files were were assured to be processed last which was accomplished
# by overriding YARD::SourceParser to make it load file in a similar
# order as Cucumber.
#
# As of YARD 0.7.0 this is no longer necessary as there are callbacks
# that can be registered after all the files have been loaded. That
# callback _after_parse_list_ is defined below and performs the
# functionality described above.
#
end
#
# Register, once, when that when all files are finished to perform
# the final matching of feature steps to step definitions and step
# definitions to step transforms.
#
YARD::Parser::SourceParser.after_parse_list do |files,globals|
# For every feature found in the Registry, find their steps and step
# definitions...
YARD::Registry.all(:feature).each do |feature|
log.debug "Finding #{feature.file} - steps, step definitions, and step transforms"
FeatureHandler.match_steps_to_step_definitions(feature)
end
end
class << self
@@step_definitions = nil
@@step_transforms = nil
def match_steps_to_step_definitions(statement)
# Create a cache of all of the step definitions and the step transforms
@@step_definitions = cache(:stepdefinition) unless @@step_definitions
@@step_transforms = cache(:steptransform) unless @@step_transforms
if statement
# For the background and the scenario, find the steps that have definitions
process_scenario(statement.background) if statement.background
statement.scenarios.each do |scenario|
if scenario.outline?
#log.info "Scenario Outline: #{scenario.value}"
scenario.scenarios.each_with_index do |example,index|
#log.info " * Processing Example #{index + 1}"
process_scenario(example)
end
else
process_scenario(scenario)
end
end
else
log.warn "Empty feature file. A feature failed to process correctly or contains no feature"
end
rescue YARD::Handlers::NamespaceMissingError
rescue Exception => exception
log.error "Skipping feature because an error has occurred."
log.debug "\n#{exception}\n#{exception.backtrace.join("\n")}\n"
end
#
# Store all comparable items with their compare_value as the key and the item as the value
# - Reject any compare values that contain escapes #{} as that means they have unpacked constants
#
def cache(type)
YARD::Registry.all(type).inject({}) do |hash,item|
hash[item.regex] = item if item.regex
hash
end
end
# process a scenario
def process_scenario(scenario)
scenario.steps.each {|step| process_step(step) }
end
# process a step
def process_step(step)
match_step_to_step_definition_and_transforms(step)
end
#
# Given a step object, attempt to match that step to a step
# transformation
#
def match_step_to_step_definition_and_transforms(step)
@@step_definitions.each_pair do |stepdef,stepdef_object|
stepdef_matches = step.value.match(stepdef)
if stepdef_matches
step.definition = stepdef_object
stepdef_matches[1..-1].each do |match|
@@step_transforms.each do |steptrans,steptransform_object|
if steptrans.match(match)
step.transforms << steptransform_object
steptransform_object.steps << step
end
end
end
# Step has been matched to step definition and step transforms
# TODO: If the step were to match again then we would be able to display ambigous step definitions
break
end
end
end
end
end
end
end
end | ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/templates/helpers/base_helper.rb | lib/yard/templates/helpers/base_helper.rb | module YARD::Templates::Helpers
module BaseHelper
def format_object_title(object)
if object.is_a?(YARD::CodeObjects::Cucumber::FeatureTags)
"Tags"
elsif object.is_a?(YARD::CodeObjects::Cucumber::StepTransformersObject)
"Step Definitions and Transforms"
elsif object.is_a?(YARD::CodeObjects::Cucumber::NamespaceObject)
"#{format_object_type(object)}#{object.value ? ": #{object.value}" : ''}"
elsif object.is_a?(YARD::CodeObjects::Cucumber::FeatureDirectory)
"Feature Directory: #{object.name}"
else
case object
when YARD::CodeObjects::RootObject
"Top Level Namespace"
else
format_object_type(object) + ": " + object.path
end
end
end
end
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/server/router.rb | lib/yard/server/router.rb | module YARD
module Server
#
# The YARD::Server::Router needs the following modification,
# so that it will provide routing for the features and tags commands
# to their appropriate definitions
#
Router.class_eval do
alias_method :core_route_list, :route_list
#
# Provide the full list of features and tags
#
def route_list(library, paths)
if paths && !paths.empty? && paths.first =~ /^(?:features|tags)$/
case paths.shift
when "features"; cmd = Commands::ListFeaturesCommand
when "tags"; cmd = Commands::ListTagsCommand
end
cmd.new(final_options(library, paths)).call(request)
else
core_route_list(library,paths)
end
end
end
end
end | ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/server/adapter.rb | lib/yard/server/adapter.rb | module YARD
module Server
class Adapter
class << self
alias_method :yard_setup, :setup
#
# To provide the templates necessary for `yard-cucumber` to integrate
# with YARD the adapter has to around-alias the setup method to place
# the `yard-cucumber` server templates as the last template in the list.
#
# When they are normally loaded with the plugin they cause an error with
# the `yardoc` command. They are also not used because the YARD server
# templates are placed after all plugin templates.
#
def setup
yard_setup
YARD::Templates::Engine.template_paths +=
[File.dirname(__FILE__) + '/../../templates',File.dirname(__FILE__) + '/../../docserver']
end
alias_method :yard_shutdown, :shutdown
#
# Similar to the addition, it is good business to tear down the templates
# that were added by again around-aliasing the shutdown method.
#
def shutdown
yard_shutdown
YARD::Templates::Engine.template_paths -=
[File.dirname(__FILE__) + '/../../templates',File.dirname(__FILE__) + '/../../docserver']
end
end
end
end
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/server/commands/list_command.rb | lib/yard/server/commands/list_command.rb | module YARD
module Server
module Commands
#
# List Features powers the features menu option in `yard server`
#
class ListFeaturesCommand < ListCommand
def type; :features end
def items
Registry.load_all
run_verifier(Registry.all(:feature))
end
end
#
# List Tags powers the tags menu option in `yard server`
#
class ListTagsCommand < ListCommand
def type; :tags end
def items
Registry.load_all
run_verifier(Registry.all(:tag).sort_by {|t| t.value.to_s })
end
end
end
end
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/yard/parser/cucumber/feature.rb | lib/yard/parser/cucumber/feature.rb | module YARD::Parser::Cucumber
class FeatureParser < YARD::Parser::Base
#
# Each found feature found is creates a new FeatureParser
#
# This logic was copied from the logic found in Cucumber to create the builder
# and then set up the formatter and parser. The difference is really the
# custom Cucumber::Parser::CityBuilder that is being used to parse the elements
# of the feature into YARD::CodeObjects.
#
# @param [<String>] source containing the string conents of the feauture file
# @param [<String>] file the filename that contains the source
#
def initialize(source, file = '(stdin)')
@builder = Cucumber::Parser::CityBuilder.new(file)
@tag_counts = {}
@parser = Gherkin::Parser.new(@builder)
@source = source
@file = file
@feature = nil
end
#
# When parse is called, the gherkin parser is executed and all the feature
# elements that are found are sent to the various methods in the
# Cucumber::Parser::CityBuilder. The result of which is the feature element
# that contains all the scenarios, steps, etc. associated with that feature.
#
# @see Cucumber::Parser::CityBuilder
def parse
begin
@parser.parse(@source)
@feature = @builder.ast
return nil if @feature.nil? # Nothing matched
# The parser used the following keywords when parsing the feature
# @feature.language = @parser.i18n_language.get_code_keywords.map {|word| word }
rescue Gherkin::ParserError => e
e.message.insert(0, "#{@file}: ")
warn e
end
self
end
#
# This is not used as all the work is done in the parse method
#
def tokenize
end
#
# The only enumeration that can be done here is returning the feature itself
#
def enumerator
[@feature]
end
end
#
# Register all feature files (.feature) to be processed with the above FeatureParser
YARD::Parser::SourceParser.register_parser_type :feature, FeatureParser, 'feature'
end | ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/templates/default/featuretags/html/setup.rb | lib/templates/default/featuretags/html/setup.rb | def init
super
sections.push :namespace
@namespace = object
end
def namespace
erb(:namespace)
end
def all_tags_by_letter
hash = {}
objects = tags
objects = run_verifier(objects)
objects.each {|o| (hash[o.value.to_s[1,1].upcase] ||= []) << o }
hash
end
def tags
@tags ||= Registry.all(:tag).sort_by {|l| l.value.to_s }
end
def features
@features ||= Registry.all(:feature).sort {|x,y| x.value.to_s <=> y.value.to_s }
end
def feature_tags_with_all_scenario_tags(feature)
feature.tags.collect {|t| t.value} + feature.scenarios.collect {|s| s.tags.collect {|t| t.value} }.flatten.uniq
end
def tagify(tag)
%{<span class="tag" href="#{url_for tag}">#{tag.value}</span>}
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/templates/default/fulldoc/html/setup.rb | lib/templates/default/fulldoc/html/setup.rb | include YARD::Templates::Helpers::HtmlHelper
def init
super
# Additional javascript that power the additional menus, collapsing, etc.
asset "js/cucumber.js", file("js/cucumber.js",true)
serialize_object_type :feature
serialize_object_type :tag
# Generates the requirements splash page with the 'requirements' template
serialize(YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE)
# Generates a page for step definitions and step transforms with the 'steptransformers' template
serialize(YARD::CodeObjects::Cucumber::CUCUMBER_STEPTRANSFORM_NAMESPACE)
# Generates the tags page with the 'featuretags' template
serialize(YARD::CodeObjects::Cucumber::CUCUMBER_TAG_NAMESPACE)
serialize_feature_directories
end
#
# The top-level feature directories. This is affected by the directories that YARD is told to parse.
# All other features in sub-directories are contained under each of these top-level directories.
#
# @example Generating one feature directory
#
# `yardoc 'example/**/*'`
#
# @example Generating two feature directories
#
# `yardoc 'example/**/*' 'example2/**/*'`
#
# @return the feature directories at the root of the Cucumber Namespace.
#
def root_feature_directories
@root_feature_directories ||= YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE.children.find_all {|child| child.is_a?(YARD::CodeObjects::Cucumber::FeatureDirectory)}
end
#
# Generate pages for the objects if there are objects of this type contained
# within the Registry.
#
def serialize_object_type(type)
objects = Registry.all(type.to_sym)
Array(objects).each {|object| serialize(object) }
end
#
# Generates pages for the feature directories found. Starting with all root-level feature
# directories and then recursively finding all child feature directories.
#
def serialize_feature_directories
serialize_feature_directories_recursively(root_feature_directories)
root_feature_directories.each {|directory| serialize(directory) }
end
#
# Generate a page for each Feature Directory. This is called recursively to
# ensure that all feature directories contained as children are rendered to
# pages.
#
def serialize_feature_directories_recursively(namespaces)
namespaces.each do |namespace|
Templates::Engine.with_serializer(namespace, options[:serializer]) do
options[:object] = namespace
T('layout').run(options)
end
serialize_feature_directories_recursively(namespace.children.find_all {|child| child.is_a?(YARD::CodeObjects::Cucumber::FeatureDirectory)})
end
end
# Generate feature list
# @note this method is called automatically by YARD based on the menus defined in the layout
def generate_feature_list
features = Registry.all(:feature)
features_ordered_by_name = features.sort {|x,y| x.value.to_s <=> y.value.to_s }
generate_full_list features_ordered_by_name, :features
end
# Count scenarios for features
def record_feature_scenarios(features)
count_with_examples = 0
features.each do |f|
count_with_examples += f.total_scenarios
end
return count_with_examples
end
# Count scenarios for tags
def record_tagged_scenarios(tags)
scenario_count = 0
count_with_examples = 0
tags.each do |t|
scenario_count += t.all_scenarios.size
count_with_examples += t.total_scenarios
end
end
# Generate tag list
# @note this method is called automatically by YARD based on the menus defined in the layout
def generate_tag_list
tags = Registry.all(:tag)
tags_ordered_by_use = Array(tags).sort {|x,y| y.total_scenarios <=> x.total_scenarios }
record_tagged_scenarios(tags)
generate_full_list tags_ordered_by_use, :tags
end
# Generate a step definition list
# @note this menu is not automatically added until yard configuration has this menu added
# See the layout template method that loads the menus
def generate_stepdefinition_list
generate_full_list YARD::Registry.all(:stepdefinition), :stepdefinitions,
:list_title => "Step Definitions List"
end
# Generate a step list
# @note this menu is not automatically added until yard configuration has this menu added
# See the layout template method that loads the menus
def generate_step_list
generate_full_list YARD::Registry.all(:step), :steps
end
# Generate feature list
# @note this menu is not automatically added until yard configuration has this menu added
# See the layout template method that loads the menus
def generate_featuredirectories_list
directories_ordered_by_name = root_feature_directories.sort {|x,y| x.value.to_s <=> y.value.to_s }
generate_full_list directories_ordered_by_name, :featuredirectories,
:list_title => "Features by Directory",
:list_filename => "featuredirectories_list.html"
end
# Helpler method to generate a full_list page of the specified objects with the
# specified type.
def generate_full_list(objects,type,options = {})
defaults = { :list_title => "#{type.to_s.capitalize} List",
:css_class => "class",
:list_filename => "#{type.to_s.gsub(/s$/,'')}_list.html" }
options = defaults.merge(options)
@items = objects
@list_type = type
@list_title = options[:list_title]
@list_class = options[:css_class]
asset options[:list_filename], erb(:full_list)
end
#
# @note This method overrides YARD's default template class_list method.
#
# The existing YARD 'Class List' search field contains all the YARD namespace objects.
# We, however, do not want the Cucumber Namespace YARD Object (which holds the features,
# tags, etc.) as it is a meta-object.
#
# This method removes the namespace from the root node, generates the class list,
# and then adds it back into the root node.
#
def class_list(root = Registry.root, tree = TreeContext.new)
return super unless root == Registry.root
cucumber_namespace = YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE
root.instance_eval { children.delete cucumber_namespace }
out = super(root)
root.instance_eval { children.push cucumber_namespace }
out
end
#
# Generate a link to the 'All Features' in the features_list.html
#
# When there are no feature directories or multiple top-level feature directories
# then we want to link to the 'Requirements' page
#
# When there are is just one feature directory then we want to link to that directory
#
def all_features_link
features = Registry.all(:feature)
count_with_examples = record_feature_scenarios(features)
if root_feature_directories.length == 0 || root_feature_directories.length > 1
linkify YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE, "All Features (#{count_with_examples})"
else
linkify root_feature_directories.first, "All Features (#{count_with_examples})"
end
end
#
# This method is used to generate a feature directory. This template may call
# this method as well to generate any child feature directories as well.
#
# @param directory [FeatureDirectory] this is the FeatureDirectory to display
# @param padding [Fixnum] this is the pixel value to ident as we want to keep
# pushing in the padding to show the parent relationship
# @param row [String] 'odd' or 'even' to correctly color the row
#
def directory_node(directory,padding,row)
@directory = directory
@padding = padding
@row = row
erb(:directories)
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/templates/default/requirements/html/setup.rb | lib/templates/default/requirements/html/setup.rb | def init
super
sections.push :requirements
@namespace = object
end
def features
@features ||= Registry.all(:feature)
end
def tags
@tags ||= Registry.all(:tag).sort_by {|l| l.value.to_s }
end
def feature_directories
@feature_directories ||= YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE.children.find_all {|child| child.is_a?(YARD::CodeObjects::Cucumber::FeatureDirectory)}
end
def feature_subdirectories
@feature_subdirectories ||= Registry.all(:featuredirectory) - feature_directories
end
def step_transformers
YARD::CodeObjects::Cucumber::CUCUMBER_STEPTRANSFORM_NAMESPACE
end
def step_definitions
@step_definitions ||= YARD::Registry.all(:stepdefinition)
end
def transformers
@transformers ||= YARD::Registry.all(:steptransform)
end
def undefined_steps
@undefined_steps ||= Registry.all(:step).reject {|s| s.definition || s.scenario.outline? }
end
def alpha_table(objects)
@elements = Hash.new
objects = run_verifier(objects)
objects.each {|o| (@elements[o.value.to_s[0,1].upcase] ||= []) << o }
@elements.values.each {|v| v.sort! {|a,b| b.value.to_s <=> a.value.to_s } }
@elements = @elements.sort_by {|l,o| l.to_s }
@elements.each {|letter,objects| objects.sort! {|a,b| b.value.to_s <=> a.value.to_s }}
erb(:alpha_table)
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/templates/default/steptransformers/html/setup.rb | lib/templates/default/steptransformers/html/setup.rb | def init
super
sections.push :index, :stepdefinitions, :steptransforms, :undefinedsteps
end
def step_definitions
@step_definitions ||= begin
YARD::Registry.all(:stepdefinition).sort_by {|definition| definition.steps.length * -1 }
end
end
def step_transforms
@step_transforms ||= begin
YARD::Registry.all(:steptransform).sort_by {|definition| definition.steps.length * -1 }
end
end
def undefined_steps
@undefined_steps ||= begin
unique_steps(Registry.all(:step).reject {|s| s.definition || s.scenario.outline? }).sort_by{|steps| steps.last.length * -1 }
end
end
def stepdefinitions
@item_title = "Step Definitions"
@item_anchor_name = "step_definitions"
@item_type = "step definition"
@items = step_definitions
erb(:header) + erb(:transformers)
end
def steptransforms
@item_title = "Step Transforms"
@item_anchor_name = "step_transforms"
@item_type = "step transform"
@items = step_transforms
erb(:header) + erb(:transformers)
end
def undefinedsteps
@item_title = "Undefined Steps"
@item_anchor_name = "undefined_steps"
@item_type = nil
@items = undefined_steps
erb(:header) + erb(:undefinedsteps)
end
def unique_steps(steps)
uniq_steps = {}
steps.each {|s| (uniq_steps[s.value.to_s] ||= []) << s }
uniq_steps
end
def display_comments_for(item)
begin
T('docstring').run(options.dup.merge({:object => item}))
rescue
log.warn %{An error occurred while attempting to render the comments for: #{item.location} }
return ""
end
end
def link_constants(definition)
value = definition.literal_value.dup
definition.constants_from_value(value).each do |name|
constant = YARD::Registry.all(:constant).find{|c| c.name == name.to_sym }
value.gsub!(/\b#{name}\b/,"<a href='#{url_for(constant)}'>#{name}</a>") if constant
end
value
end
def link_transformed_step(step)
value = step.value.dup
if step.definition
matches = step.value.match(step.definition.regex)
if matches
matches[1..-1].reverse.each_with_index do |match,index|
next if match == nil
transform = step.transforms.find {|transform| transform.regex.match(match) }
value[matches.begin((matches.size - 1) - index)..(matches.end((matches.size - 1) - index) - 1)] = transform ? "<a href='#{url_for(transform)}'>#{h(match)}</a>" : "<span class='match'>#{match}</span>"
end
end
end
value
end | ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/templates/default/feature/html/setup.rb | lib/templates/default/feature/html/setup.rb | def init
super
@feature = object
sections.push :feature
sections.push :scenarios if object.scenarios
end
def background
@scenario = @feature.background
@id = "background"
erb(:scenario)
end
def scenarios
scenarios = ""
if @feature.background
@scenario = @feature.background
@id = "background"
scenarios += erb(:scenario)
end
@feature.scenarios.each_with_index do |scenario,index|
@scenario = scenario
@id = "scenario_#{index}"
scenarios += erb(:scenario)
end
scenarios
end
def highlight_matches(step)
value = step.value.dup
if step.definition
matches = step.value.match(step.definition.regex)
if matches
matches[1..-1].reverse.each_with_index do |match,index|
next if match == nil
value[matches.begin((matches.size - 1) - index)..(matches.end((matches.size - 1) - index) - 1)] = "<span class='match'>#{h(match)}</span>"
end
end
end
value
end
def htmlify_with_newlines(text)
text.split("\n").collect {|c| h(c).gsub(/\s/,' ') }.join("<br/>")
end | ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/templates/default/layout/html/setup.rb | lib/templates/default/layout/html/setup.rb | def init
super
end
#
# Append yard-cucumber stylesheet to yard core stylesheets
#
def stylesheets
super + %w(css/cucumber.css)
end
#
# Append yard-cucumber javascript to yard core javascripts
#
def javascripts
super + %w(js/cucumber.js)
end
#
# Append yard-cucumber specific menus 'features' and 'tags'
#
# 'features' and 'tags' are enabled by default.
#
# 'step definitions' and 'steps' may be enabled by setting up a value in
# yard configuration file '~/.yard/config'
#
# @example `~/.yard.config`
#
# yard-cucumber:
# menus: [ 'features', 'directories', 'tags', 'step definitions', 'steps' ]
#
def menu_lists
current_menu_lists.map {|menu_name| yard_cucumber_menus[menu_name] }.compact + super
end
#
# By default we want to display the 'features' and 'tags' menu but we will allow
# the YARD configuration to override that functionality.
#
def current_menu_lists
@current_menu_lists ||= begin
menus = [ "features", "tags" ]
if YARD::Config.options["yard-cucumber"] and YARD::Config.options["yard-cucumber"]["menus"]
menus = YARD::Config.options["yard-cucumber"]["menus"]
end
menus
end
end
#
# When a menu is specified in the yard configuration file, this hash contains
# the details about the menu necessary for it to be displayed.
#
# @see #menu_lists
#
def yard_cucumber_menus
{ "features" => { :type => 'feature', :title => 'Features', :search_title => 'Features' },
"directories" => { :type => 'featuredirectories', :title => 'Features by Directory', :search_title => 'Features by Directory' },
"tags" => { :type => 'tag', :title => 'Tags', :search_title => 'Tags' },
"step definitions" => { :type => 'stepdefinition', :title => 'Step Definitions', :search_title => 'Step Defs' },
"steps" => { :type => 'step', :title => 'Steps', :search_title => 'Steps' } }
end
#
# @note This method overrides YARD's default layout template's layout method.
#
# The existing YARD layout method generates the url for the nav menu on the left
# side. For YARD-Cucumber objects this will default to the class_list.html.
# which is not what we want for features, tags, etc.
#
# So we override this method and put in some additional logic to figure out the
# correct list to appear in the search. This can be particularly tricky because
#
# This method removes the namespace from the root node, generates the class list,
# and then adds it back into the root node.
#
def layout
@nav_url = url_for_list(!@file || options.index ? 'class' : 'file')
if is_yard_cucumber_object?(object)
@nav_url = rewrite_nav_url(@nav_url)
end
if !object || object.is_a?(String)
@path = nil
elsif @file
@path = @file.path
elsif !object.is_a?(YARD::CodeObjects::NamespaceObject)
@path = object.parent.path
else
@path = object.path
end
erb(:layout)
end
#
# Determine if the object happens to be a CodeObject defined in this gem.
#
# @note quite a few of the classes/modules defined here are not object that we
# would never want to display but it's alright if we match on them.
#
# @return [Boolean] true if the object's class name is one of the CodeObjects
#
def is_yard_cucumber_object?(object)
YARD::CodeObjects::Cucumber.constants.any? {|constant| object.class.name == "YARD::CodeObjects::Cucumber::#{constant}" }
end
#
# The re-write rules will only change the nav link to a new menu if it is a
# a Cucumber CodeObject that we care about and that we have also generated a
# menu for that item.
#
def rewrite_nav_url(nav_url)
if object.is_a?(YARD::CodeObjects::Cucumber::Feature) && current_menu_lists.include?('features')
nav_url.gsub('class_list.html','feature_list.html')
elsif object.is_a?(YARD::CodeObjects::Cucumber::FeatureDirectory) && current_menu_lists.include?('directories')
nav_url.gsub('class_list.html','featuredirectories_list.html')
elsif object.is_a?(YARD::CodeObjects::Cucumber::Tag) && current_menu_lists.include?('tags')
nav_url.gsub('class_list.html','tag_list.html')
elsif object.is_a?(YARD::CodeObjects::Cucumber::Step) && current_menu_lists.include?('steps')
nav_url.gsub('class_list.html','step_list.html')
elsif object.is_a?(YARD::CodeObjects::Cucumber::StepTransformersObject) && current_menu_lists.include?('step definitions')
nav_url.gsub('class_list.html','stepdefinition_list.html')
else
nav_url
end
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/templates/default/tag/html/setup.rb | lib/templates/default/tag/html/setup.rb | def init
super
@tag = object
sections.push :tag
end
def features
@tag.features
end
def scenarios
@tag.scenarios
end
def alpha_table(objects)
@elements = Hash.new
objects = run_verifier(objects)
objects.each {|o| (@elements[o.value.to_s[0,1].upcase] ||= []) << o }
@elements.values.each {|v| v.sort! {|a,b| b.value.to_s <=> a.value.to_s } }
@elements = @elements.sort_by {|l,o| l.to_s }
@elements.each {|letter,objects| objects.sort! {|a,b| b.value.to_s <=> a.value.to_s }}
erb(:alpha_table)
end | ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
burtlo/yard-cucumber | https://github.com/burtlo/yard-cucumber/blob/177e5ad17aa4973660ce646b398118a6408d8913/lib/templates/default/featuredirectory/html/setup.rb | lib/templates/default/featuredirectory/html/setup.rb | def init
super
sections.push :directory
@directory = object
end
def markdown(text)
htmlify(text,:markdown) rescue h(text)
end
def htmlify_with_newlines(text)
text.split("\n").collect {|c| h(c).gsub(/\s/,' ') }.join("<br/>")
end
def directories
@directories ||= @directory.subdirectories
end
def features
@features ||= @directory.features + directories.collect {|d| d.features }.flatten
end
def scenarios
@scenarios ||= features.collect {|feature| feature.scenarios }.flatten
end
def tags
@tags ||= (features.collect{|feature| feature.tags } + scenarios.collect {|scenario| scenario.tags }).flatten.uniq.sort_by {|l| l.value.to_s }
end
def alpha_table(objects)
@elements = Hash.new
objects = run_verifier(objects)
objects.each {|o| (@elements[o.value.to_s[0,1].upcase] ||= []) << o }
@elements.values.each {|v| v.sort! {|a,b| b.value.to_s <=> a.value.to_s } }
@elements = @elements.sort_by {|l,o| l.to_s }
@elements.each {|letter,objects| objects.sort! {|a,b| b.value.to_s <=> a.value.to_s }}
erb(:alpha_table)
end
| ruby | MIT | 177e5ad17aa4973660ce646b398118a6408d8913 | 2026-01-04T17:52:15.257300Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.