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 |
|---|---|---|---|---|---|---|---|---|
flyerhzm/eager_group | https://github.com/flyerhzm/eager_group/blob/7dc79e5705b24e6193e869ab8624c188399b438e/lib/eager_group/preloader/has_many.rb | lib/eager_group/preloader/has_many.rb | # frozen_string_literal: true
module EagerGroup
class Preloader
class HasMany < AggregationFinder
def group_by_foreign_key
reflection.foreign_key
end
def aggregate_hash
scope = reflection.klass.all.tap{|query| query.merge!(definition_scope) if definition_scope }
scope.where(group_by_foreign_key => record_ids).
where(polymophic_as_condition).
group(group_by_foreign_key).
send(definition.aggregation_function, definition.column_name)
end
end
end
end
| ruby | MIT | 7dc79e5705b24e6193e869ab8624c188399b438e | 2026-01-04T17:56:14.651123Z | false |
flyerhzm/eager_group | https://github.com/flyerhzm/eager_group/blob/7dc79e5705b24e6193e869ab8624c188399b438e/lib/eager_group/preloader/many_to_many.rb | lib/eager_group/preloader/many_to_many.rb | # frozen_string_literal: true
module EagerGroup
class Preloader
class ManyToMany < AggregationFinder
def group_by_foreign_key
"#{reflection.join_table}.#{reflection.foreign_key}"
end
def aggregate_hash
scope = klass.joins(reflection.name).tap{|query| query.merge!(definition_scope) if definition_scope}
scope.where(group_by_foreign_key => record_ids).
where(polymophic_as_condition).
group(group_by_foreign_key).
send(definition.aggregation_function, definition.column_name)
end
end
end
end
| ruby | MIT | 7dc79e5705b24e6193e869ab8624c188399b438e | 2026-01-04T17:56:14.651123Z | false |
flyerhzm/eager_group | https://github.com/flyerhzm/eager_group/blob/7dc79e5705b24e6193e869ab8624c188399b438e/lib/eager_group/preloader/has_many_through_many.rb | lib/eager_group/preloader/has_many_through_many.rb | # frozen_string_literal: true
module EagerGroup
class Preloader
class HasManyThroughMany < AggregationFinder
def group_by_foreign_key
"#{reflection.through_reflection.name}.#{reflection.through_reflection.foreign_key}"
end
def aggregate_hash
scope = klass.joins(reflection.name).tap{|query| query.merge!(definition_scope) if definition_scope }
scope.where(group_by_foreign_key => record_ids).
where(polymophic_as_condition).
group(group_by_foreign_key).
send(definition.aggregation_function, definition.column_name)
end
end
end
end
| ruby | MIT | 7dc79e5705b24e6193e869ab8624c188399b438e | 2026-01-04T17:56:14.651123Z | false |
teeparham/gemdiff | https://github.com/teeparham/gemdiff/blob/161f341b14c1386bbaa4ac9266fad345b15fcb31/test/outdated_gem_test.rb | test/outdated_gem_test.rb | # frozen_string_literal: true
require "test_helper"
describe "#initialize" do
it "sets name" do
assert_equal "x", Gemdiff::OutdatedGem.new("x").name
end
it "sets name to current directory when ." do
assert_equal "gemdiff", Gemdiff::OutdatedGem.new(".").name
end
end
describe "#missing_versions?" do
it "returns true" do
assert Gemdiff::OutdatedGem.new("x").missing_versions?
end
it "returns false" do
refute Gemdiff::OutdatedGem.new("x", "1", "2").missing_versions?
end
end
describe "#compare_url" do
it "returns compare url" do
outdated_gem = Gemdiff::OutdatedGem.new("x", "1.0", "2.0")
outdated_gem.stubs repo: "http://github.com/x/x/"
assert_equal "http://github.com/x/x/compare/v1.0...v2.0", outdated_gem.compare_url
end
it "returns compare url with no v for exceptions" do
outdated_gem = Gemdiff::OutdatedGem.new("ffi", "1.9.17", "1.9.18")
outdated_gem.stubs repo: "http://github.com/ffi/ffi"
assert_equal "http://github.com/ffi/ffi/compare/1.9.17...1.9.18", outdated_gem.compare_url
end
it "returns compare url with branch name for new version" do
outdated_gem = Gemdiff::OutdatedGem.new("x", "4.0.0", "main")
outdated_gem.stubs repo: "http://github.com/x/x"
assert_equal "http://github.com/x/x/compare/v4.0.0...main", outdated_gem.compare_url
end
end
describe "#releases_url" do
it "returns releases url" do
outdated_gem = Gemdiff::OutdatedGem.new("x")
outdated_gem.stubs repo: "http://github.com/x/x"
assert_equal "http://github.com/x/x/releases", outdated_gem.releases_url
end
end
describe "#commits_url" do
it "returns commits url" do
outdated_gem = Gemdiff::OutdatedGem.new("x")
outdated_gem.stubs repo: "http://github.com/x/x"
assert_equal "http://github.com/x/x/commits/main", outdated_gem.commits_url
end
end
describe "#compare_message" do
it "returns compare message" do
outdated_gem = Gemdiff::OutdatedGem.new("x", "1", "2")
outdated_gem.stubs repo: "http://github.com/x/x"
assert_equal "x: 2 > 1", outdated_gem.compare_message
end
end
describe "#load_bundle_versions" do
it "returns false if not found" do
mock_inspector = stub(get: nil)
Gemdiff::BundleInspector.stubs new: mock_inspector
refute Gemdiff::OutdatedGem.new("x").load_bundle_versions
end
it "sets versions from gem in bundle" do
mock_outdated_gem = Gemdiff::OutdatedGem.new("y", "1.2.3", "2.3.4")
mock_inspector = stub get: mock_outdated_gem
Gemdiff::BundleInspector.stubs new: mock_inspector
outdated_gem = Gemdiff::OutdatedGem.new("y")
assert outdated_gem.load_bundle_versions
assert_equal "1.2.3", outdated_gem.old_version
assert_equal "2.3.4", outdated_gem.new_version
end
end
describe "#set_versions" do
it "sets nil versions" do
outdated_gem = Gemdiff::OutdatedGem.new("x", "1", "2")
outdated_gem.set_versions nil, nil
assert_nil outdated_gem.old_version
assert_nil outdated_gem.new_version
end
it "sets old, new versions" do
outdated_gem = Gemdiff::OutdatedGem.new("x")
outdated_gem.set_versions "1.2.34", "2.34.56"
assert_equal "1.2.34", outdated_gem.old_version
assert_equal "2.34.56", outdated_gem.new_version
end
it "swaps versions in the wrong order" do
outdated_gem = Gemdiff::OutdatedGem.new("x")
outdated_gem.set_versions "2.34.56", "1.2.34"
assert_equal "1.2.34", outdated_gem.old_version
assert_equal "2.34.56", outdated_gem.new_version
end
it "swaps versions over 10 in the wrong order" do
outdated_gem = Gemdiff::OutdatedGem.new("x")
outdated_gem.set_versions "1.10.0", "1.9.3"
assert_equal "1.9.3", outdated_gem.old_version
assert_equal "1.10.0", outdated_gem.new_version
end
it "swaps versions with main" do
outdated_gem = Gemdiff::OutdatedGem.new("x")
outdated_gem.set_versions "main", "1.9.3"
assert_equal "1.9.3", outdated_gem.old_version
assert_equal "main", outdated_gem.new_version
end
end
describe "#main" do
it "opens main commits url" do
outdated_gem = Gemdiff::OutdatedGem.new("x")
outdated_gem.stubs repo: "http://github.com/x/x"
outdated_gem.expects(:open_url).with("http://github.com/x/x/commits/main")
outdated_gem.main
end
end
describe "#releases" do
it "opens releases url" do
outdated_gem = Gemdiff::OutdatedGem.new("x")
outdated_gem.stubs repo: "http://github.com/x/x"
outdated_gem.expects(:open_url).with("http://github.com/x/x/releases")
outdated_gem.releases
end
end
describe "#compare" do
it "opens compare url" do
outdated_gem = Gemdiff::OutdatedGem.new("x", "1.2.3", "2.3.4")
outdated_gem.stubs repo: "http://github.com/x/x"
outdated_gem.expects(:open_url).with("http://github.com/x/x/compare/v1.2.3...v2.3.4")
outdated_gem.compare
end
end
describe "#open" do
it "opens repo url" do
outdated_gem = Gemdiff::OutdatedGem.new("x")
outdated_gem.stubs repo: "http://github.com/x/x"
outdated_gem.expects(:open_url).with("http://github.com/x/x")
outdated_gem.open
end
end
| ruby | MIT | 161f341b14c1386bbaa4ac9266fad345b15fcb31 | 2026-01-04T17:56:17.422815Z | false |
teeparham/gemdiff | https://github.com/teeparham/gemdiff/blob/161f341b14c1386bbaa4ac9266fad345b15fcb31/test/test_helper.rb | test/test_helper.rb | # frozen_string_literal: true
require "minitest/autorun"
require "mocha/minitest"
require "gemdiff"
begin
require "debug" unless ENV["CI"]
rescue LoadError
# ok
end
| ruby | MIT | 161f341b14c1386bbaa4ac9266fad345b15fcb31 | 2026-01-04T17:56:17.422815Z | false |
teeparham/gemdiff | https://github.com/teeparham/gemdiff/blob/161f341b14c1386bbaa4ac9266fad345b15fcb31/test/repo_finder_test.rb | test/repo_finder_test.rb | # frozen_string_literal: true
require "test_helper"
describe ".github_url" do
it "returns github url from local gemspec" do
Gemdiff::RepoFinder.stubs find_local_gemspec: fake_gemspec("homepage: http://github.com/rails/arel")
assert_equal "https://github.com/rails/arel", Gemdiff::RepoFinder.github_url("arel")
end
it "strips anchors from urls" do
Gemdiff::RepoFinder.stubs \
find_local_gemspec: fake_gemspec("homepage: https://github.com/rubysec/bundler-audit#readme")
assert_equal "https://github.com/rubysec/bundler-audit",
Gemdiff::RepoFinder.github_url("bundler-audit")
end
it "returns github url from remote gemspec" do
Gemdiff::RepoFinder.stubs find_local_gemspec: ""
Gemdiff::RepoFinder.stubs find_remote_gemspec: fake_gemspec("homepage: http://github.com/rails/arel")
assert_equal "https://github.com/rails/arel", Gemdiff::RepoFinder.github_url("arel")
end
it "returns nil when gem does not exist and not found in search" do
Gemdiff::RepoFinder.stubs octokit_client: mock_octokit(nil)
Gemdiff::RepoFinder.stubs gemspec: ""
assert_nil Gemdiff::RepoFinder.github_url("nope")
end
it "returns url from github search when gem does not exist and found in search" do
Gemdiff::RepoFinder.stubs octokit_client: mock_octokit("x/x")
Gemdiff::RepoFinder.stubs gemspec: ""
assert_equal "https://github.com/x/x", Gemdiff::RepoFinder.github_url("x")
end
it "returns url from github search when not in gemspec" do
Gemdiff::RepoFinder.stubs octokit_client: mock_octokit("y/y")
Gemdiff::RepoFinder.stubs gemspec: fake_gemspec
assert_equal "https://github.com/y/y", Gemdiff::RepoFinder.github_url("y")
end
it "returns nil when not in gemspec and not found" do
Gemdiff::RepoFinder.stubs octokit_client: mock_octokit(nil)
Gemdiff::RepoFinder.stubs gemspec: fake_gemspec
assert_nil Gemdiff::RepoFinder.github_url("not_found")
end
it "returns exception url" do
assert_equal "https://github.com/rails/rails", Gemdiff::RepoFinder.github_url("activerecord")
end
it "returns nil for gemspec with no homepage and no description" do
Gemdiff::RepoFinder.stubs octokit_client: mock_octokit(nil)
Gemdiff::RepoFinder.stubs gemspec: NO_DESCRIPTION_GEMSPEC
assert_nil Gemdiff::RepoFinder.github_url("none")
end
it "returns url when # is present in description" do
Gemdiff::RepoFinder.stubs find_local_gemspec: ANCHOR_DESCRIPTION_GEMSPEC
assert_equal "https://github.com/nicksieger/multipart-post",
Gemdiff::RepoFinder.github_url("multipart-post")
end
end
FAKE_GEMSPEC = <<~SPEC
--- !ruby/object:Gem::Specification
name: fake
version: !ruby/object:Gem::Version
version: 1.2.3
date: 2021-01-06 00:00:00.000000000 Z
description: fake
SPEC
NO_DESCRIPTION_GEMSPEC = <<~SPEC
--- !ruby/object:Gem::Specification
name: fake
version: !ruby/object:Gem::Version
version: 1.2.3
description:
SPEC
ANCHOR_DESCRIPTION_GEMSPEC = <<~SPEC
--- !ruby/object:Gem::Specification
name: multipart-post
version: !ruby/object:Gem::Version
version: 2.0.0
description: 'IO values that have #content_type, #original_filename,
and #local_path will be posted as a binary file.'
homepage: https://github.com/nicksieger/multipart-post
licenses:
- MIT
SPEC
private
def mock_octokit(full_name)
mock_items = if full_name.nil?
stub items: []
else
stub items: [stub(full_name: full_name)]
end
stub search_repositories: mock_items
end
def fake_gemspec(extra = "")
[FAKE_GEMSPEC, extra].compact.join("\n")
end
| ruby | MIT | 161f341b14c1386bbaa4ac9266fad345b15fcb31 | 2026-01-04T17:56:17.422815Z | false |
teeparham/gemdiff | https://github.com/teeparham/gemdiff/blob/161f341b14c1386bbaa4ac9266fad345b15fcb31/test/cli_test.rb | test/cli_test.rb | # frozen_string_literal: true
require "test_helper"
def cli
@cli ||= Gemdiff::CLI.new
end
describe "#find" do
it "finds" do
mock_gem "haml"
cli.expects(:puts).with("http://github.com/haml/haml")
cli.find "haml"
end
it "does not find" do
mock_missing_gem
cli.expects(:puts).with("Could not find github repository for notfound.")
cli.find "notfound"
end
end
describe "#open" do
it "opens repo" do
outdated_gem = mock_gem("haml")
cli.expects(:puts).with("http://github.com/haml/haml")
outdated_gem.expects :open
cli.open "haml"
end
end
describe "#releases" do
it "opens releases page" do
outdated_gem = mock_gem("haml")
cli.expects(:puts).with("http://github.com/haml/haml")
outdated_gem.expects :releases
cli.releases "haml"
end
end
describe "#main" do
it "opens commits page" do
outdated_gem = mock_gem("haml")
cli.expects(:puts).with("http://github.com/haml/haml")
outdated_gem.expects :main
cli.main "haml"
end
end
describe "#compare" do
it "opens compare view using bundle" do
outdated_gem = mock_gem("haml")
cli.expects(:puts).with("http://github.com/haml/haml")
outdated_gem.expects(:set_versions).with(nil, nil)
outdated_gem.expects(:missing_versions?).returns(true)
cli.expects(:puts).with(Gemdiff::CLI::CHECKING_FOR_OUTDATED)
outdated_gem.expects(:load_bundle_versions).returns(true)
outdated_gem.expects(:compare_message).returns("compare message")
cli.expects(:puts).with("compare message")
outdated_gem.expects :compare
cli.compare "haml"
end
it "opens compare view with versions" do
outdated_gem = mock_gem("haml")
cli.expects(:puts).with("http://github.com/haml/haml")
outdated_gem.expects(:set_versions).with("4.0.4", "4.0.5")
outdated_gem.expects(:missing_versions?).returns(false)
outdated_gem.expects(:compare_message).returns("compare message")
cli.expects(:puts).with("compare message")
outdated_gem.expects :compare
cli.compare "haml", "4.0.4", "4.0.5"
end
it "returns when the gem is not found" do
mock_missing_gem
cli.expects(:puts).with("Could not find github repository for notfound.")
cli.compare "notfound"
end
end
describe "#each" do
it "does nothing when nothing to update" do
mock_inspector = stub list: [], outdated: ""
Gemdiff::BundleInspector.stubs new: mock_inspector
cli.expects(:puts).with(Gemdiff::CLI::CHECKING_FOR_OUTDATED)
cli.expects(:puts).with("")
cli.each
end
it "compares outdated gems with responses of y" do
outdated_gem = Gemdiff::OutdatedGem.new("haml", "4.0.4", "4.0.5")
mock_inspector = stub list: [outdated_gem], outdated: "outdated"
Gemdiff::BundleInspector.stubs new: mock_inspector
cli.stubs ask: "y"
cli.expects(:puts).with(Gemdiff::CLI::CHECKING_FOR_OUTDATED)
cli.expects(:puts).with("outdated")
cli.expects(:puts).with("haml: 4.0.5 > 4.0.4")
outdated_gem.expects :compare
cli.each
end
it "show compare urls of outdated gems with responses of s" do
outdated_gem = Gemdiff::OutdatedGem.new("haml", "4.0.4", "4.0.5")
mock_inspector = stub list: [outdated_gem], outdated: "outdated"
Gemdiff::BundleInspector.stubs new: mock_inspector
cli.stubs ask: "s"
cli.expects(:puts).with(Gemdiff::CLI::CHECKING_FOR_OUTDATED)
cli.expects(:puts).with("outdated")
cli.expects(:puts).with("haml: 4.0.5 > 4.0.4")
outdated_gem.expects(:compare_url).returns("https://github.com/haml/haml/compare/4.0.4...4.0.5")
cli.expects(:puts).with("https://github.com/haml/haml/compare/4.0.4...4.0.5")
cli.each
end
it "skips outdated gems without responses of y" do
outdated_gem = Gemdiff::OutdatedGem.new("haml", "4.0.4", "4.0.5")
mock_inspector = stub list: [outdated_gem], outdated: "outdated"
Gemdiff::BundleInspector.stubs new: mock_inspector
cli.stubs ask: ""
cli.expects(:puts).with(Gemdiff::CLI::CHECKING_FOR_OUTDATED)
cli.expects(:puts).with("outdated")
cli.expects(:puts).with("haml: 4.0.5 > 4.0.4")
outdated_gem.expects(:compare).never
cli.each
end
end
describe "#list" do
it "does nothing when nothing to update" do
mock_inspector = stub list: [], outdated: ""
Gemdiff::BundleInspector.stubs new: mock_inspector
cli.expects(:puts).with(Gemdiff::CLI::CHECKING_FOR_OUTDATED)
cli.expects(:puts).with("")
cli.expects(:puts).with("\n")
cli.list
end
it "lists outdated gems" do
outdated_gem = Gemdiff::OutdatedGem.new("pundit", "1.0.0", "1.0.1")
mock_inspector = stub list: [outdated_gem], outdated: "outdated"
Gemdiff::BundleInspector.stubs new: mock_inspector
outdated_gem.expects(:compare_url)
.returns("https://github.com/varvet/pundit/compare/v1.0.0...v1.0.1")
cli.expects(:puts).with(Gemdiff::CLI::CHECKING_FOR_OUTDATED)
cli.expects(:puts).with("outdated")
cli.expects(:puts).with("\n").twice
cli.expects(:puts).with("pundit: 1.0.1 > 1.0.0")
cli.expects(:puts).with("https://github.com/varvet/pundit/compare/v1.0.0...v1.0.1")
cli.list
end
end
describe "#update" do
before do
@mock_gem = stub clean?: true, diff: "le diff", show: "le show"
Gemdiff::GemUpdater.stubs new: @mock_gem
end
it "updates the gem and returns with no response" do
cli.stubs ask: ""
cli.expects(:puts).with("Updating haml...")
@mock_gem.expects :update
cli.expects(:puts).with("le diff")
cli.update "haml"
end
it "updates the gem and commits with responses of c" do
cli.stubs ask: "c"
cli.expects(:puts).with("Updating haml...")
@mock_gem.expects :update
cli.expects(:puts).with("le diff")
@mock_gem.expects :commit
cli.expects(:puts).with("\nle show")
cli.update "haml"
end
it "updates the gem and resets with responses of r" do
cli.stubs ask: "r"
cli.expects(:puts).with("Updating haml...")
@mock_gem.expects :update
cli.expects(:puts).with("le diff")
@mock_gem.expects(:reset).returns("le reset")
cli.expects(:puts).with("le reset")
cli.update "haml"
end
end
private
def mock_gem(name)
outdated_gem = stub repo?: true, repo: "http://github.com/#{name}/#{name}"
Gemdiff::OutdatedGem.stubs new: outdated_gem
outdated_gem
end
def mock_missing_gem
outdated_gem = stub repo?: false
Gemdiff::OutdatedGem.stubs new: outdated_gem
outdated_gem
end
| ruby | MIT | 161f341b14c1386bbaa4ac9266fad345b15fcb31 | 2026-01-04T17:56:17.422815Z | false |
teeparham/gemdiff | https://github.com/teeparham/gemdiff/blob/161f341b14c1386bbaa4ac9266fad345b15fcb31/test/bundle_inspector_test.rb | test/bundle_inspector_test.rb | # frozen_string_literal: true
require "test_helper"
def inspector
@inspector ||= Gemdiff::BundleInspector.new
end
describe "#list" do
it "returns outdated gems" do
inspector.stubs bundle_outdated_strict: fake_outdated_parseable
inspector.list.tap do |list|
assert_equal 3, list.size
assert_equal "paperclip", list[0].name
assert_equal "4.2.2", list[0].old_version
assert_equal "4.3.0", list[0].new_version
assert_equal "rails", list[1].name
assert_equal "4.2.1", list[1].old_version
assert_equal "4.2.2", list[1].new_version
assert_equal "web-console", list[2].name
assert_equal "2.1.2", list[2].old_version
assert_equal "2.1.3", list[2].new_version
end
end
it "returns empty list when bundle is up to date" do
inspector.stubs bundle_outdated_strict: fake_up_to_date
assert_empty inspector.list
end
end
describe "#get" do
it "returns single outdated gem" do
inspector.stubs bundle_outdated_strict: fake_outdated_parseable
inspector.get("rails").tap do |gem|
assert_equal "rails", gem.name
assert_equal "4.2.1", gem.old_version
assert_equal "4.2.2", gem.new_version
end
end
it "returns nil when gem is not outdated" do
inspector.stubs bundle_outdated_strict: fake_up_to_date
assert_nil inspector.get("notfound")
end
end
private
def fake_outdated_parseable
<<~OUT
paperclip (newest 4.3.0, installed 4.2.2)
rails (newest 4.2.2, installed 4.2.1, requested ~> 4.2.1)
web-console (newest 2.1.3, installed 2.1.2)
OUT
end
def fake_up_to_date
<<~OUT
OUT
end
| ruby | MIT | 161f341b14c1386bbaa4ac9266fad345b15fcb31 | 2026-01-04T17:56:17.422815Z | false |
teeparham/gemdiff | https://github.com/teeparham/gemdiff/blob/161f341b14c1386bbaa4ac9266fad345b15fcb31/test/gem_updater_test.rb | test/gem_updater_test.rb | # frozen_string_literal: true
require "test_helper"
describe "#update" do
it "updates the gem" do
updater = Gemdiff::GemUpdater.new("x")
updater.expects :bundle_update
updater.update
end
end
describe "#commit" do
it "adds a git commit for a gem update" do
updater = Gemdiff::GemUpdater.new("json")
updater.stubs git_removed_line: "- json (1.8.0)"
updater.stubs git_added_line: "+ json (1.8.1)"
assert_equal "Update json to 1.8.1\n\nhttps://github.com/ruby/json/compare/v1.8.0...v1.8.1",
updater.send(:commit_message)
updater.expects :git_add_and_commit_lockfile
assert updater.commit
end
it "adds a git commit for an update from a specific ref" do
updater = Gemdiff::GemUpdater.new("ffi")
updater.stubs git_removed_line: "- ffi (1.2.3)"
updater.stubs git_added_line: "+ ffi (1.2.4)\n+ ffi"
assert_equal "Update ffi to 1.2.4\n\nhttps://github.com/ffi/ffi/compare/1.2.3...1.2.4",
updater.send(:commit_message)
updater.expects :git_add_and_commit_lockfile
assert updater.commit
end
it "adds a git commit for an update with dependencies" do
updater = Gemdiff::GemUpdater.new("activejob")
updater.stubs git_removed_line: "- activejob (4.2.2)"
updater.stubs git_added_line:
"+ activejob (= 4.2.3)\n+ activejob (4.2.3)\n+ activejob (= 4.2.3)"
assert_equal "Update activejob to 4.2.3\n\nhttps://github.com/rails/rails/compare/v4.2.2...v4.2.3",
updater.send(:commit_message)
updater.expects :git_add_and_commit_lockfile
assert updater.commit
end
end
describe "#reset" do
it "resets Gemfile.lock" do
updater = Gemdiff::GemUpdater.new("x")
updater.expects :git_reset
updater.reset
end
end
describe "#diff" do
it "returns git diff" do
updater = Gemdiff::GemUpdater.new("x")
updater.expects :git_diff
updater.diff
end
end
describe "#show" do
it "returns git show" do
updater = Gemdiff::GemUpdater.new("x")
updater.expects :git_show
updater.show
end
end
describe "#clean?" do
it "returns true for empty diff" do
updater = Gemdiff::GemUpdater.new("x")
updater.stubs git_diff: ""
assert updater.clean?
end
it "returns false for non-empty diff" do
updater = Gemdiff::GemUpdater.new("x")
updater.stubs git_diff: "something"
refute updater.clean?
end
end
| ruby | MIT | 161f341b14c1386bbaa4ac9266fad345b15fcb31 | 2026-01-04T17:56:17.422815Z | false |
teeparham/gemdiff | https://github.com/teeparham/gemdiff/blob/161f341b14c1386bbaa4ac9266fad345b15fcb31/lib/gemdiff.rb | lib/gemdiff.rb | # frozen_string_literal: true
require "gemdiff/version"
require "gemdiff/colorize"
require "gemdiff/cli"
require "gemdiff/bundle_inspector"
require "gemdiff/outdated_gem"
require "gemdiff/repo_finder"
require "gemdiff/gem_updater"
| ruby | MIT | 161f341b14c1386bbaa4ac9266fad345b15fcb31 | 2026-01-04T17:56:17.422815Z | false |
teeparham/gemdiff | https://github.com/teeparham/gemdiff/blob/161f341b14c1386bbaa4ac9266fad345b15fcb31/lib/gemdiff/repo_finder.rb | lib/gemdiff/repo_finder.rb | # frozen_string_literal: true
require "octokit"
require "yaml"
module Gemdiff
module RepoFinder
GITHUB_REPO_REGEX = %r{(https?)://(www.)?github\.com/([\w.%-]*)/([\w.%-]*)}
# rails builds several gems that are not individual projects
# some repos move and the old repo page still exists
# some repos are not mostly ruby so the github search doesn't find them
REPO_EXCEPTIONS =
{
actioncable: "rails/rails",
actionmailer: "rails/rails",
actionpack: "rails/rails",
actionview: "rails/rails",
activejob: "rails/rails",
activemodel: "rails/rails",
activerecord: "rails/rails",
activesupport: "rails/rails",
"aws-sdk-rails": "aws/aws-sdk-rails",
bluepill: "bluepill-rb/bluepill",
chunky_png: "wvanbergen/chunky_png",
"color-schemer": "at-import/color-schemer",
delayed_job: "collectiveidea/delayed_job",
execjs: "rails/execjs",
factory_girl: "thoughtbot/factory_bot",
factory_girl_rails: "thoughtbot/factory_bot_rails",
faraday_middleware: "lostisland/faraday_middleware",
flamegraph: "SamSaffron/flamegraph",
ffi: "ffi/ffi",
"foundation-rails": "zurb/foundation-rails",
"google-protobuf": "protocolbuffers/protobuf",
googleauth: "google/google-auth-library-ruby",
gosu: "jlnr/gosu",
grpc: "google/grpc",
"guard-livereload": "guard/guard-livereload",
i18n: "ruby-i18n/i18n",
"jquery-ujs": "rails/jquery-ujs",
json: "ruby/json",
kaminari: "kaminari/kaminari",
"kaminari-actionview": "kaminari/kaminari",
"kaminari-activerecord": "kaminari/kaminari",
"kaminari-core": "kaminari/kaminari",
"libxml-ruby": "xml4r/libxml-ruby",
"minitest-reporters": "kern/minitest-reporters",
"modular-scale": "modularscale/modularscale-sass",
msgpack: "msgpack/msgpack-ruby",
"net-ssh-gateway": "net-ssh/net-ssh-gateway",
newrelic_rpm: "newrelic/rpm",
nokogiri: "sparklemotion/nokogiri",
nokogumbo: "rubys/nokogumbo",
nsa: "localshred/nsa",
oauth: "oauth-xx/oauth-ruby",
oj: "ohler55/oj",
passenger: "phusion/passenger",
pg: "ged/ruby-pg",
"pkg-config": "ruby-gnome2/pkg-config",
pres: "neighborland/pres",
"pry-doc": "pry/pry-doc",
public_suffix: "weppos/publicsuffix-ruby",
pundit: "varvet/pundit",
"rack-protection": "sinatra/sinatra",
rails_multisite: "discourse/rails_multisite",
railties: "rails/rails",
rake: "ruby/rake",
resque: "resque/resque",
"rb-fsevent": "thibaudgg/rb-fsevent",
"resque-multi-job-forks": "stulentsev/resque-multi-job-forks",
representable: "trailblazer/representable",
rr: "rr/rr",
rspec: "rspec/rspec",
"rspec-core": "rspec/rspec",
"rspec-expectations": "rspec/rspec",
"rspec-mocks": "rspec/rspec",
"rspec-support": "rspec/rspec",
sass: "sass/ruby-sass",
SassyLists: "at-import/SassyLists",
"Sassy-Maps": "at-import/Sassy-Maps",
"sassy-math": "at-import/Sassy-math",
settingslogic: "settingslogic/settingslogic",
sinatra: "sinatra/sinatra",
"sinatra-contrib": "sinatra/sinatra",
stripe: "stripe/stripe-ruby",
thread_safe: "ruby-concurrency/thread_safe",
tolk: "tolk/tolk",
toolkit: "at-import/tookit",
"trailblazer-cells": "trailblazer/trailblazer-cells",
turbolinks: "turbolinks/turbolinks",
"twitter-text": "twitter/twitter-text",
ox: "ohler55/ox",
zeus: "burke/zeus",
}.freeze
PERMITTED_GEMSPEC_CLASSES =
%w[
Gem::Dependency
Gem::Requirement
Gem::Specification
Gem::Version
Symbol
Time
].freeze
class << self
# Try to get the homepage from the gemspec
# If not found, search github
def github_url(gem_name)
gemspec_homepage(gem_name) || search(gem_name)
end
private
def gemspec_homepage(gem_name)
if (full_name = REPO_EXCEPTIONS[gem_name.to_sym])
return github_repo(full_name)
end
yaml = gemspec(gem_name)
return if yaml.to_s.empty?
spec = YAML.safe_load(yaml, permitted_classes: PERMITTED_GEMSPEC_CLASSES)
return clean_url(spec.homepage) if GITHUB_REPO_REGEX.match?(spec.homepage)
match = spec.description.to_s.match(GITHUB_REPO_REGEX)
match && clean_url(match[0])
end
# return https URL with anchors stripped
def clean_url(url)
url.sub(/\Ahttp:/, "https:").partition("#").first
end
def search(gem_name)
query = "#{gem_name} language:ruby in:name"
result = octokit_client.search_repositories(query)
return if result.items.empty?
github_repo result.items.first.full_name
end
def github_repo(full_name)
"https://github.com/#{full_name}"
end
def access_token
ENV["GEMDIFF_GITHUB_TOKEN"] || ENV.fetch("GITHUB_TOKEN", nil)
end
def octokit_client
Octokit::Client.new(access_token: access_token)
end
def gemspec(name)
yaml = find_local_gemspec(name)
return yaml unless yaml.to_s.empty?
find_remote_gemspec(name)
end
def find_local_gemspec(name)
`gem spec #{name}`
end
def find_remote_gemspec(name)
`gem spec -r #{name}`
end
end
end
end
| ruby | MIT | 161f341b14c1386bbaa4ac9266fad345b15fcb31 | 2026-01-04T17:56:17.422815Z | false |
teeparham/gemdiff | https://github.com/teeparham/gemdiff/blob/161f341b14c1386bbaa4ac9266fad345b15fcb31/lib/gemdiff/version.rb | lib/gemdiff/version.rb | # frozen_string_literal: true
module Gemdiff
VERSION = "6.0.2"
end
| ruby | MIT | 161f341b14c1386bbaa4ac9266fad345b15fcb31 | 2026-01-04T17:56:17.422815Z | false |
teeparham/gemdiff | https://github.com/teeparham/gemdiff/blob/161f341b14c1386bbaa4ac9266fad345b15fcb31/lib/gemdiff/bundle_inspector.rb | lib/gemdiff/bundle_inspector.rb | # frozen_string_literal: true
module Gemdiff
class BundleInspector
BUNDLE_OUTDATED_PARSE_REGEX = /\A([^\s]+)\s\(newest\s([^,]+),\sinstalled\s([^,\)]+).*\z/
def list
@list ||=
outdated
.split("\n")
.filter_map { |line| new_outdated_gem(line) }
end
def outdated
@outdated ||= bundle_outdated_strict
end
def get(gem_name)
list.detect { |gem| gem.name == gem_name }
end
private
def bundle_outdated_strict
`bundle outdated --strict --parseable`
end
def new_outdated_gem(line)
return unless (match = BUNDLE_OUTDATED_PARSE_REGEX.match(line))
OutdatedGem.new(match[1], match[2], match[3])
end
end
end
| ruby | MIT | 161f341b14c1386bbaa4ac9266fad345b15fcb31 | 2026-01-04T17:56:17.422815Z | false |
teeparham/gemdiff | https://github.com/teeparham/gemdiff/blob/161f341b14c1386bbaa4ac9266fad345b15fcb31/lib/gemdiff/cli.rb | lib/gemdiff/cli.rb | # frozen_string_literal: true
require "thor"
module Gemdiff
class CLI < Thor
include Thor::Actions
include Colorize
default_task :list
CHECKING_FOR_OUTDATED = "Checking for outdated gems in your bundle..."
NOTHING_TO_UPDATE = "Nothing to update."
WORKING_DIRECTORY_IS_NOT_CLEAN = "Your working directory is not clean. Please commit or stash before updating."
RESPONSES_ALL = %w[s A].freeze
RESPONSES_COMPARE = %w[y A].freeze
desc "find <gem>", "Find the github repository URL for a gem"
def find(gem_name)
outdated_gem = OutdatedGem.new(gem_name)
if outdated_gem.repo?
puts outdated_gem.repo
else
puts "Could not find github repository for #{gem_name}."
end
outdated_gem
end
desc "open <gem>", "Open the github repository for a gem"
def open(gem_name)
find(gem_name).open
end
desc "releases <gem>", "Open the github releases page for a gem"
def releases(gem_name)
find(gem_name).releases
end
desc "main <gem>", "Open the github main branch commits page for a gem"
def main(gem_name)
find(gem_name).main
end
desc "compare <gem> [<old> <new>]", <<~DESC
Compare gem versions. Opens the compare view between the specified new and old versions.
If versions are not specified, your bundle is inspected and the latest version of the
gem is compared with the current version in your bundle.
DESC
def compare(gem_name, old_version = nil, new_version = nil)
outdated_gem = find(gem_name)
return unless outdated_gem.repo?
outdated_gem.set_versions old_version, new_version
if outdated_gem.missing_versions?
puts CHECKING_FOR_OUTDATED
unless outdated_gem.load_bundle_versions
puts "#{gem_name} is not outdated in your bundle. Specify versions."
return
end
end
puts outdated_gem.compare_message
outdated_gem.compare
end
desc "each", "Compare each outdated gem in the bundle. You will be prompted to open each compare view."
def each
puts CHECKING_FOR_OUTDATED
inspector = BundleInspector.new
puts inspector.outdated
all_action = false
inspector.list.each do |outdated_gem|
puts outdated_gem.compare_message
response = all_action || ask("Open? (y to open, x to exit, A to open all, s to show all to stdout, else skip)")
all_action = response if RESPONSES_ALL.include?(response)
outdated_gem.compare if RESPONSES_COMPARE.include?(response)
puts outdated_gem.compare_url if response == "s"
break if response == "x"
end
end
map outdated: :each
desc "list", "List compare URLs for all outdated gems in the bundle."
def list
puts CHECKING_FOR_OUTDATED
inspector = BundleInspector.new
puts inspector.outdated
puts "\n"
inspector.list.each do |outdated_gem|
puts outdated_gem.compare_message
puts outdated_gem.compare_url
puts "\n"
end
end
desc "update <gem>", "Update a gem, show a git diff of the update, and commit or reset"
def update(name)
gem_updater = GemUpdater.new(name)
puts WORKING_DIRECTORY_IS_NOT_CLEAN unless gem_updater.clean?
puts "Updating #{name}..."
gem_updater.update
diff_output = colorize_git_output(gem_updater.diff)
puts diff_output
if diff_output.empty?
puts NOTHING_TO_UPDATE
return
end
response = ask("\nCommit? (c to commit, r to reset, else do nothing)")
case response
when "c"
gem_updater.commit
puts "\n#{colorize_git_output(gem_updater.show)}"
when "r"
puts gem_updater.reset
end
end
end
end
| ruby | MIT | 161f341b14c1386bbaa4ac9266fad345b15fcb31 | 2026-01-04T17:56:17.422815Z | false |
teeparham/gemdiff | https://github.com/teeparham/gemdiff/blob/161f341b14c1386bbaa4ac9266fad345b15fcb31/lib/gemdiff/outdated_gem.rb | lib/gemdiff/outdated_gem.rb | # frozen_string_literal: true
require "launchy"
require "uri"
module Gemdiff
class OutdatedGem
# gems that tag releases with tag names like 1.2.3
# keep it alphabetical
LIST_NO_V = %w[
atomic
autoprefixer-rails
babosa
bullet
cancan
capybara
compass
erubi
ffi
google-api-client
mail
mysql2
net-ssh-gateway
newrelic_rpm
rack
rvm-capistrano
safe_yaml
sass
secure_headers
slack-notifier
signet
twilio-ruby
].freeze
attr_reader :name, :old_version, :new_version
def initialize(name, old_version = nil, new_version = nil)
@name = find_name(name)
set_versions old_version, new_version
end
def set_versions(v_old, v_new)
@old_version, @new_version = old_new(v_old, v_new)
end
def missing_versions?
@old_version.nil? || @new_version.nil?
end
def load_bundle_versions
outdated_gem = BundleInspector.new.get(@name)
return false if outdated_gem.nil?
@old_version ||= outdated_gem.old_version
@new_version ||= outdated_gem.new_version
true
end
def repo
@repo ||= RepoFinder.github_url(@name)
end
def repo?
repo
end
def releases_url
clean_url "#{repo}/releases"
end
def commits_url
clean_url "#{repo}/commits/main"
end
def compare_message
"#{name}: #{new_version} > #{old_version}"
end
def compare_url
clean_url "#{repo}/compare/#{compare_part}"
end
def main
open_url(commits_url) if repo?
end
def releases
open_url(releases_url) if repo?
end
def compare
open_url(compare_url) if repo?
end
def open
open_url(repo) if repo?
end
private
# When ".", use the name of the current directory
def find_name(name)
return File.basename(Dir.getwd) if name == "."
name
end
def clean_url(url)
uri = URI.parse(url)
uri.path.squeeze!("/")
uri.to_s
end
def open_url(url)
Launchy.open(url) do |exception|
warn "Could not open #{url} because #{exception}"
end
end
def compare_part
if compare_type == :no_v
"#{old_version}...#{new_version}"
else
# if the new version is not a number, assume it is a branch name
# and drop the 'v'
prefix = (new_version[0] =~ /^[0-9]/) == 0 ? "v" : ""
"v#{old_version}...#{prefix}#{new_version}"
end
end
def compare_type
if LIST_NO_V.include?(@name)
:no_v
else
:default
end
end
# swap versions if needed
def old_new(v_old, v_new)
return [v_old, v_new] unless v_old && v_new
if v_old == "main" || (Gem::Version.new(v_old) > Gem::Version.new(v_new))
[v_new, v_old]
else
[v_old, v_new]
end
rescue ArgumentError
[v_old, v_new]
end
end
end
| ruby | MIT | 161f341b14c1386bbaa4ac9266fad345b15fcb31 | 2026-01-04T17:56:17.422815Z | false |
teeparham/gemdiff | https://github.com/teeparham/gemdiff/blob/161f341b14c1386bbaa4ac9266fad345b15fcb31/lib/gemdiff/gem_updater.rb | lib/gemdiff/gem_updater.rb | # frozen_string_literal: true
module Gemdiff
class GemUpdater
attr_reader :name
def initialize(name)
@name = name
end
def update
bundle_update
end
def diff
git_diff
end
def show
git_show
end
def commit
git_commit
end
def reset
git_reset
end
def clean?
git_diff.empty?
end
private
def git_show
`git show`
end
def git_diff
`git diff`
end
def git_commit
return false if git_added_line.empty?
git_add_and_commit_lockfile
true
end
def version(changed_line)
changed_line.split("\n").first.split.last.gsub(/[()]/, "")
end
# example returns:
# + rails (4.2.3)
# or
# + sass-rails (4.0.3)
# + sass-rails
# or
# + activejob (= 4.2.3)
# + activejob (4.2.3)
# + activejob (= 4.2.3)
def git_added_line
@git_added_line ||= `git diff | grep ' #{name} (' | grep '+ '`
end
# example returns:
# - json (1.8.1)
def git_removed_line
`git diff | grep ' #{name} (' | grep '\\- '`
end
def commit_message
new_version = version(git_added_line)
outdated = OutdatedGem.new(name, new_version, version(git_removed_line))
"Update #{name} to #{new_version}\n\n#{outdated.compare_url}"
end
def git_add_and_commit_lockfile
`git add Gemfile.lock && git commit -m '#{commit_message}'`
end
def git_reset
`git checkout Gemfile.lock`
end
def bundle_update
`bundle update #{name}`
end
end
end
| ruby | MIT | 161f341b14c1386bbaa4ac9266fad345b15fcb31 | 2026-01-04T17:56:17.422815Z | false |
teeparham/gemdiff | https://github.com/teeparham/gemdiff/blob/161f341b14c1386bbaa4ac9266fad345b15fcb31/lib/gemdiff/colorize.rb | lib/gemdiff/colorize.rb | # frozen_string_literal: true
module Gemdiff
module Colorize
COLORS =
{
red: 31,
green: 32,
yellow: 33,
blue: 34,
magenta: 35,
}.freeze
# works with `git show` and `git diff`
def colorize_git_output(lines)
out = lines.split("\n").map do |line|
if line.start_with?("---", "+++", "diff", "index")
colorize line, :blue
elsif line.start_with?("@@")
colorize line, :magenta
elsif line.start_with?("commit")
colorize line, :yellow
elsif line.start_with?("-")
colorize line, :red
elsif line.start_with?("+")
colorize line, :green
else
line
end
end
out.join("\n")
end
def colorize(string, color)
"\e[#{to_color_code(color)}m#{string}\e[0m"
end
private
def to_color_code(color)
COLORS[color] || 30
end
end
end
| ruby | MIT | 161f341b14c1386bbaa4ac9266fad345b15fcb31 | 2026-01-04T17:56:17.422815Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/test/lib/test_helper.rb | test/lib/test_helper.rb | require "minitest/reporters"
Minitest::Reporters.use!
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/test/lib/nugrant/test_config.rb | test/lib/nugrant/test_config.rb | require 'minitest/autorun'
require 'tmpdir'
require 'nugrant/config'
module Nugrant
class TestConfig < ::Minitest::Test
def setup
@default_param_filename = Nugrant::Config::DEFAULT_PARAMS_FILENAME
@old_working_dir = Dir.getwd()
@user_dir = Nugrant::Config.default_user_path()
@system_dir = Nugrant::Config.default_system_path()
Dir.chdir(Dir.tmpdir())
@current_dir = Dir.getwd()
end
def teardown
Dir.chdir(@old_working_dir)
@old_working_dir = nil
@current_dir = nil
@user_dir = nil
@system_dir = nil
end
def test_default_values
config = Nugrant::Config.new()
assert_equal(@default_param_filename, config.params_filename())
assert_equal("#{@current_dir}/#{@default_param_filename}", config.current_path())
assert_equal("#{@user_dir}/#{@default_param_filename}", config.user_path())
assert_equal("#{@system_dir}/#{@default_param_filename}", config.system_path())
end
def test_custom_params_filename
config = Nugrant::Config.new({:params_filename => ".customparams"})
assert_equal(".customparams", config.params_filename())
assert_equal("#{@current_dir}/.customparams", config.current_path())
assert_equal("#{@user_dir}/.customparams", config.user_path())
assert_equal("#{@system_dir}/.customparams", config.system_path())
end
def test_custom_current_path
config = Nugrant::Config.new({
:params_filename => ".customparams",
:current_path => "#{@user_dir}/.currentcustomparams"
})
assert_equal(".customparams", config.params_filename())
assert_equal("#{@user_dir}/.currentcustomparams", config.current_path())
end
def test_custom_current_path_without_filename
config = Nugrant::Config.new({
:params_filename => ".customparams",
:current_path => "#{@user_dir}"
})
assert_equal(".customparams", config.params_filename())
assert_equal("#{@user_dir}/.customparams", config.current_path())
end
def test_custom_current_path_using_callable
config = Nugrant::Config.new({
:params_filename => ".customparams",
:current_path => lambda do ||
"#{@user_dir}/"
end
})
assert_equal(".customparams", config.params_filename())
assert_equal("#{@user_dir}/.customparams", config.current_path())
end
def test_custom_user_path
config = Nugrant::Config.new({
:params_filename => ".customparams",
:user_path => "#{@system_dir}/.usercustomparams"
})
assert_equal(".customparams", config.params_filename())
assert_equal("#{@system_dir}/.usercustomparams", config.user_path()) end
def test_custom_system_path
config = Nugrant::Config.new({
:params_filename => ".customparams",
:system_path => "#{@current_dir}/.systemcustomparams"
})
assert_equal(".customparams", config.params_filename())
assert_equal("#{@current_dir}/.systemcustomparams", config.system_path())
end
def test_custom_all
config = Nugrant::Config.new({
:params_filename => ".customparams",
:current_path => "#{@user_dir}/.currentcustomparams",
:user_path => "#{@system_dir}/.usercustomparams",
:system_path => "#{@current_dir}/.systemcustomparams"
})
assert_equal(".customparams", config.params_filename())
assert_equal("#{@user_dir}/.currentcustomparams", config.current_path())
assert_equal("#{@system_dir}/.usercustomparams", config.user_path())
assert_equal("#{@current_dir}/.systemcustomparams", config.system_path())
end
def test_nil_current
config = Nugrant::Config.new({
:params_filename => ".customparams",
:current_path => nil,
})
assert_equal("#{@current_dir}/.customparams", config.current_path())
end
def test_nil_user
config = Nugrant::Config.new({
:params_filename => ".customparams",
:user_path => nil,
})
assert_equal("#{@user_dir}/.customparams", config.user_path())
end
def test_nil_system
config = Nugrant::Config.new({
:params_filename => ".customparams",
:system_path => nil,
})
assert_equal("#{@system_dir}/.customparams", config.system_path())
end
def test_invalid_format
assert_raises(ArgumentError) do
Nugrant::Config.new({:params_format => :invalid})
end
end
def test_merge
config1 = Nugrant::Config.new({
:params_filename => ".customparams",
:current_path => nil,
})
config2 = Nugrant::Config.new({
:params_filename => ".overrideparams",
:current_path => "something",
})
config3 = config1.merge(config2)
refute_same(config1, config3)
refute_same(config2, config3)
assert_equal(Nugrant::Config.new({
:params_filename => config2[:params_filename],
:params_format => config2[:params_format],
:current_path => config2[:current_path],
:user_path => config2[:user_path],
:system_path => config2[:system_path],
:array_merge_strategy => config2[:array_merge_strategy],
:key_error => config2[:key_error],
:parse_error => config2[:parse_error],
}), config3)
end
def test_merge!
config1 = Nugrant::Config.new({
:params_filename => ".customparams",
:current_path => nil,
})
config2 = Nugrant::Config.new({
:params_filename => ".overrideparams",
:current_path => "something",
})
config3 = config1.merge!(config2)
assert_same(config1, config3)
refute_same(config2, config3)
assert_equal(Nugrant::Config.new({
:params_filename => config2[:params_filename],
:params_format => config2[:params_format],
:current_path => config2[:current_path],
:user_path => config2[:user_path],
:system_path => config2[:system_path],
:array_merge_strategy => config2[:array_merge_strategy],
:key_error => config2[:key_error],
:parse_error => config2[:parse_error],
}), config3)
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/test/lib/nugrant/test_parameters.rb | test/lib/nugrant/test_parameters.rb | require 'minitest/autorun'
require 'nugrant'
require 'nugrant/helper/parameters'
require 'nugrant/parameters'
module Nugrant
class TestParameters < ::Minitest::Test
@@FORMATS = [:json, :yaml]
@@INVALID_PATH = "impossible_file_path.yamljson.impossible"
def test_params_level_1()
formats.each do |format|
parameters = create_parameters(format, "params_current_1", "params_user_1", "params_system_1")
assert_level(parameters, {
:'1.1.1' => "current",
:'1.1.0' => "current",
:'1.0.1' => "current",
:'0.1.1' => "user",
:'1.0.0' => "current",
:'0.1.0' => "user",
:'0.0.1' => "system",
})
end
end
def test_params_level_2()
formats.each do |format|
parameters = create_parameters(format, "params_current_2", "params_user_2", "params_system_2")
run_second_level(parameters, :'1.1.1', {
:'1.1.1' => "current",
:'1.1.0' => "current",
:'1.0.1' => "current",
:'0.1.1' => "user",
:'1.0.0' => "current",
:'0.1.0' => "user",
:'0.0.1' => "system",
})
run_second_level(parameters, :'1.1.0', {
:'1.1.1' => "current",
:'1.1.0' => "current",
:'1.0.1' => "current",
:'0.1.1' => "user",
:'1.0.0' => "current",
:'0.1.0' => "user",
})
run_second_level(parameters, :'1.0.1', {
:'1.1.1' => "current",
:'1.1.0' => "current",
:'1.0.1' => "current",
:'0.1.1' => "system",
:'1.0.0' => "current",
:'0.0.1' => "system",
})
run_second_level(parameters, :'0.1.1', {
:'1.1.1' => "user",
:'1.1.0' => "user",
:'1.0.1' => "system",
:'0.1.1' => "user",
:'0.1.0' => "user",
:'0.0.1' => "system",
})
run_second_level(parameters, :'1.0.0', {
:'1.1.1' => "current",
:'1.1.0' => "current",
:'1.0.1' => "current",
:'1.0.0' => "current",
})
run_second_level(parameters, :'0.1.0', {
:'1.1.1' => "user",
:'1.1.0' => "user",
:'0.1.1' => "user",
:'0.1.0' => "user",
})
run_second_level(parameters, :'0.0.1', {
:'1.1.1' => "system",
:'1.0.1' => "system",
:'0.1.1' => "system",
:'0.0.1' => "system",
})
assert_key_error(parameters, :'0.0.0')
end
end
def run_second_level(parameters, key, results)
assert_level(parameters.send(key), results)
assert_level(parameters[key], results)
assert_key_error(parameters, :'0.0.0')
end
def test_params_array()
file_path = "params_array"
formats.each do |format|
parameters = create_parameters(format, file_path, invalid_path, invalid_path)
assert_equal(["1", "2", "3"], parameters[:level1][:level2])
end
end
def test_file_nil()
run_test_file_invalid(nil)
end
def test_file_does_not_exist()
run_test_file_invalid("impossible_file_path.yml.impossible")
end
def run_test_file_invalid(invalid_value)
formats.each do |format|
parameters = create_parameters(format, "params_simple", invalid_path, invalid_path)
assert_all_access_equal("value", parameters, "test")
parameters = create_parameters(format, invalid_path, "params_simple", invalid_path)
assert_all_access_equal("value", parameters, "test")
parameters = create_parameters(format, invalid_path, invalid_path, "params_simple")
assert_all_access_equal("value", parameters, "test")
parameters = create_parameters(format, invalid_path, invalid_path, invalid_path)
assert(parameters)
end
end
def test_params_windows_eol()
run_test_params_eol("params_windows_eol")
end
def test_params_unix_eol()
run_test_params_eol("params_unix_eol")
end
def run_test_params_eol(file_path)
formats.each do |format|
parameters = create_parameters(format, file_path, invalid_path, invalid_path)
assert_all_access_equal("value1", parameters, 'level1')
assert_all_access_equal("value2", parameters['level2'], 'first')
end
end
def test_restricted_defaults_usage()
formats.each do |format|
parameters = create_parameters(format, "params_defaults_at_root", invalid_path, invalid_path)
assert_all_access_equal("value", parameters, :defaults)
end
formats.each do |format|
parameters = create_parameters(format, "params_defaults_not_at_root", invalid_path, invalid_path)
assert_all_access_equal("value", parameters.level, :defaults)
end
end
def test_defaults()
formats.each do |format|
parameters = create_parameters(format, "params_simple", invalid_path, invalid_path)
parameters.defaults = {:test => "override1", :level => "new1"}
assert_all_access_equal("value", parameters, 'test')
assert_all_access_equal("new1", parameters, 'level')
end
end
def test_empty_file()
formats.each do |format|
parameters = create_parameters(format, "params_empty", invalid_path, invalid_path)
parameters.defaults = {:test => "value"}
assert_all_access_equal("value", parameters, 'test')
end
end
def test_file_not_hash()
["boolean", "list"].each do |wrong_type|
formats.each do |format|
parameters = create_parameters(format, "params_#{wrong_type}", invalid_path, invalid_path)
parameters.defaults = {:test => "value"}
assert_all_access_equal("value", parameters, 'test')
end
end
end
def test_nil_values()
formats.each do |format|
parameters = create_parameters(format, "params_user_nil_values", invalid_path, invalid_path)
parameters.defaults = {:nil => "Not nil", :deep => {:nil => "Not nil", :deeper => {:nil => "Not nil"}}}
assert_all_access_equal("Not nil", parameters[:deep][:deeper], :nil)
assert_all_access_equal("Not nil", parameters[:deep], :nil)
assert_all_access_equal("Not nil", parameters, :nil)
end
formats.each do |format|
parameters = create_parameters(format, "params_user_nil_values", invalid_path, invalid_path)
assert_all_access_equal(nil, parameters[:deep][:deeper], :nil)
assert_all_access_equal(nil, parameters[:deep], :nil)
assert_all_access_equal(nil, parameters, :nil)
end
end
def test_restricted_keys_are_still_accessible
keys = Helper::Parameters.restricted_keys()
elements = Hash[
keys.map do |key|
[key, "#{key.to_s} - value"]
end
]
parameters = create_parameters(:json, invalid_path, invalid_path, invalid_path)
parameters.defaults = elements
keys.each do |key|
assert_equal("#{key.to_s} - value", parameters[key.to_s], "parameters[#{key.to_s}]")
assert_equal("#{key.to_s} - value", parameters[key.to_sym], "parameters[#{key.to_sym}]")
end
end
def test_enumerable_method_insensitive()
parameters = create_parameters(:json, "params_simple", invalid_path, invalid_path)
parameters.defaults = {"test" => "override1", :level => :new1}
assert_equal(1, parameters.count([:test, "value"]))
assert_equal(1, parameters.count(["test", "value"]))
assert_equal(0, parameters.count(["test"]))
assert_equal(0, parameters.count([]))
assert_equal(0, parameters.count(:a))
assert_equal(0, parameters.count(nil))
assert_equal(0, parameters.find_index([:test, "value"]))
assert_equal(0, parameters.find_index(["test", "value"]))
assert_equal(nil, parameters.find_index(["test"]))
assert_equal(nil, parameters.find_index([]))
assert_equal(nil, parameters.find_index(:a))
assert_equal(nil, parameters.find_index(nil))
assert_equal(0, parameters.find_index() { |key, value| key == :test and value == "value" })
assert_equal(false, parameters.include?([:test, "value"]))
assert_equal(false, parameters.include?(["test", "value"]))
end
def test_hash_method_insensitive()
parameters = create_parameters(:json, "params_simple", invalid_path, invalid_path)
parameters.defaults = {"test" => "override1", :level => :new1}
assert_equal([:test, "value"], parameters.assoc("test"))
assert_equal([:test, "value"], parameters.assoc(:test))
# compare_by_identity ?
parameters.delete("test")
assert_equal(nil, parameters.assoc("test"))
assert_equal(nil, parameters.assoc(:test))
parameters = create_parameters(:json, "params_simple", invalid_path, invalid_path)
parameters.defaults = {"test" => "override1", :level => :new1}
assert_equal([[:test, "value"], [:level, :new1]], parameters.collect {|key, value| [key, value]})
assert_equal("value", parameters.fetch("test"))
assert_equal("value", parameters.fetch("test", "default"))
assert_equal("default", parameters.fetch("unknown", "default"))
assert_equal(true, parameters.has_key?("test"))
assert_equal(true, parameters.has_key?(:test))
assert_equal(true, parameters.include?("test"))
assert_equal(true, parameters.include?(:test))
assert_equal(true, parameters.member?("test"))
assert_equal(true, parameters.member?(:test))
parameters.store("another", "different")
assert_equal(true, parameters.member?("another"))
assert_equal(true, parameters.member?(:another))
end
def test_defaults_not_overwritten_on_array_merge_strategy_change
parameters = create_parameters(:json, "params_array", invalid_path, invalid_path)
parameters.defaults = {"level1" => {"level2" => ["4", "5", "6"]}}
parameters.array_merge_strategy = :concat
assert_equal(["4", "5", "6"], parameters.defaults().level1.level2)
assert_equal(["1", "2", "3", "4", "5", "6"], parameters.level1.level2)
end
def test_merge()
parameters1 = create_parameters(:json, "params_current_1", invalid_path, invalid_path, {
"0.1.1" => "default",
"0.1.0" => "default",
"0.0.1" => "default",
})
parameters2 = create_parameters(:json, "params_current_1", invalid_path, "params_system_1", {
"0.1.0" => "default_overriden",
})
parameters3 = parameters1.merge(parameters2)
refute_same(parameters1, parameters3)
refute_same(parameters2, parameters3)
assert_equal(Nugrant::Parameters, parameters3.class)
assert_level(parameters3, {
:'1.1.1' => "current",
:'1.1.0' => "current",
:'1.0.1' => "current",
:'0.1.1' => "system",
:'1.0.0' => "current",
:'0.1.0' => "default_overriden",
:'0.0.1' => "system",
})
end
def test_merge!()
parameters1 = create_parameters(:json, "params_current_1", invalid_path, invalid_path, {
"0.1.1" => "default",
"0.1.0" => "default",
"0.0.1" => "default",
})
parameters2 = create_parameters(:json, "params_current_1", invalid_path, "params_system_1", {
"0.1.0" => "default_overriden",
})
parameters3 = parameters1.merge!(parameters2)
assert_same(parameters1, parameters3)
refute_same(parameters2, parameters3)
assert_equal(Nugrant::Parameters, parameters3.class)
assert_level(parameters3, {
:'1.1.1' => "current",
:'1.1.0' => "current",
:'1.0.1' => "current",
:'0.1.1' => "system",
:'1.0.0' => "current",
:'0.1.0' => "default_overriden",
:'0.0.1' => "system",
})
end
def test_merge_with_different_array_merge_strategy()
parameters1 = create_parameters(:json, "params_array", invalid_path, invalid_path, {
"level1" => {
"level2" => ["3", "4", "5"]
}
}, :array_merge_strategy => :replace)
parameters2 = create_parameters(:json, "params_array", invalid_path, invalid_path, {
"level1" => {
"level2" => ["3", "6", "7"]
}
}, :array_merge_strategy => :concat)
parameters3 = parameters1.merge(parameters2)
assert_equal(["1", "2", "3", "3", "6", "7"], parameters3.level1.level2)
end
def test_numeric_key_in_yaml_converted_to_symbol()
parameters = create_parameters(:yaml, "params_numeric_key", invalid_path, invalid_path)
assert_equal("value1", parameters.servers[:'1'])
end
## Helpers & Assertions
def create_parameters(format, current_filename, user_filename, system_filename, defaults = {}, options = {})
extension = case format
when :json
"json"
when :yml, :yaml
"yml"
else
raise ArgumentError, "Format [#{format}] is currently not supported"
end
resource_path = File.expand_path("#{File.dirname(__FILE__)}/../../resources/#{format}")
current_path = "#{resource_path}/#{current_filename}.#{extension}" if current_filename
user_path = "#{resource_path}/#{user_filename}.#{extension}" if user_filename
system_path = "#{resource_path}/#{system_filename}.#{extension}" if system_filename
return Nugrant::Parameters.new(defaults, {
:format => format,
:current_path => current_path,
:user_path => user_path,
:system_path => system_path,
:array_merge_strategy => options[:array_merge_strategy]
})
end
def assert_all_access_equal(expected, parameters, key)
assert_equal(expected, parameters.method_missing(key.to_sym), "parameters.#{key.to_s}")
assert_equal(expected, parameters[key.to_s], "parameters[#{key.to_s}]")
assert_equal(expected, parameters[key.to_sym], "parameters[#{key.to_sym}]")
end
def assert_level(parameters, results)
results.each do |key, value|
assert_all_access_equal(value, parameters, key)
end
assert_key_error(parameters, "0.0.0")
end
def assert_key_error(parameters, key)
assert_raises(KeyError) do
parameters[key]
end
end
def formats()
@@FORMATS
end
def invalid_path()
@@INVALID_PATH
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/test/lib/nugrant/test_bag.rb | test/lib/nugrant/test_bag.rb | require 'minitest/autorun'
require 'nugrant/bag'
require 'nugrant/helper/bag'
module Nugrant
class TestBag < ::Minitest::Test
def run_test_bag(parameters)
bag = create_bag(parameters)
assert_bag_equal(parameters, bag)
end
def test_bag()
run_test_bag({:first => "value1", :second => "value2"})
run_test_bag({
:first => {
:level1 => "value1",
:level2 => "value2",
},
:second => {
:level1 => "value3",
:level2 => "value4",
},
:third => "value5"
})
run_test_bag({
:first => {
:level1 => {
:level11 => "value1",
:level12 => "value2",
},
:level2 => {
:level21 => "value3",
:level22 => "value4",
},
:level3 => "value5",
},
:second => {
:level1 => {
:level11 => "value6",
:level12 => "value7",
},
:level2 => {
:level21 => "value8",
:level22 => "value9",
},
:level3 => "value10",
},
:third => "value11"
})
end
def test_undefined_value()
bag = create_bag({:value => "one"})
assert_raises(KeyError) do
bag.invalid_value
end
assert_raises(KeyError) do
bag["invalid_value"]
end
assert_raises(KeyError) do
bag[:invalid_value]
end
end
def test_to_hash()
hash = create_bag({}).to_hash()
assert_is_hash_exclusive(hash)
assert_equal({}, hash)
hash = create_bag({"value" => {:one => "value", "two" => "value"}}).to_hash()
assert_is_hash_exclusive(hash)
assert_is_hash_exclusive(hash[:value])
assert_kind_of(String, hash[:value][:one])
assert_kind_of(String, hash[:value][:two])
assert_equal({:value => {:one => "value", :two => "value"}}, hash)
end
def test_to_hash_array_with_bag()
hash = create_bag({:a => [{:b => "1", :c => [{"d" => "2"}]}]}).to_hash()
assert_is_hash_exclusive(hash)
assert_kind_of(Array, hash[:a])
assert_is_hash_exclusive(hash[:a][0])
assert_kind_of(String, hash[:a][0][:b])
assert_kind_of(Array, hash[:a][0][:c])
assert_is_hash_exclusive(hash[:a][0][:c][0])
assert_kind_of(String, hash[:a][0][:c][0][:d])
assert_equal({:a => [{:b => "1", :c => [{:d => "2"}]}]}, hash)
end
def test_to_hash_array_with_bag_string_key()
hash = create_bag({:a => [{:b => "1", :c => [{"d" => "2"}]}]}).to_hash(use_string_key: true)
assert_is_hash_exclusive(hash)
assert_kind_of(Array, hash["a"])
assert_is_hash_exclusive(hash["a"][0])
assert_kind_of(String, hash["a"][0]["b"])
assert_kind_of(Array, hash["a"][0]["c"])
assert_is_hash_exclusive(hash["a"][0]["c"][0])
assert_kind_of(String, hash["a"][0]["c"][0]["d"])
assert_equal({"a" => [{"b" => "1", "c" => [{"d" => "2"}]}]}, hash)
end
def test_merge_array_replace()
# Replace should be the default case
bag1 = create_bag({"first" => [1, 2]})
bag2 = create_bag({:first => [2, 3]})
bag1.merge!(bag2);
assert_equal({:first => [2, 3]}, bag1.to_hash())
bag1 = create_bag({"first" => [1, 2]})
bag2 = create_bag({:first => "string"})
bag1.merge!(bag2);
assert_equal({:first => "string"}, bag1.to_hash())
end
def test_merge_array_extend()
bag1 = create_bag({"first" => [1, 2]}, :array_merge_strategy => :extend)
bag2 = create_bag({:first => [2, 3]})
bag1.merge!(bag2);
assert_equal({:first => [1, 2, 3]}, bag1.to_hash())
bag1 = create_bag({"first" => [1, 2]}, :array_merge_strategy => :extend)
bag2 = create_bag({:first => "string"})
bag1.merge!(bag2);
assert_equal({:first => "string"}, bag1.to_hash())
end
def test_merge_array_concat()
bag1 = create_bag({"first" => [1, 2]}, :array_merge_strategy => :concat)
bag2 = create_bag({:first => [2, 3]})
bag1.merge!(bag2);
assert_equal({:first => [2, 3, 1, 2]}, bag1.to_hash())
bag1 = create_bag({"first" => [1, 2]}, :array_merge_strategy => :concat)
bag2 = create_bag({:first => "string"})
bag1.merge!(bag2);
assert_equal({:first => "string"}, bag1.to_hash())
end
def test_merge_hash_keeps_indifferent_access
bag1 = create_bag({"first" => {:second => [1, 2]}})
bag1.merge!({:third => "three", "first" => {:second => [3, 4]}})
assert_equal({:first => {:second => [3, 4]}, :third => "three"}, bag1.to_hash())
assert_indifferent_access_equal({:second => [3, 4]}, bag1, :first)
assert_indifferent_access_equal([3, 4], bag1["first"], :second)
end
def test_set_a_slot_with_a_hash_keeps_indifferent_access
bag1 = create_bag({})
bag1["first"] = {:second => [1, 2]}
assert_indifferent_access_equal({:second => [1, 2]}, bag1, :first)
assert_indifferent_access_equal([1, 2], bag1["first"], :second)
end
def test_nil_key()
assert_raises(ArgumentError) do
create_bag({nil => "value"})
end
parameters = create_bag({})
assert_raises(ArgumentError) do
parameters[nil] = 1
end
assert_raises(ArgumentError) do
parameters[nil]
end
assert_raises(ArgumentError) do
parameters.method_missing(nil)
end
end
def test_restricted_keys_are_still_accessible
keys = Helper::Bag.restricted_keys()
bag = create_bag(Hash[
keys.map do |key|
[key, "#{key.to_s} - value"]
end
])
keys.each do |key|
assert_equal("#{key.to_s} - value", bag[key.to_s], "bag[#{key.to_s}]")
assert_equal("#{key.to_s} - value", bag[key.to_sym], "bag[#{key.to_sym}]")
end
end
def test_numeric_keys_converted_to_string
bag1 = create_bag({1 => "value1"})
assert_indifferent_access_equal("value1", bag1, :'1')
end
def test_custom_key_error_handler
bag = create_bag({:value => "one"}, :key_error => Proc.new do |key|
raise IndexError
end)
assert_raises(IndexError) do
bag.invalid_value
end
assert_raises(IndexError) do
bag["invalid_value"]
end
assert_raises(IndexError) do
bag[:invalid_value]
end
end
def test_custom_key_error_handler_returns_value
bag = create_bag({:value => "one"}, :key_error => Proc.new do |key|
"Some value"
end)
assert_indifferent_access_equal("Some value", bag, :invalid_value)
end
def test_walk_bag
bag = create_bag({
:first => {
:level1 => "value1",
:level2 => "value2",
},
:second => {
:level1 => "value3",
:level2 => "value4",
},
:third => "value5"
})
lines = []
bag.walk do |path, key, value|
lines << "Path (#{path}), Key (#{key}), Value (#{value})"
end
assert_equal([
"Path ([:first, :level1]), Key (level1), Value (value1)",
"Path ([:first, :level2]), Key (level2), Value (value2)",
"Path ([:second, :level1]), Key (level1), Value (value3)",
"Path ([:second, :level2]), Key (level2), Value (value4)",
"Path ([:third]), Key (third), Value (value5)",
], lines)
end
def test_merge
bag1 = create_bag({
:first => {
:level1 => "value1",
:level2 => "value2",
},
:second => {
:level1 => "value3",
:level2 => "value4",
},
:third => "value5"
})
bag2 = create_bag({
:first => {
:level2 => "overriden2",
},
:second => {
:level1 => "value3",
:level2 => "value4",
},
:third => "overriden5"
})
bag3 = bag1.merge(bag2)
refute_same(bag1, bag3)
refute_same(bag2, bag3)
assert_equal(Nugrant::Bag, bag3.class)
assert_indifferent_access_equal("value1", bag3['first'], :level1)
assert_indifferent_access_equal("overriden2", bag3['first'], :level2)
assert_indifferent_access_equal("value3", bag3['second'], :level1)
assert_indifferent_access_equal("value4", bag3['second'], :level2)
assert_indifferent_access_equal("overriden5", bag3, :third)
end
def test_merge!
bag1 = create_bag({
:first => {
:level1 => "value1",
:level2 => "value2",
},
:second => {
:level1 => "value3",
:level2 => "value4",
},
:third => "value5"
})
bag2 = create_bag({
:first => {
:level2 => "overriden2",
},
:second => {
:level1 => "value3",
:level2 => "value4",
},
:third => "overriden5"
})
bag3 = bag1.merge!(bag2)
assert_same(bag1, bag3)
refute_same(bag2, bag3)
assert_equal(Nugrant::Bag, bag3.class)
assert_indifferent_access_equal("value1", bag3['first'], :level1)
assert_indifferent_access_equal("overriden2", bag3['first'], :level2)
assert_indifferent_access_equal("value3", bag3['second'], :level1)
assert_indifferent_access_equal("value4", bag3['second'], :level2)
assert_indifferent_access_equal("overriden5", bag3, :third)
end
def test_merge_hash()
bag1 = create_bag({"first" => {:second => [1, 2]}}, :array_merge_strategy => :extend)
bag1.merge!({"first" => {:second => [2, 3]}});
assert_equal({:first => {:second => [1, 2, 3]}}, bag1.to_hash())
end
def test_merge_custom_array_merge_strategy()
bag1 = create_bag({"first" => {:second => [1, 2]}}, :array_merge_strategy => :extend)
bag1.merge!({"first" => {:second => [2, 3]}}, :array_merge_strategy => :replace);
assert_equal({:first => {:second => [2, 3]}}, bag1.to_hash())
end
def test_merge_custom_invalid_array_merge_strategy()
bag1 = create_bag({"first" => {:second => [1, 2]}}, :array_merge_strategy => :extend)
bag2 = bag1.merge({"first" => {:second => [2, 3]}}, :array_merge_strategy => nil);
assert_equal({:first => {:second => [1, 2, 3]}}, bag2.to_hash())
bag2 = bag1.merge({"first" => {:second => [2, 3]}}, :array_merge_strategy => :invalid);
assert_equal({:first => {:second => [1, 2, 3]}}, bag2.to_hash())
end
def test_change_config
bag1 = create_bag({"first" => [1, 2]}, :array_merge_strategy => :extend)
bag2 = create_bag({:first => [2, 3]})
bag3 = bag1.merge!(bag2);
bag3.config = {
:array_merge_strategy => :concat
}
bag3.merge!({"first" => [1, 2, 3]})
assert_equal([1, 2, 3, 1, 2, 3], bag3['first'])
end
def test_indifferent_access_in_array
bag = create_bag({:a => [{:b => 1, :c => [{"d" => 1}]}]})
assert_indifferent_access_equal(1, bag['a'][0]['c'][0], :d)
end
## Helpers & Assertions
def create_bag(elements, options = {})
return Bag.new(elements, options)
end
def assert_is_hash_exclusive(input)
assert_equal(true, input.kind_of?(Hash), "#{input} should be a kind of Hash")
assert_equal(false, input.kind_of?(Bag), "#{input} should not be a kind of Bag")
end
def assert_indifferent_access_equal(expected, bag, key)
assert_symbol_access_equal(expected, bag, key)
assert_string_access_equal(expected, bag, key)
end
def assert_string_access_equal(expected, bag, key)
assert_equal(expected, bag[key.to_s], "bag[#{key.to_s}]")
end
def assert_symbol_access_equal(expected, bag, key)
assert_equal(expected, bag.method_missing(key.to_sym), "bag.#{key.to_sym}")
assert_equal(expected, bag[key.to_sym], "bag[#{key.to_sym}]")
end
def assert_indifferent_access_bag_equal(expected, bag, key)
assert_string_access_bag_equal(expected, bag, key)
assert_symbol_access_bag_equal(expected, bag, key)
end
def assert_string_access_bag_equal(expected, bag, key)
assert_bag_equal(expected, bag[key.to_s])
end
def assert_symbol_access_bag_equal(expected, bag, key)
assert_bag_equal(expected, bag.method_missing(key.to_sym))
assert_bag_equal(expected, bag[key.to_sym])
end
def assert_bag_equal(expected, bag)
assert_kind_of(Bag, bag)
expected.each do |key, expected_value|
if not expected_value.kind_of?(Hash)
assert_indifferent_access_equal(expected_value, bag, key)
next
end
assert_indifferent_access_bag_equal(expected_value, bag, key)
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/test/lib/nugrant/helper/test_parameters.rb | test/lib/nugrant/helper/test_parameters.rb | require 'minitest/autorun'
require 'nugrant/bag'
require 'nugrant/helper/parameters'
module Nugrant
module Helper
class TestParameters < ::Minitest::Test
def test_restricted_keys_contains_hash_ones
keys = Helper::Parameters.restricted_keys()
Nugrant::Bag.instance_methods.each do |method|
assert_includes(keys, method, "Restricted keys must include Nugrant::Bag method #{method}")
end
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/test/lib/nugrant/helper/test_stack.rb | test/lib/nugrant/helper/test_stack.rb | require 'minitest/autorun'
require 'nugrant/helper/stack'
module Nugrant
module Helper
class TestStack < ::Minitest::Test
def create_stack(options = {})
pattern = options[:pattern] || "Vagrantfile:%s"
count = options[:count] || 4
stack = []
(0..count).each do |index|
stack << pattern.gsub("%s", index.to_s())
end
stack
end
def create_location(name, line)
resource_path = File.expand_path("#{File.dirname(__FILE__)}/../../../resources/vagrantfiles")
{:file => "#{resource_path}/#{name}", :line => line}
end
def assert_error_location(expected, entry, matcher = nil)
assert_equal(expected, Stack::extract_error_location(entry, :matcher => matcher), "Not exact error location")
end
def assert_error_region(expected, region)
expected_lines = expected.split("\n")
region_lines = region.split("\n")
expected_count = expected_lines.length()
actual_count = region_lines.length()
assert_equal(expected_count, actual_count, "Region different line count")
expected_lines.each_with_index do |expected_line, index|
assert_equal(expected_line.strip(), region_lines[index].strip(), "Line ##{index} are not equals")
end
end
def test_fetch_error_region_from_location()
location = create_location("v2.defaults_using_symbol", 4)
error_region = Stack::fetch_error_region_from_location(location)
expected_region = <<-EOT
1: Vagrant.configure("2") do |config|
2: config.user.defaults = {
3: :single => 1,
4:>> :local => {
5: :first => "value1",
6: :second => "value2"
7: }
8: }
EOT
assert_error_region(expected_region, error_region)
end
def test_fetch_error_region_from_location_custom_prefix()
location = create_location("v2.defaults_using_symbol", 4)
error_region = Stack::fetch_error_region_from_location(location, :prefix => "**")
expected_region = <<-EOT
**1: Vagrant.configure(\"2\") do |config|
**2: config.user.defaults = {
**3: :single => 1,
**4:>> :local => {
**5: :first => "value1",
**6: :second => "value2"
**7: }
**8: }
EOT
assert_error_region(expected_region, error_region)
end
def test_fetch_error_region_from_location_custom_width()
location = create_location("v2.defaults_using_symbol", 4)
error_region = Stack::fetch_error_region_from_location(location, :width => 2)
expected_region = <<-EOT
2: config.user.defaults = {
3: :single => 1,
4:>> :local => {
5: :first => "value1",
6: :second => "value2"
EOT
assert_error_region(expected_region, error_region)
end
def test_fetch_error_region_from_location_wrong_location()
location = {:file => nil, :line => nil}
assert_equal("Unknown", Stack::fetch_error_region_from_location(location))
assert_equal("Failed", Stack::fetch_error_region_from_location(location, :unknown => "Failed"))
location = {:file => "Vagrantfile", :line => nil}
assert_equal("Vagrantfile", Stack::fetch_error_region_from_location(location))
location = {:file => "NonExistingVagrantfile", :line => 4}
assert_equal("NonExistingVagrantfile:4", Stack::fetch_error_region_from_location(location))
end
def test_find_entry()
entries = ["First", "Second:", "Third:a", "Fourth:4"]
assert_equal("Fourth:4", Stack::find_entry(entries))
assert_equal("Third:a", Stack::find_entry(entries, :matcher => /^(.+):([a-z]+)/))
end
def test_extract_error_location_default_matcher()
# Matches
assert_error_location({:file => "/work/irb/workspace.rb", :line => 80}, "/work/irb/workspace.rb:80:in `eval'")
assert_error_location({:file => "workspace.rb", :line => 80}, "workspace.rb:80:in `eval'")
assert_error_location({:file => "/work/irb/workspace.rb", :line => 80}, "/work/irb/workspace.rb:80")
# No match
assert_error_location({:file => nil, :line => nil}, "/work/irb/workspace.rb?80")
assert_error_location({:file => nil, :line => nil}, "/work/irb/workspace.rb")
assert_error_location({:file =>nil, :line => nil}, "")
end
def test_extract_error_location_custom_matcher()
# Matches
assert_error_location(
{:file => "/work/Vagrantfile", :line => 80},
"/work/Vagrantfile:80:in `eval'",
/(.*Vagrantfile):([0-9]+)/
)
assert_error_location(
{:file => "Vagrantfile", :line => 80},
"Vagrantfile:80:in `eval'",
/(.*Vagrantfile):([0-9]+)/
)
assert_error_location(
{:file => "/work/irb/Vagrantfile", :line => 80},
"/work/irb/Vagrantfile:80",
/(.*Vagrantfile):([0-9]+)/
)
# Partial match
assert_error_location(
{:file => "/work/Vagrantfile", :line => nil},
"/work/Vagrantfile:80:in `eval'",
/(.*Vagrantfile)/
)
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/test/lib/nugrant/helper/test_bag.rb | test/lib/nugrant/helper/test_bag.rb | require 'minitest/autorun'
require 'nugrant/helper/bag'
module Nugrant
module Helper
class TestBag < ::Minitest::Test
def test_restricted_keys_contains_hash_ones
keys = Helper::Bag.restricted_keys()
Hash.instance_methods.each do |method|
assert_includes(keys, method, "Restricted keys must include Hash method #{method}")
end
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/test/lib/nugrant/helper/env/test_exporter.rb | test/lib/nugrant/helper/env/test_exporter.rb | require 'minitest/autorun'
require 'nugrant/bag'
require 'nugrant/helper/env/exporter'
module Nugrant
module Helper
module Env
class TestExporter < ::Minitest::Test
def create_bag(parameters)
return Nugrant::Bag.new(parameters)
end
def assert_export(expected, key, value, options = {})
actual = Env::Exporter.command(:export, key, value, options)
assert_equal(expected, actual)
end
def assert_unset(expected, key, options = {})
actual = Env::Exporter.command(:unset, key, options)
assert_equal(expected, actual)
end
def assert_autoenv_exporter(expected, bag, options = {})
io = StringIO.new()
Env::Exporter.autoenv_exporter(bag, options.merge({:io => io}))
actual = io.string().split(/\r?\n/)
assert_equal(expected, actual)
end
def assert_script_exporter(expected, bag, options = {})
io = StringIO.new()
Env::Exporter.script_exporter(bag, options.merge({:io => io}))
actual = io.string().split(/\r?\n/)
assert_equal(expected, actual)
end
def assert_terminal_exporter(expected, bag, options = {})
io = StringIO.new()
Env::Exporter.terminal_exporter(bag, options.merge({:io => io}))
actual = io.string().split(/\r?\n/)
assert_equal(expected, actual)
end
def assert_unset_commands(expected, bag, options = {})
actual = Env::Exporter.unset_commands(bag, options)
assert_equal(expected, actual)
end
def test_valid_exporter
assert_equal(true, Env::Exporter.valid?(:autoenv))
assert_equal(true, Env::Exporter.valid?(:script))
assert_equal(true, Env::Exporter.valid?(:terminal))
assert_equal(false, Env::Exporter.valid?(:foreman))
end
def test_export_command
assert_export("export TEST=\\\"running\\ with\\ space\\\"", "TEST", "\"running with space\"")
assert_export("export TEST=running with space", "TEST", "running with space", :escape_value => false)
end
def test_unset_command
assert_unset("unset TEST", "TEST")
end
def test_terminal_exporter_export
bag = create_bag({
:level1 => {
:level2 => {
:first => "first with space",
:second => "\"second\\"
},
:third => "third"
},
:existing => "downcase",
})
stub_env(:existing => "exist", :EXISTING => "exist") do
assert_terminal_exporter([
"export EXISTING=downcase",
"export LEVEL1_LEVEL2_FIRST=first\\ with\\ space",
"export LEVEL1_LEVEL2_SECOND=\\\"second\\\\",
"export LEVEL1_THIRD=third",
], bag)
assert_terminal_exporter([
"export LEVEL1_LEVEL2_FIRST=first\\ with\\ space",
"export LEVEL1_LEVEL2_SECOND=\\\"second\\\\",
"export LEVEL1_THIRD=third",
], bag, :override => false)
assert_terminal_exporter([
"export EXISTING=downcase",
"export LEVEL1_LEVEL2_FIRST=first with space",
"export LEVEL1_LEVEL2_SECOND=\"second\\",
"export LEVEL1_THIRD=third",
], bag, :type => :export, :override => true, :escape_value => false)
default_namer = Env::Namer.default(".")
prefix_namer = Env::Namer.prefix("CONFIG", default_namer)
assert_terminal_exporter([
"export CONFIG.EXISTING=downcase",
"export CONFIG.LEVEL1.LEVEL2.FIRST=first with space",
"export CONFIG.LEVEL1.LEVEL2.SECOND=\"second\\",
"export CONFIG.LEVEL1.THIRD=third",
], bag, :override => true, :escape_value => false, :namer => prefix_namer)
end
end
def test_terminal_exporter_unset
bag = create_bag({
:level1 => {
:level2 => {
:first => "first",
:second => "second"
},
:third => "third"
},
:existing => "downcase",
})
stub_env(:existing => "exist", :EXISTING => "exist") do
assert_terminal_exporter([
"unset EXISTING",
"unset LEVEL1_LEVEL2_FIRST",
"unset LEVEL1_LEVEL2_SECOND",
"unset LEVEL1_THIRD",
], bag, :type => :unset)
assert_terminal_exporter([
"unset LEVEL1_LEVEL2_FIRST",
"unset LEVEL1_LEVEL2_SECOND",
"unset LEVEL1_THIRD",
], bag, :override => false, :type => :unset)
default_namer = Env::Namer.default(".")
prefix_namer = Env::Namer.prefix("CONFIG", default_namer)
assert_terminal_exporter([
"unset CONFIG.EXISTING",
"unset CONFIG.LEVEL1.LEVEL2.FIRST",
"unset CONFIG.LEVEL1.LEVEL2.SECOND",
"unset CONFIG.LEVEL1.THIRD",
], bag, :override => true, :namer => prefix_namer, :type => :unset)
end
end
def test_autoenv_exporter
bag = create_bag({
:level1 => {
:level2 => {
:first => "first",
:second => "second"
},
:third => "third"
},
:existing => "downcase",
})
assert_autoenv_exporter([
"export EXISTING=downcase",
"export LEVEL1_LEVEL2_FIRST=first",
"export LEVEL1_LEVEL2_SECOND=second",
"export LEVEL1_THIRD=third",
], bag, :type => :export)
assert_autoenv_exporter([
"unset EXISTING",
"unset LEVEL1_LEVEL2_FIRST",
"unset LEVEL1_LEVEL2_SECOND",
"unset LEVEL1_THIRD",
], bag, :type => :unset)
end
def test_script_exporter
bag = create_bag({
:level1 => {
:level2 => {
:first => "first",
:second => "second"
},
:third => "third"
},
:existing => "downcase",
})
assert_script_exporter([
"#!/bin/env sh",
"",
"export EXISTING=downcase",
"export LEVEL1_LEVEL2_FIRST=first",
"export LEVEL1_LEVEL2_SECOND=second",
"export LEVEL1_THIRD=third",
], bag, :type => :export)
assert_script_exporter([
"#!/bin/env sh",
"",
"unset EXISTING",
"unset LEVEL1_LEVEL2_FIRST",
"unset LEVEL1_LEVEL2_SECOND",
"unset LEVEL1_THIRD",
], bag, :type => :unset)
end
def replace_env(variables)
ENV.clear()
variables = Hash[variables.map do |name, value|
[name.to_s, value]
end]
ENV.update(variables)
end
def stub_env(new = {})
old = ENV.to_hash()
replace_env(new)
yield
ensure
replace_env(old)
end
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant.rb | lib/nugrant.rb | require 'pathname'
require 'nugrant/config'
require 'nugrant/parameters'
# 1.8 Compatibility check
unless defined?(KeyError)
class KeyError < IndexError
end
end
module Nugrant
def self.setup_i18n()
I18n.load_path << File.expand_path("locales/en.yml", Nugrant.source_root)
I18n.reload!
end
def self.source_root
@source_root ||= Pathname.new(File.expand_path("../../", __FILE__))
end
end
if defined?(Vagrant)
Nugrant.setup_i18n()
case
when defined?(Vagrant::Plugin::V2)
require 'nugrant/vagrant/v2/plugin'
else
raise RuntimeError, "Vagrant [#{Vagrant::VERSION}] is not supported by Nugrant."
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/bag.rb | lib/nugrant/bag.rb | require 'nugrant/config'
module Nugrant
class Bag < Hash
##
# Create a new Bag object which holds key/value pairs.
# The Bag object inherits from the Hash object, the main
# differences with a normal Hash are indifferent access
# (symbol or string) and method access (via method call).
#
# Hash objects in the map are converted to Bag. This ensure
# proper nesting of functionality.
#
# =| Arguments
# * `elements`
# The initial elements the bag should be built with it.'
# Must be an object responding to `each` and accepting
# a block with two arguments: `key, value`. Defaults to
# the empty hash.
#
# * `config`
# A Nugrant::Config object or hash passed to Nugrant::Config
# constructor. Used for `key_error` handler.
#
def initialize(elements = {}, config = {})
super()
@__config = Config::convert(config)
(elements || {}).each do |key, value|
self[key] = value
end
end
def config=(config)
@__config = Config::convert(config)
end
def method_missing(method, *args, &block)
self[method]
end
##
### Enumerable Overridden Methods (for string & symbol indifferent access)
##
def count(item)
super(__try_convert_item(item))
end
def find_index(item = nil, &block)
block_given? ? super(&block) : super(__try_convert_item(item))
end
##
### Hash Overridden Methods (for string & symbol indifferent access)
##
def [](input)
key = __convert_key(input)
return @__config.key_error.call(key) if not key?(key)
super(key)
end
def []=(input, value)
super(__convert_key(input), __convert_value(value))
end
def assoc(key)
super(__convert_key(key))
end
def delete(key)
super(__convert_key(key))
end
def fetch(key, default = nil)
super(__convert_key(key), default)
end
def has_key?(key)
super(__convert_key(key))
end
def include?(item)
super(__try_convert_item(item))
end
def key?(key)
super(__convert_key(key))
end
def member?(item)
super(__try_convert_item(item))
end
def dup()
self.class.new(self, @__config.dup())
end
def merge(other, options = {})
result = dup()
result.merge!(other)
end
def merge!(other, options = {})
other.each do |key, value|
current = __get(key)
case
when current == nil
self[key] = value
when current.kind_of?(Hash) && value.kind_of?(Hash)
current.merge!(value, options)
when current.kind_of?(Array) && value.kind_of?(Array)
strategy = options[:array_merge_strategy]
if not Nugrant::Config.supported_array_merge_strategy(strategy)
strategy = @__config.array_merge_strategy
end
self[key] = send("__#{strategy}_array_merge", current, value)
when value != nil
self[key] = value
end
end
self
end
def store(key, value)
self[key] = value
end
def to_hash(options = {})
return {} if empty?()
use_string_key = options[:use_string_key]
Hash[map do |key, value|
key = use_string_key ? key.to_s() : key
value = __convert_value_to_hash(value, options)
[key, value]
end]
end
def walk(path = [], &block)
each do |key, value|
nested_bag = value.kind_of?(Nugrant::Bag)
value.walk(path + [key], &block) if nested_bag
yield path + [key], key, value if not nested_bag
end
end
alias_method :to_ary, :to_a
##
### Private Methods
##
private
def __convert_key(key)
return key.to_s().to_sym() if !key.nil? && key.respond_to?(:to_s)
raise ArgumentError, "Key cannot be nil" if key.nil?
raise ArgumentError, "Key cannot be converted to symbol, current value [#{key}] (#{key.class.name})"
end
##
# This function change value convertible to Bag into actual Bag.
# This trick enable deeply using all Bag functionalities and also
# ensures at the same time a deeply preventive copy since a new
# instance is created for this nested structure.
#
# In addition, it also transforms array elements of type Hash into
# Bag instance also. This enable indifferent access inside arrays
# also.
#
# @param value The value to convert to bag if necessary
# @return The converted value
#
def __convert_value(value)
case
# Converts Hash to Bag instance
when value.kind_of?(Hash)
Bag.new(value, @__config)
# Converts Array elements to Bag instances if needed
when value.kind_of?(Array)
value.map(&self.method(:__convert_value))
# Keeps as-is other elements
else
value
end
end
##
# This function does the reversion of value conversion to Bag
# instances. It transforms Bag instances to Hash (using to_hash)
# and array Bag elements to Hash (using to_hash).
#
# The options parameters are pass to the to_hash function
# when invoked.
#
# @param value The value to convert to hash
# @param options The options passed to the to_hash function
# @return The converted value
#
def __convert_value_to_hash(value, options = {})
case
# Converts Bag instance to Hash
when value.kind_of?(Bag)
value.to_hash(options)
# Converts Array elements to Hash instances if needed
when value.kind_of?(Array)
value.map { |value| __convert_value_to_hash(value, options) }
# Keeps as-is other elements
else
value
end
end
def __get(key)
# Calls Hash method [__convert_key(key)], used internally to retrieve value without raising Undefined parameter
self.class.superclass.instance_method(:[]).bind(self).call(__convert_key(key))
end
##
# The concat order is the reversed compared to others
# because we assume that new values have precedence
# over current ones. Hence, the are prepended to
# current values. This is also logical for parameters
# because of the order in which bags are merged.
#
def __concat_array_merge(current_array, new_array)
new_array + current_array
end
def __extend_array_merge(current_array, new_array)
current_array | new_array
end
def __replace_array_merge(current_array, new_array)
new_array
end
def __try_convert_item(args)
return [__convert_key(args[0]), args[1]] if args.kind_of?(Array)
__convert_key(args)
rescue
args
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/version.rb | lib/nugrant/version.rb | module Nugrant
VERSION = "2.1.5.dev1"
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/parameters.rb | lib/nugrant/parameters.rb | require 'nugrant/mixin/parameters'
module Nugrant
class Parameters
include Mixin::Parameters
##
# Create a new parameters object which holds completed
# merged values. The following precedence is used to decide
# which location has precedence over which location:
#
# (Highest) ------------------ (Lowest)
# project < user < system < defaults
#
# =| Arguments
# * `defaults`
# Passed to Mixin::Parameters setup! method. See mixin
# module for further information.
#
# * `config`
# Passed to Mixin::Parameters setup! method. See mixin
# module for further information.
#
def initialize(defaults = {}, config = {}, options = {})
setup!(defaults, config, options)
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/config.rb | lib/nugrant/config.rb | require 'rbconfig'
module Nugrant
class Config
DEFAULT_ARRAY_MERGE_STRATEGY = :replace
DEFAULT_PARAMS_FILENAME = ".nuparams"
DEFAULT_PARAMS_FORMAT = :yaml
DEFAULT_AUTO_EXPORT = false
SUPPORTED_ARRAY_MERGE_STRATEGIES = [:concat, :extend, :replace]
SUPPORTED_PARAMS_FORMATS = [:json, :yaml]
attr_reader :params_filename, :params_format,
:current_path, :user_path, :system_path,
:array_merge_strategy, :auto_export, :auto_export_script_path,
:key_error, :parse_error
attr_writer :array_merge_strategy, :auto_export, :auto_export_script_path
##
# Convenience method to easily accept either a hash that will
# be converted to a Nugrant::Config object or directly a config
# object.
def self.convert(config = {})
return config.kind_of?(Nugrant::Config) ? config : Nugrant::Config.new(config)
end
##
# Return the fully expanded path of the user parameters
# default location that is used in the constructor.
#
def self.default_user_path()
File.expand_path("~")
end
##
# Return the fully expanded path of the system parameters
# default location that is used in the constructor.
#
def self.default_system_path()
if Config.on_windows?
return File.expand_path(ENV['PROGRAMDATA'] || ENV['ALLUSERSPROFILE'])
end
"/etc"
end
##
# Method to fix-up a received path. The fix-up do the follows
# the following rules:
#
# 1. If the path is callable, call it to get the value.
# 2. If value is nil, return default value.
# 3. If value is a directory, return path + params_filename to it.
# 4. Otherwise, return value
#
# @param path The path parameter received.
# @param default The default path to use, can be a directory.
# @param params_filename The params filename to append if path is a directory
#
# @return The fix-up path following rules defined above.
#
def self.fixup_path(path, default, params_filename)
path = path.call if path.respond_to?(:call)
path = File.expand_path(path || default)
path = "#{path}/#{params_filename}" if ::File.directory?(path)
path
end
def self.supported_array_merge_strategy(strategy)
SUPPORTED_ARRAY_MERGE_STRATEGIES.include?(strategy)
end
def self.supported_params_format(format)
SUPPORTED_PARAMS_FORMATS.include?(format)
end
##
# Return true if we are currently on a Windows platform.
#
def self.on_windows?()
(RbConfig::CONFIG['host_os'].downcase =~ /mswin|mingw|cygwin/) != nil
end
##
# Creates a new config object that is used to configure an instance
# of Nugrant::Parameters. See the list of options and how they interact
# with Nugrant::Parameters.
#
# =| Options
# * +:params_filename+ - The filename used to fetch parameters from. This
# will be appended to various default locations.
# Location are system, project and current that
# can be tweaked individually by using the options
# below.
# Defaults => ".nuparams"
# * +:params_format+ - The format in which parameters are to be parsed.
# Presently supporting :yaml and :json.
# Defaults => :yaml
# * +:current_path+ - The current path has the highest precedence over
# any other location. It can be be used for many purposes
# depending on your usage.
# * A path from where to read project parameters
# * A path from where to read overriding parameters for a cli tool
# * A path from where to read user specific settings not to be committed in a VCS
# Defaults => "./#{@params_filename}"
# * +:user_path+ - The user path is the location where the user
# parameters should resides. The parameters loaded from this
# location have the second highest precedence.
# Defaults => "~/#{@params_filename}"
# * +:system_path+ - The system path is the location where system wide
# parameters should resides. The parameters loaded from this
# location have the third highest precedence.
# Defaults => Default system path depending on OS + @params_filename
# * +:array_merge_strategy+ - This option controls how array values are merged together when merging
# two Bag instances. Possible values are:
# * :replace => Replace current values by new ones
# * :extend => Merge current values with new ones
# * :concat => Append new values to current ones
# Defaults => The strategy :replace.
# * +:key_error+ - A callback method receiving one argument, the key as a symbol, and that
# deal with the error. If the callable does not
# raise an exception, the result of it's execution is returned.
# Defaults => A callable that throws a KeyError exception.
# * +:parse_error+ - A callback method receiving two arguments, the offending filename and
# the error object, that deal with the error. If the callable does not
# raise an exception, the result of it's execution is returned.
# Defaults => A callable that returns the empty hash.
# * +:auto_export+ - Automatically export configuration to the specified format :autoenv or :script
# * +:auto_export_script_path+ - The path where to write the export script, defaults to "./nugrant2env.sh"
#
def initialize(options = {})
@params_filename = options[:params_filename] || DEFAULT_PARAMS_FILENAME
@params_format = options[:params_format] || DEFAULT_PARAMS_FORMAT
@auto_export = options[:auto_export] || DEFAULT_AUTO_EXPORT
@auto_export_script_path = options[:auto_export_script_path] || false # use default
@current_path = Config.fixup_path(options[:current_path], ".", @params_filename)
@user_path = Config.fixup_path(options[:user_path], Config.default_user_path(), @params_filename)
@system_path = Config.fixup_path(options[:system_path], Config.default_system_path(), @params_filename)
@array_merge_strategy = options[:array_merge_strategy] || :replace
@key_error = options[:key_error] || Proc.new do |key|
raise KeyError, "Undefined parameter '#{key}'"
end
@parse_error = options[:parse_error] || Proc.new do |filename, error|
{}
end
validate()
end
def ==(other)
self.class.equal?(other.class) &&
instance_variables.all? do |variable|
instance_variable_get(variable) == other.instance_variable_get(variable)
end
end
def [](key)
instance_variable_get("@#{key}")
rescue
nil
end
def merge(other)
result = dup()
result.merge!(other)
end
def merge!(other)
other.instance_variables.each do |variable|
instance_variable_set(variable, other.instance_variable_get(variable)) if instance_variables.include?(variable)
end
self
end
def to_h()
Hash[instance_variables.map do |variable|
[variable[1..-1].to_sym, instance_variable_get(variable)]
end]
end
alias_method :to_hash, :to_h
def validate()
raise ArgumentError,
"Invalid value for :params_format. \
The format [#{@params_format}] is currently not supported." if not Config.supported_params_format(@params_format)
raise ArgumentError,
"Invalid value for :array_merge_strategy. \
The array merge strategy [#{@array_merge_strategy}] is currently not supported." if not Config.supported_array_merge_strategy(@array_merge_strategy)
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/vagrant/errors.rb | lib/nugrant/vagrant/errors.rb | require 'vagrant/errors'
require 'nugrant/helper/stack'
module Nugrant
module Vagrant
module Errors
class NugrantVagrantError < ::Vagrant::Errors::VagrantError
error_namespace("nugrant.vagrant.errors")
def compute_context()
Helper::Stack.fetch_error_region(caller(), {
:matcher => /(.+Vagrantfile):([0-9]+)/
})
end
end
class ParameterNotFoundError < NugrantVagrantError
error_key(:parameter_not_found)
def initialize(options = nil, *args)
super({:context => compute_context()}.merge(options || {}), *args)
end
end
class VagrantUserParseError < NugrantVagrantError
error_key(:parse_error)
def initialize(options = nil, *args)
super(options, *args)
end
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/vagrant/v2/plugin.rb | lib/nugrant/vagrant/v2/plugin.rb | require 'nugrant/vagrant/v2/action'
module Nugrant
module Vagrant
module V2
class Plugin < ::Vagrant.plugin("2")
name "Nugrant"
description <<-DESC
Plugin to define and use user specific parameters from various location inside your Vagrantfile.
DESC
class << self
def provision(hook)
hook.before(::Vagrant::Action::Builtin::Provision, Nugrant::Vagrant::V2::Action.auto_export)
end
end
action_hook(:nugrant_provision, :machine_action_up, &method(:provision))
action_hook(:nugrant_provision, :machine_action_reload, &method(:provision))
action_hook(:nugrant_provision, :machine_action_provision, &method(:provision))
command "user" do
require_relative "command/root"
Command::Root
end
config "user" do
require_relative "config/user"
Config::User
end
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/vagrant/v2/helper.rb | lib/nugrant/vagrant/v2/helper.rb | require 'pathname'
require 'nugrant'
require 'nugrant/bag'
require 'nugrant/vagrant/v2/config/user'
module Nugrant
module Vagrant
module V2
class Helper
##
# The project path is the path where the top-most (loaded last)
# Vagrantfile resides. It can be considered the project root for
# this environment.
#
# Copied from `lib\vagrant\environment.rb#532` (tag: v1.6.2)
#
# @return [String] The project path to use.
#
def self.find_project_path()
vagrantfile_name = ENV["VAGRANT_VAGRANTFILE"]
vagrantfile_name = [vagrantfile_name] if vagrantfile_name && !vagrantfile_name.is_a?(Array)
root_finder = lambda do |path|
vagrantfile = find_vagrantfile(path, vagrantfile_name)
return path if vagrantfile
return nil if path.root? || !File.exist?(path)
root_finder.call(path.parent)
end
root_finder.call(get_vagrant_working_directory())
end
##
# Finds the Vagrantfile in the given directory.
#
# Copied from `lib\vagrant\environment.rb#732` (tag: v1.6.2)
#
# @param [Pathname] path Path to search in.
# @return [Pathname]
#
def self.find_vagrantfile(search_path, filenames = nil)
filenames ||= ["Vagrantfile", "vagrantfile"]
filenames.each do |vagrantfile|
current_path = search_path.join(vagrantfile)
return current_path if current_path.file?
end
nil
end
##
# Returns Vagrant working directory to use.
#
# Copied from `lib\vagrant\environment.rb#80` (tag: v1.6.2)
#
# @return [Pathname] The working directory to start search in.
#
def self.get_vagrant_working_directory()
cwd = nil
# Set the default working directory to look for the vagrantfile
cwd ||= ENV["VAGRANT_CWD"] if ENV.has_key?("VAGRANT_CWD")
cwd ||= Dir.pwd
cwd = Pathname.new(cwd)
if !cwd.directory?
raise Errors::EnvironmentNonExistentCWD, cwd: cwd.to_s
end
cwd = cwd.expand_path
end
def self.get_restricted_keys()
bag_methods = Nugrant::Bag.instance_methods
parameters_methods = V2::Config::User.instance_methods
(bag_methods | parameters_methods).map(&:to_s)
end
def self.get_used_restricted_keys(hash, restricted_keys)
keys = []
hash.each do |key, value|
keys << key if restricted_keys.include?(key)
keys += get_used_restricted_keys(value, restricted_keys) if value.kind_of?(Hash)
end
keys.uniq
end
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/vagrant/v2/action.rb | lib/nugrant/vagrant/v2/action.rb | require 'nugrant/vagrant/v2/action/auto_export'
module Nugrant
module Vagrant
module V2
module Action
class << self
def auto_export
@auto_export ||= ::Vagrant::Action::Builder.new.tap do |builder|
builder.use Nugrant::Vagrant::V2::Action::AutoExport
end
end
end
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/vagrant/v2/command/restricted_keys.rb | lib/nugrant/vagrant/v2/command/restricted_keys.rb | require 'nugrant'
require 'nugrant/vagrant/v2/helper'
module Nugrant
module Vagrant
module V2
module Command
class RestrictedKeys < ::Vagrant.plugin("2", :command)
def self.synopsis
"prints list of restricted keys for method access"
end
def initialize(arguments, environment)
super(arguments, environment)
@show_help = false
end
def create_parser()
return OptionParser.new do |parser|
parser.banner = "Usage: vagrant user restricted-keys"
parser.separator ""
parser.separator "Available options:"
parser.separator ""
parser.on("-h", "--help", "Prints this help") do
@show_help = true
end
parser.separator ""
parser.separator "Prints keys that cannot be accessed using the method access syntax\n" +
"(`config.user.<key>`). Use array access syntax (`config.user['<key>']`)\n" +
"if you really want to use of the restricted keys.\n"
end
end
def execute
parser = create_parser()
arguments = parse_options(parser)
return help(parser) if @show_help
@env.ui.info("The following keys are restricted, i.e. that method access (`config.user.<key>`)", :prefix => false)
@env.ui.info("will not work. If you really want to use a restricted key, use array access ", :prefix => false)
@env.ui.info("instead (`config.user['<key>']`).", :prefix => false)
@env.ui.info("", :prefix => false)
@env.ui.info("You can run `vagrant user parameters` to check if your config currently defines", :prefix => false)
@env.ui.info("one or more restricted keys shown below.", :prefix => false)
@env.ui.info("", :prefix => false)
restricted_keys = Helper::get_restricted_keys()
@env.ui.info(restricted_keys.sort().join(", "), :prefix => false)
end
def help(parser)
@env.ui.info(parser.help, :prefix => false)
end
end
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/vagrant/v2/command/env.rb | lib/nugrant/vagrant/v2/command/env.rb | require 'nugrant'
require 'nugrant/helper/env/exporter'
require 'nugrant/parameters'
module Nugrant
module Vagrant
module V2
module Command
class Env < ::Vagrant.plugin("2", :command)
EnvExporter = Nugrant::Helper::Env::Exporter
def self.synopsis
"env utilities to export config.user as environment variables in host machine"
end
def initialize(arguments, environment)
super(arguments, environment)
@unset = false
@format = :terminal
@script_path = false
@show_help = false
end
def create_parser()
return OptionParser.new do |parser|
parser.banner = "Usage: vagrant user env [<options>]"
parser.separator ""
parser.separator "Outputs the commands that should be executed to export\n" +
"the various parameter as environment variables. By default,\n" +
"existing ones are overridden. The --format argument can be used\n" +
"to choose in which format the variables should be displayed.\n" +
"Changing the format will also change where they are displayed.\n"
parser.separator ""
parser.separator "Available options:"
parser.separator ""
parser.on("-u", "--unset", "Generates commands needed to unset environment variables, default false") do
@unset = true
end
parser.on("-f", "--format FORMAT", "Determines in what format variables are output, default to terminal") do |format|
@format = format.to_sym()
end
parser.on("-s", "--script-path PATH", "Specifies path of the generated bash script, default to #{EnvExporter::DEFAULT_SCRIPT_PATH}") do |path|
@script_path = path
end
parser.on("-h", "--help", "Prints this help") do
@show_help = true
end
parser.separator ""
parser.separator "Available formats:"
parser.separator " autoenv Write commands to a file named `.env` in the current directory."
parser.separator " See https://github.com/kennethreitz/autoenv for more info."
parser.separator " terminal Write commands to terminal so they can be sourced."
parser.separator " script Write commands to a bash script named `nugrant2env.sh` so it can be sourced."
parser.separator ""
end
end
def error(message, parser)
@env.ui.info("ERROR: #{message}", :prefix => false)
@env.ui.info("", :prefix => false)
help(parser)
return 1
end
def help(parser)
@env.ui.info(parser.help, :prefix => false)
end
def execute
parser = create_parser()
arguments = parse_options(parser)
return error("Invalid format value '#{@format}'", parser) if not EnvExporter.valid?(@format)
return help(parser) if @show_help
@logger.debug("Nugrant 'Env'")
with_target_vms(arguments) do |vm|
parameters = vm.config.user
if not parameters
@env.ui.info("# Vm '#{vm.name}' : unable to retrieve `config.user`, report as bug https://github.com/maoueh/nugrant/issues", :prefix => false)
next
end
bag = parameters.__all
options = {
:type => @unset ? :unset : :export,
:script_path => @script_path
}
case
when @format == :script
EnvExporter.script_exporter(bag, options)
when @format == :autoenv
EnvExporter.autoenv_exporter(bag, options)
when @format == :terminal
EnvExporter.terminal_exporter(bag, options)
end
# No need to execute for the other VMs
return 0
end
end
end
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/vagrant/v2/command/parameters.rb | lib/nugrant/vagrant/v2/command/parameters.rb | require 'nugrant'
require 'nugrant/helper/yaml'
require 'nugrant/vagrant/v2/helper'
module Nugrant
module Vagrant
module V2
module Command
class Parameters < ::Vagrant.plugin("2", :command)
def self.synopsis
"prints parameters hierarchy as seen by Nugrant"
end
def initialize(arguments, environment)
super(arguments, environment)
@show_help = false
@show_defaults = false
@show_system = false
@show_user = false
@show_project = false
end
def create_parser()
return OptionParser.new do |parser|
parser.banner = "Usage: vagrant user parameters [<options>]"
parser.separator ""
parser.separator "Available options:"
parser.separator ""
parser.on("-h", "--help", "Prints this help") do
@show_help = true
end
parser.on("-d", "--defaults", "Show only defaults parameters") do
@show_defaults = true
end
parser.on("-s", "--system", "Show only system parameters") do
@show_system = true
end
parser.on("-u", "--user", "Show only user parameters") do
@show_user = true
end
parser.on("-p", "--project", "Show only project parameters") do
@show_project = true
end
parser.separator ""
parser.separator "When no options is provided, the command prints the names and values \n" +
"of all parameters that would be available for usage in the Vagrantfile.\n" +
"The hierarchy of the parameters is respected, so the final values are\n" +
"displayed."
end
end
def execute
parser = create_parser()
arguments = parse_options(parser)
return help(parser) if @show_help
@logger.debug("'Parameters' each target VM...")
with_target_vms(arguments) do |vm|
parameters = vm.config.user
if not parameters
@env.ui.info("# Vm '#{vm.name}' : unable to retrieve `config.user`, report as bug https://github.com/maoueh/nugrant/issues", :prefix => false)
next
end
@env.ui.info("# Vm '#{vm.name}'", :prefix => false)
defaults(parameters) if @show_defaults
system(parameters) if @show_system
user(parameters) if @show_user
project(parameters) if @show_project
all(parameters) if !@show_defaults && !@show_system && !@show_user && !@show_project
end
return 0
end
def help(parser)
@env.ui.info(parser.help, :prefix => false)
end
def defaults(parameters)
print_bag("Defaults", parameters.__defaults)
end
def system(parameters)
print_bag("System", parameters.__system)
end
def user(parameters)
print_bag("User", parameters.__user)
end
def project(parameters)
print_bag("Project", parameters.__current)
end
def all(parameters)
print_bag("All", parameters.__all)
end
def print_bag(kind, bag)
if !bag || bag.empty?()
print_header(kind)
@env.ui.info(" Empty", :prefix => false)
@env.ui.info("", :prefix => false)
return
end
print_parameters(kind, {
'config' => {
'user' => bag.to_hash(:use_string_key => true)
}
})
end
def print_parameters(kind, hash)
string = Nugrant::Helper::Yaml.format(hash.to_yaml, :indent => 1)
used_restricted_keys = Helper::get_used_restricted_keys(hash, Helper::get_restricted_keys())
print_warning(used_restricted_keys) if !used_restricted_keys.empty?()
print_header(kind)
@env.ui.info(string, :prefix => false)
@env.ui.info("", :prefix => false)
end
def print_header(kind, length = 50)
@env.ui.info(" #{kind.capitalize} Parameters", :prefix => false)
@env.ui.info(" " + "-" * length, :prefix => false)
end
def print_warning(used_restricted_keys)
@env.ui.info("", :prefix => false)
@env.ui.info(" You are using some restricted keys. Method access (using .<key>) will", :prefix => false)
@env.ui.info(" not work, only array access ([<key>]) will. Offending keys:", :prefix => false)
@env.ui.info(" #{used_restricted_keys.join(", ")}", :prefix => false)
@env.ui.info("", :prefix => false)
end
end
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/vagrant/v2/command/root.rb | lib/nugrant/vagrant/v2/command/root.rb | require 'nugrant'
require 'nugrant/vagrant/v2/command/env'
require 'nugrant/vagrant/v2/command/parameters'
require 'nugrant/vagrant/v2/command/restricted_keys'
require 'nugrant/version'
module Nugrant
module Vagrant
module V2
module Command
class Root < ::Vagrant.plugin("2", :command)
def self.synopsis
"manage Nugrant user defined parameters (config.user)"
end
def initialize(arguments, environment)
super(arguments, environment)
@arguments, @subcommand, @subarguments = split_main_and_subcommand(arguments)
# Change super class available arguments to main ones only
@argv = @arguments
@subcommands = ::Vagrant::Registry.new()
@subcommands.register(:env) do
Command::Env
end
@subcommands.register(:parameters) do
Command::Parameters
end
@subcommands.register(:'restricted-keys') do
Command::RestrictedKeys
end
@show_help = false
@show_version = false
end
def create_parser()
return OptionParser.new do |parser|
parser.banner = "Usage: vagrant user [-h] [-v] <subcommand> [<args>]"
parser.separator ""
parser.on("-h", "--help", "Prints this help") do
@show_help = true
end
parser.on("-v", "--version", "Prints plugin version and exit.") do
@show_version = true
end
parser.separator ""
parser.separator "Available subcommands:"
keys = []
@subcommands.each { |key, value| keys << key.to_s }
keys.sort.each do |key|
parser.separator " #{key}"
end
parser.separator ""
parser.separator "For help on any individual command run `vagrant user <subcommand> -h`"
end
end
def execute
parser = create_parser()
arguments = parse_options(parser)
return version() if @show_version
return help(parser) if @show_help
command_class = @subcommands.get(@subcommand.to_sym) if @subcommand
return help(parser) if !command_class || !@subcommand
@logger.debug("Invoking nugrant command class: #{command_class} #{@subarguments.inspect}")
command_class.new(@subarguments, @env).execute
end
def help(parser)
@env.ui.info(parser.help, :prefix => false)
end
def version()
@env.ui.info("Nugrant version #{Nugrant::VERSION}", :prefix => false)
end
end
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/vagrant/v2/action/auto_export.rb | lib/nugrant/vagrant/v2/action/auto_export.rb | require 'nugrant'
require 'nugrant/helper/env/exporter'
require 'nugrant/parameters'
module Nugrant
module Vagrant
module V2
module Action
EnvExporter = Nugrant::Helper::Env::Exporter
class AutoExport
def initialize(app, env)
@app = app
@config = env[:machine].env.vagrantfile.config
end
def call(env)
return @app.call(env) if not @config.user.auto_export
options = {
:type => :export,
:script_path => @config.user.auto_export_script_path
}
Array(@config.user.auto_export).each do |exporter|
if exporter == :terminal or not EnvExporter.valid?(exporter)
env[:ui].warn("ERROR: Invalid config.user.auto_export value '#{exporter}'", :prefix => false)
next
end
env[:ui].info("Configuration exported '#{exporter}'", :prefix => false)
case
when exporter == :script
EnvExporter.script_exporter(@config.user.__all, options)
when exporter == :autoenv
EnvExporter.autoenv_exporter(@config.user.__all, options)
end
end
end
end
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/vagrant/v2/config/user.rb | lib/nugrant/vagrant/v2/config/user.rb | require 'nugrant/mixin/parameters'
require 'nugrant/vagrant/errors'
require 'nugrant/vagrant/v2/helper'
module Nugrant
module Vagrant
module V2
module Config
class User < ::Vagrant.plugin("2", :config)
include Mixin::Parameters
def initialize(defaults = {}, config = {})
setup!(defaults,
:params_filename => ".vagrantuser",
:current_path => Helper.find_project_path(),
:key_error => Proc.new do |key|
raise Errors::ParameterNotFoundError, :key => key.to_s
end,
:parse_error => Proc.new do |filename, error|
raise Errors::VagrantUserParseError, :filename => filename.to_s, :error => error
end
)
end
end
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/mixin/parameters.rb | lib/nugrant/mixin/parameters.rb | require 'nugrant/bag'
require 'nugrant/config'
require 'nugrant/helper/bag'
module Nugrant
module Mixin
##
# Mixin module so it's possible to share parameters
# logic between default Parameters class and Vagrant
# implementation.
#
# This module delegates method missing to the final
# bag hierarchy (@__all). This means that even if the class
# including this module doesn't inherit Bag directly,
# it act exactly like one.
#
# When including this module, you must respect an important
# constraint.
#
# The including class must call `setup!` before starting using
# parameters retrieval. This is usually performed in
# the `initialize` method directly but could be in a different place
# depending on the including class lifecycle. The call to `setup!` is
# important to initialize all required instance variables.
#
# Here an example where `setup!` is called in constructor. Your constructor
# does not need to have these arguments, they are there as an example.
#
# ```
# def initialize(defaults = {}, config = {}, options = {})
# setup!(defaults, config, options)
# end
# ```
#
module Parameters
attr_reader :__config, :__current, :__user, :__system, :__defaults, :__all
def method_missing(method, *args, &block)
case
when @__all.class.method_defined?(method)
@__all.send(method, *args, &block)
else
@__all[method]
end
end
def array_merge_strategy
@__config.array_merge_strategy
end
def auto_export
@__config.auto_export
end
def auto_export_script_path
@__config.auto_export_script_path
end
##
# Change the current array merge strategy for this parameters.
#
# @param strategy The new strategy to use.
def array_merge_strategy=(strategy)
return if not Nugrant::Config.supported_array_merge_strategy(strategy)
@__config.array_merge_strategy = strategy
# When array_merge_strategy change, we need to recompute parameters hierarchy
compute_all!()
end
def auto_export=(auto_export)
@__config.auto_export = auto_export
end
def auto_export_script_path=(path)
@__config.auto_export_script_path = path
end
def defaults()
@__defaults
end
##
# Set the new default values for the
# various parameters contain by this instance.
# This will call `compute_all!` to recompute
# correct precedences.
#
# =| Attributes
# * +elements+ - The new default elements
#
def defaults=(elements)
@__defaults = Bag.new(elements, @__config)
# When defaults change, we need to recompute parameters hierarchy
compute_all!()
end
def merge(other)
result = dup()
result.merge!(other)
end
def merge!(other)
@__config.merge!(other.__config)
# Updated Bags' config
@__current.config = @__config
@__user.config = @__config
@__system.config = @__config
@__defaults.config = @__config
# Merge other into Bags
@__current.merge!(other.__current, :array_merge_strategy => :replace)
@__user.merge!(other.__user, :array_merge_strategy => :replace)
@__system.merge!(other.__system, :array_merge_strategy => :replace)
@__defaults.merge!(other.__defaults, :array_merge_strategy => :replace)
# Recompute all from merged Bags
compute_all!()
self
end
##
# Setup instance variables of the mixin. It will compute all parameters bags
# (current, user, system, default and all) and stored them to these respective
# instance variables:
#
# * @__current
# * @__user
# * @__system
# * @__defaults
#
# =| Arguments
# * `defaults`
# A hash that is used as the initial data for the defaults bag. Defaults
# to an empty hash.
#
# * `config`
# A Nugrant::Config object or hash passed to Nugrant::Config
# convert method. Used to determine where to find the various
# bag data sources and other configuration options.
#
# Passed to nested structures that requires a Nugrant::Config object
# like the Bag object and Helper::Bag module.
#
# * `options`
# Options hash used by this method exclusively. No options yet, added
# for future improvements.
#
def setup!(defaults = {}, config = {}, options = {})
@__config = Nugrant::Config::convert(config);
@__defaults = Bag.new(defaults, @__config)
@__current = Helper::Bag.read(@__config.current_path, @__config.params_format, @__config)
@__user = Helper::Bag.read(@__config.user_path, @__config.params_format, @__config)
@__system = Helper::Bag.read(@__config.system_path, @__config.params_format, @__config)
compute_all!()
end
##
# Recompute the correct precedences by merging the various
# bag in the right order and return the result as a Nugrant::Bag
# object.
#
def compute_all!()
@__all = Bag.new({}, @__config)
@__all.merge!(@__defaults)
@__all.merge!(@__system)
@__all.merge!(@__user)
@__all.merge!(@__current)
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/helper/bag.rb | lib/nugrant/helper/bag.rb | require 'multi_json'
require 'yaml'
require 'nugrant/bag'
module Nugrant
module Helper
module Bag
def self.read(filepath, filetype, config)
Nugrant::Bag.new(parse_data(filepath, filetype, config), config)
end
def self.restricted_keys()
Nugrant::Bag.instance_methods()
end
private
def self.parse_data(filepath, filetype, config)
return if not File.exist?(filepath)
File.open(filepath, "rb") do |file|
return send("parse_#{filetype}", file)
end
rescue => error
config.parse_error.call(filepath, error)
end
def self.parse_json(io)
MultiJson.load(io.read())
end
def self.parse_yaml(io)
YAML.load(io.read())
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/helper/yaml.rb | lib/nugrant/helper/yaml.rb | module Nugrant
module Helper
class Yaml
def self.format(string, options = {})
lines = string.send(string.respond_to?(:lines) ? :lines : :to_s).to_a
lines = lines.drop(1)
if options[:indent]
indent_text = " " * options[:indent]
lines = lines.map do |line|
indent_text + line
end
end
return lines.join("")
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/helper/stack.rb | lib/nugrant/helper/stack.rb | module Nugrant
module Helper
class Stack
@@DEFAULT_MATCHER = /^(.+):([0-9]+)/
def self.fetch_error_region(stack, options = {})
entry = find_entry(stack, options)
location = extract_error_location(entry, options)
return (options[:unknown] || "Unknown") if not location[:file] and not location[:line]
return location[:file] if not location[:line]
fetch_error_region_from_location(location, options)
end
def self.fetch_error_region_from_location(location, options = {})
prefix = options[:prefix] || " "
width = options[:width] || 4
file = File.new(location[:file], "r")
line = location[:line]
index = 0
lines = []
while (line_string = file.gets())
index += 1
next if (line - index).abs > width
line_prefix = "#{prefix}#{index}:"
line_prefix += (line == index ? ">> " : " ")
lines << "#{line_prefix}#{line_string}"
end
lines.join().chomp()
rescue
return (options[:unknown] || "Unknown") if not location[:file] and not location[:line]
return location[:file] if not location[:line]
"#{location[:file]}:#{location[:line]}"
ensure
file.close() if file
end
##
# Search a stack list (as simple string array) for the first
# entry that match the +:matcher+.
#
def self.find_entry(stack, options = {})
matcher = options[:matcher] || @@DEFAULT_MATCHER
stack.find do |entry|
entry =~ matcher
end
end
##
# Extract error location information from a stack entry using the
# matcher received in arguments.
#
# The usual stack entry format is:
# > /home/users/joe/work/lib/ruby.rb:4:Error message
#
# This function will extract the file and line information from
# the stack entry using the matcher. The matcher is expected to
# have two groups, the first for the file and the second for
# line.
#
# The results is returned in form of a hash with two keys, +:file+
# for the file information and +:line+ for the line information.
#
# If the matcher matched zero group, return +{:file => nil, :line => nil}+.
# If the matcher matched one group, return +{:file => file, :line => nil}+.
# If the matcher matched two groups, return +{:file => file, :line => line}+.
#
def self.extract_error_location(entry, options = {})
matcher = options[:matcher] || @@DEFAULT_MATCHER
result = matcher.match(entry)
captures = result ? result.captures : []
{:file => captures[0], :line => captures[1] ? captures[1].to_i() : nil}
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/helper/parameters.rb | lib/nugrant/helper/parameters.rb | require 'nugrant/parameters'
module Nugrant
module Helper
module Parameters
def self.restricted_keys()
methods = Nugrant::Parameters.instance_methods() + Nugrant::Bag.instance_methods()
methods.uniq!
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/helper/env/exporter.rb | lib/nugrant/helper/env/exporter.rb | require 'shellwords'
require 'nugrant/bag'
require 'nugrant/helper/env/namer'
module Nugrant
module Helper
module Env
module Exporter
DEFAULT_AUTOENV_PATH = "./.env"
DEFAULT_SCRIPT_PATH = "./nugrant2env.sh"
VALID_EXPORTERS = [:autoenv, :script, :terminal]
##
# Returns true if the exporter name received is a valid
# valid export, false otherwise.
#
# @param exporter The exporter name to check validity
#
# @return true if exporter is valid, false otherwise.
def self.valid?(exporter)
VALID_EXPORTERS.include?(exporter)
end
##
# Creates an autoenv script containing the commands that are required
# to export or unset a bunch of environment variables taken from the
# bag.
#
# @param bag The bag to create the script for.
#
# @return (side-effect) Creates a script file containing commands
# to export or unset environment variables for
# bag.
#
# Options:
# * :autoenv_path => The path where to write the script, defaults to `./.env`.
# * :escape_value => If true, escape the value to export (or unset), default to true.
# * :io => The io where the command should be written, default to nil which create the autoenv on disk.
# * :namer => The namer used to transform bag segments into variable name, default to Namer::default().
# * :override => If true, variable a exported even when the override an existing env key, default to true.
# * :type => The type of command, default to :export.
#
def self.autoenv_exporter(bag, options = {})
io = options[:io] || (File.open(File.expand_path(options[:autoenv_path] || DEFAULT_AUTOENV_PATH), "wb"))
terminal_exporter(bag, options.merge({:io => io}))
ensure
io.close() if io
end
##
# Creates a bash script containing the commands that are required
# to export or unset a bunch of environment variables taken from the
# bag.
#
# @param bag The bag to create the script for.
#
# @return (side-effect) Creates a script file containing commands
# to export or unset environment variables for
# bag.
#
# Options:
# * :escape_value => If true, escape the value to export (or unset), default to true.
# * :io => The io where the command should be written, default to nil which create the script on disk.
# * :namer => The namer used to transform bag segments into variable name, default to Namer::default().
# * :override => If true, variable a exported even when the override an existing env key, default to true.
# * :script_path => The path where to write the script, defaults to `./nugrant2env.sh`.
# * :type => The type of command, default to :export.
#
def self.script_exporter(bag, options = {})
io = options[:io] || (File.open(File.expand_path(options[:script_path] || DEFAULT_SCRIPT_PATH), "wb"))
io.puts("#!/bin/env sh")
io.puts()
terminal_exporter(bag, options.merge({:io => io}))
ensure
io.close() if io
end
##
# Export to terminal the commands that are required
# to export or unset a bunch of environment variables taken from the
# bag.
#
# @param bag The bag to create the script for.
#
# @return (side-effect) Outputs to io the commands generated.
#
# Options:
# * :escape_value => If true, escape the value to export (or unset), default to true.
# * :io => The io where the command should be displayed, default to $stdout.
# * :namer => The namer used to transform bag segments into variable name, default to Namer::default().
# * :override => If true, variable a exported even when the override an existing env key, default to true.
# * :type => The type of command, default to :export.
#
def self.terminal_exporter(bag, options = {})
io = options[:io] || $stdout
type = options[:type] || :export
export(bag, options) do |key, value|
io.puts(command(type, key, value, options))
end
end
##
# Generic function to export a bag. This walk the bag,
# for each element, it creates the key using the namer
# and then forward the key and value to the block if
# the variable does not override an existing environment
# variable or if options :override is set to true.
#
# @param bag The bag to export.
#
# @return (side-effect) Yields each key and value to a block
#
# Options:
# * :namer => The namer used to transform bag parents into variable name, default to Namer::default().
# * :override => If true, variable a exported even when the override an existing env key, default to true.
#
def self.export(bag, options = {})
namer = options[:namer] || Env::Namer.default()
override = options.fetch(:override, true)
variables = {}
bag.walk do |path, key, value|
key = namer.call(path)
variables[key] = value if override or not ENV[key]
end
variables.sort().each do |key, value|
yield key, value
end
end
##
# Given a key and a value, return a string representation
# of the command type requested. Available types:
#
# * :export => A bash compatible export command
# * :unset => A bash compatible export command
#
def self.command(type, key, value, options = {})
# TODO: Replace by a map type => function name
case
when type == :export
export_command(key, value, options)
when type == :unset
unset_command(key, value, options)
end
end
##
# Returns a string representation of the command
# that needs to be used on the current platform
# to export an environment variable.
#
# @param key The key of the environment variable to export.
# It cannot be nil.
# @param value The value of the environment variable to export
#
# @return The export command, as a string
#
# Options:
# * :escape_value (true) => If true, escape the value to export.
#
def self.export_command(key, value, options = {})
value = value.to_s()
value = Shellwords.escape(value) if options[:escape_value] == nil || options[:escape_value]
# TODO: Handle platform differently
"export #{key}=#{value}"
end
##
# Returns a string representation of the command
# that needs to be used on the current platform
# to unset an environment variable.
#
# @param key The key of the environment variable to export.
# It cannot be nil.
#
# @return The unset command, as a string
#
def self.unset_command(key, value, options = {})
# TODO: Handle platform differently
"unset #{key}"
end
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
maoueh/nugrant | https://github.com/maoueh/nugrant/blob/6276b3e81364c6ed204d958ec01c653a34a74464/lib/nugrant/helper/env/namer.rb | lib/nugrant/helper/env/namer.rb | module Nugrant
module Helper
module Env
##
# A namer is a lambda taking as argument an array of segments
# that should return a string representation of those segments.
# How the segments are transformed to a string is up to the
# namer. By using various namer, we can change how a bag key
# is transformed into and environment variable name. This is
# like the strategy pattern.
#
module Namer
##
# Returns the default namer, which join segments together
# using a character and upcase the result.
#
# @param `char` The character used to join segments together, default to `"_"`.
#
# @return A lambda that will simply joins segment using the `char` argument
# and upcase the result.
#
def self.default(char = "_")
lambda do |segments|
segments.join(char).upcase()
end
end
##
# Returns the prefix namer, which add a prefix to segments
# and delegate its work to another namer.
#
# @param prefix The prefix to add to segments.
# @param delegate_namer A namer that will be used to transform the prefixed segments.
#
# @return A lambda that will simply add prefix to segments and will call
# the delegate_namer with those new segments.
#
def self.prefix(prefix, delegate_namer)
lambda do |segments|
delegate_namer.call([prefix] + segments)
end
end
end
end
end
end
| ruby | MIT | 6276b3e81364c6ed204d958ec01c653a34a74464 | 2026-01-04T17:56:15.986406Z | false |
red-data-tools/pandas.rb | https://github.com/red-data-tools/pandas.rb/blob/051633c8158a9c99b902289b771ca590d8b32b92/spec/pandas_spec.rb | spec/pandas_spec.rb | require "spec_helper"
RSpec.describe Pandas do
it "has a version number" do
expect(Pandas::VERSION).not_to be nil
end
specify do
expect(Pandas).to be_const_defined(:DataFrame)
expect(Pandas).to be_const_defined(:Series)
expect(Pandas).to be_const_defined(:IlocIndexer)
expect(Pandas).to be_const_defined(:LocIndexer)
if Pandas.__version__ < "1.0"
expect(Pandas).to be_const_defined(:IXIndexer)
end
expect(Pandas).to be_const_defined(:MultiIndex)
expect(Pandas).to be_const_defined(:Index)
expect(Pandas).to be_const_defined(:DataFrameGroupBy)
expect(Pandas).to be_const_defined(:SeriesGroupBy)
end
specify do
df = Pandas.read_csv(file_fixture('test.csv').to_s)
expect(df).to be_a(Pandas::DataFrame)
end
describe '.options.display' do
specify do
expect(Pandas.options.display.max_rows).to be_a(Integer)
begin
origin_value = Pandas.options.display.max_rows
half = origin_value >> 1
expect {
Pandas.options.display.max_rows = half
}.to change {
Pandas.options.display.max_rows
}.to(half)
ensure
Pandas.options.display.max_rows = origin_value
end
end
end
end
module Pandas
::RSpec.describe DataFrame do
specify do
df = DataFrame.new(data: { name: %w[a b], age: [27, 30] })
age = df[:age].values()
age[1] = 31
expect(df.loc[1, :age]).to eq(31)
end
end
end
| ruby | MIT | 051633c8158a9c99b902289b771ca590d8b32b92 | 2026-01-04T17:56:21.148862Z | false |
red-data-tools/pandas.rb | https://github.com/red-data-tools/pandas.rb/blob/051633c8158a9c99b902289b771ca590d8b32b92/spec/spec_helper.rb | spec/spec_helper.rb | require "bundler/setup"
require "pandas"
Dir.glob(File.expand_path('../support/**/*.rb', __FILE__)) do |file|
require file
end
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
| ruby | MIT | 051633c8158a9c99b902289b771ca590d8b32b92 | 2026-01-04T17:56:21.148862Z | false |
red-data-tools/pandas.rb | https://github.com/red-data-tools/pandas.rb/blob/051633c8158a9c99b902289b771ca590d8b32b92/spec/support/file_fixture.rb | spec/support/file_fixture.rb | require 'pathname'
module RSpecHelper
module FileFixture
def file_fixture_path
@file_fixture_path ||= File.expand_path('../../fixtures/files', __FILE__)
end
def file_fixture(fixture_name)
path = Pathname.new(file_fixture_path).join(fixture_name)
if path.exist?
path
else
msg = "the directory '%s' does not contain a file named '%s'"
raise ArgumentError, msg % [file_fixture_path, fixture_name]
end
end
end
end
RSpec.configuration.include RSpecHelper::FileFixture
| ruby | MIT | 051633c8158a9c99b902289b771ca590d8b32b92 | 2026-01-04T17:56:21.148862Z | false |
red-data-tools/pandas.rb | https://github.com/red-data-tools/pandas.rb/blob/051633c8158a9c99b902289b771ca590d8b32b92/spec/support/database.rb | spec/support/database.rb | RSpec.shared_context 'With database', :with_database do
require 'active_record'
require 'fileutils'
let(:tmp_dir) do
File.expand_path('../../../tmp', __FILE__)
end
let(:database_path) do
File.join(tmp_dir, 'test.sqlite3')
end
let(:connection_config) do
{adapter: :sqlite3, database: database_path, pool: 5, timeout: 5000}
end
before do
FileUtils.rm_f(database_path)
ActiveRecord::Base.establish_connection(connection_config)
end
end
| ruby | MIT | 051633c8158a9c99b902289b771ca590d8b32b92 | 2026-01-04T17:56:21.148862Z | false |
red-data-tools/pandas.rb | https://github.com/red-data-tools/pandas.rb/blob/051633c8158a9c99b902289b771ca590d8b32b92/spec/pandas/series_spec.rb | spec/pandas/series_spec.rb | require 'spec_helper'
module Pandas
::RSpec.describe Series do
describe '#[key]' do
let(:series) do
Series.new([5, 8, -2, 1], index: ['c', 'a', 'd', 'b'])
end
let(:index) do
['c', 'b']
end
context 'When the key is a PyCall::List' do
specify do
list = PyCall::List.new(index)
expect(series[list]).to eq(Series.new([5, 1], index: index))
end
end
context 'When the key is an Array' do
specify do
expect(series[index]).to eq(Series.new([5, 1], index: index))
end
end
context 'When the key is a Range' do
subject(:series) do
Pandas::Series.new([10, 20, 30, 40], index: %w[x1 x2 x3 x4])
end
context 'The Range is close-end' do
specify do
expect(series["x2".."x3"]).to eq([20, 30])
end
end
context 'The Range is open-end' do
specify do
expect(series["x2"..."x4"].values).to eq([20, 30, 40])
end
end
end
end
describe '#[key]=' do
let(:series) do
Series.new([5, 8, -2, 1], index: ['c', 'a', 'd', 'b'])
end
let(:index) do
['c', 'b']
end
context 'When the key is a PyCall::List' do
specify do
list = PyCall::List.new(index)
series[list] = 100
expect(series).to eq(Series.new([100, 8, -2, 100], index: series.index))
end
specify do
list = PyCall::List.new(index)
series[list] = [100, 200]
expect(series).to eq(Series.new([100, 8, -2, 200], index: series.index))
end
end
context 'When the key is an Array' do
specify do
series[index] = 100
expect(series).to eq(Series.new([100, 8, -2, 100], index: series.index))
end
specify do
series[index] = [100, 200]
expect(series).to eq(Series.new([100, 8, -2, 200], index: series.index))
end
end
context 'When the key is a Range' do
subject(:series) do
Pandas::Series.new([10, 20, 30, 40], index: %w[x1 x2 x3 x4])
end
context 'The Range is close-end' do
specify do
series["x2".."x3"] = 100
expect(series).to eq([10, 100, 100, 40])
end
specify do
series["x2".."x3"] = [100, 200]
expect(series).to eq([10, 100, 200, 40])
end
end
context 'The Range is open-end' do
specify do
series["x2"..."x4"] = 100
expect(series).to eq([10, 100, 100, 100])
end
specify do
series["x2"..."x4"] = [100, 200, 300]
expect(series).to eq([10, 100, 200, 300])
end
end
end
end
describe '#monotonic_decreasing?' do
specify do
s = Pandas::Series.new([1, 2, 3, 4, 5])
expect(s).not_to be_monotonic_decreasing
end
specify do
s = Pandas::Series.new([5, 4, 3, 2, 1])
expect(s).to be_monotonic_decreasing
end
specify do
s = Pandas::Series.new([1, 2, 6, 4, 5])
expect(s).not_to be_monotonic_decreasing
end
end
describe '#monotonic_increasing?' do
specify do
s = Pandas::Series.new([1, 2, 3, 4, 5])
expect(s).to be_monotonic_increasing
end
specify do
s = Pandas::Series.new([5, 4, 3, 2, 1])
expect(s).not_to be_monotonic_increasing
end
specify do
s = Pandas::Series.new([1, 2, 6, 4, 5])
expect(s).not_to be_monotonic_increasing
end
end
describe '#unique?' do
specify do
s = Pandas::Series.new([1, 2, 3, 4, 5])
expect(s).to be_unique
end
specify do
s = Pandas::Series.new([1, 5, 3, 4, 5])
expect(s).not_to be_unique
end
end
describe "#length" do
specify do
s = Pandas::Series.new([1, 2, 3, 4, 5])
expect(s.length).to eq(5)
end
end
describe "#to_a" do
specify do
s = Pandas::Series.new([1, 2, 3, 4, 5])
a = s.to_a
expect(a).to be_an(Array)
expect(a).to eq([1, 2, 3, 4, 5])
end
context "after dropna" do
specify "without NaNs" do
s = Pandas::Series.new([1, 2, 3, 4, 5])
a = s.dropna.to_a
expect(a).to be_an(Array)
expect(a).to eq([1, 2, 3, 4, 5])
end
specify "with NaNs" do
s = Pandas::Series.new([1, 2, nil, 4, 5])
a = s.dropna.to_a
expect(a).to be_an(Array)
expect(a).to eq([1, 2, 4, 5])
end
end
end
end
end
| ruby | MIT | 051633c8158a9c99b902289b771ca590d8b32b92 | 2026-01-04T17:56:21.148862Z | false |
red-data-tools/pandas.rb | https://github.com/red-data-tools/pandas.rb/blob/051633c8158a9c99b902289b771ca590d8b32b92/spec/pandas/data_frame_spec.rb | spec/pandas/data_frame_spec.rb | require 'spec_helper'
module Pandas
::RSpec.describe DataFrame do
let(:values) do
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
end
subject(:df) do
Pandas::DataFrame.new(values, index: %w[r1 r2 r3], columns: %w[x1 x2 x3 x4])
end
describe '#[key]' do
context 'When the key is an Array' do
specify do
expect(df[["x1", "x3"]].iloc[0]).to eq([1, 3])
end
end
end
describe '#iloc[key]' do
context 'When the key is an integer' do
specify do
expect(df.iloc[2]).to eq(values[2])
end
end
context 'When the key is an array' do
let(:expected_result) do
Pandas::DataFrame.new([values[2], values[0], values[1]],
index: %w[r3 r1 r2],
columns: df.columns)
end
specify do
expect(df.iloc[[2, 0, 1]]).to eq(expected_result)
end
end
context 'When two keys are given' do
specify do
expected_result = Pandas::DataFrame.new([[7, 5]], index: %w[r2], columns: %w[x3 x1])
expect(df.iloc[1, [2, 0]]).to eq(expected_result)
end
specify do
expected_result = Pandas::DataFrame.new([[7, 5], [3, 1]], index: %w[r2 r1], columns: %w[x3 x1])
expect(df.iloc[[1, 0], [2, 0]]).to eq(expected_result)
end
end
end
describe '#loc[key]' do
context 'When the key is a String' do
specify do
expect(df.loc["r3"]).to eq(values[2])
end
end
context 'When the key is a string array' do
let(:expected_result) do
Pandas::DataFrame.new([values[2], values[0]],
index: %w[r3 r1],
columns: df.columns)
end
specify do
expect(df.loc[["r3", "r1"]]).to eq(expected_result)
end
end
context 'When two keys are given' do
specify do
expected_result = Pandas::DataFrame.new([[7, 5]], index: %w[r2], columns: %w[x3 x1])
expect(df.loc["r2", ["x3", "x1"]]).to eq(expected_result)
end
specify do
expected_result = Pandas::DataFrame.new([[7, 5], [3, 1]], index: %w[r2 r1], columns: %w[x3 x1])
expect(df.loc[["r2", "r1"], ["x3", "x1"]]).to eq(expected_result)
end
end
end
end
end
| ruby | MIT | 051633c8158a9c99b902289b771ca590d8b32b92 | 2026-01-04T17:56:21.148862Z | false |
red-data-tools/pandas.rb | https://github.com/red-data-tools/pandas.rb/blob/051633c8158a9c99b902289b771ca590d8b32b92/spec/pandas/sql_spec.rb | spec/pandas/sql_spec.rb | require 'spec_helper'
require 'csv'
::RSpec.describe Pandas, :with_database do
let(:sqlalchemy) do
PyCall.import_module('sqlalchemy')
end
let(:engine) do
sqlalchemy.create_engine('sqlite:///' + database_path)
end
before do
PyCall.with(engine.connect) do |conn|
conn.execute sqlalchemy.text(<<-SQL)
create table people (
id integer primary key,
name string,
age integer,
sex string
);
SQL
csv = CSV.read(file_fixture('people.csv'), headers: :first_row)
csv.each do |row|
conn.execute sqlalchemy.text(<<-SQL)
insert into people (id, name, age, sex) values (#{row['id']}, "#{row['name']}", #{row['age']}, "#{row['sex']}");
SQL
end
conn.commit
end
end
describe '.read_sql_table' do
context 'When the given connection is of SQLAlchemy' do
it 'reads from SQLAlchemy engine' do
df_sql = Pandas.read_sql_table('people', engine)
df_csv = Pandas.read_csv(file_fixture('people.csv').to_s)
expect(df_sql).to eq(df_csv)
end
end
end
describe '.read_sql_query' do
context 'When the given connection is of SQLAlchemy' do
it 'reads from SQLAlchemy engine' do
df_sql = Pandas.read_sql_query(<<-SQL, engine)
select name, sex from people;
SQL
df_csv = Pandas.read_csv(file_fixture('people.csv').to_s)
expect(df_sql).to eq(df_csv[[:name, :sex]])
end
end
end
end
| ruby | MIT | 051633c8158a9c99b902289b771ca590d8b32b92 | 2026-01-04T17:56:21.148862Z | false |
red-data-tools/pandas.rb | https://github.com/red-data-tools/pandas.rb/blob/051633c8158a9c99b902289b771ca590d8b32b92/spec/pandas/activerecord_spec.rb | spec/pandas/activerecord_spec.rb | require 'spec_helper'
require 'csv'
module PandasActiveRecordSpec
end
::RSpec.describe Pandas, :with_database do
before do
ActiveRecord::Base.connection.execute <<-SQL
create table people (
id integer primary key,
name string,
age integer,
sex string
);
SQL
csv = CSV.read(file_fixture('people.csv'), headers: :first_row)
csv.each do |row|
ActiveRecord::Base.connection.execute <<-SQL
insert into people (id, name, age, sex) values (#{row['id']}, "#{row['name']}", #{row['age']}, "#{row['sex']}");
SQL
end
class PandasActiveRecordSpec::Person < ActiveRecord::Base
self.table_name = 'people'
end
end
after do
module PandasActiveRecordSpec
remove_const :Person
end
end
describe '.read_sql_table' do
context 'When the given connection is of ActiveRecord' do
it 'reads from ActiveRecord connection' do
df_ar = Pandas.read_sql_table('people', ActiveRecord::Base.connection)
df_csv = Pandas.read_csv(file_fixture('people.csv').to_s)
expect(df_ar).to eq(df_csv)
end
end
context 'When the given object is a concrete ActiveRecord model class' do
it 'reads from the table of the given model class' do
df_ar = Pandas.read_sql_table(PandasActiveRecordSpec::Person)
df_csv = Pandas.read_csv(file_fixture('people.csv').to_s)
expect(df_ar).to eq(df_csv)
end
context 'with index_col: :id' do
it 'reads from the table of the given model class' do
df_ar = Pandas.read_sql_table(PandasActiveRecordSpec::Person, index_col: :id)
df_csv = Pandas.read_csv(file_fixture('people.csv').to_s)
expect(df_ar.reset_index).to eq(df_csv)
end
end
end
end
describe '.read_sql_query' do
context 'When the given connection is of ActiveRecord' do
it 'reads from ActiveRecord connection' do
df_ar = Pandas.read_sql_query(<<-SQL, ActiveRecord::Base.connection)
select name, sex from people;
SQL
df_csv = Pandas.read_csv(file_fixture('people.csv').to_s)
expect(df_ar).to eq(df_csv[[:name, :sex]])
end
context 'with index_col: :id' do
it 'reads from ActiveRecord connection' do
df_ar = Pandas.read_sql_query(<<-SQL, ActiveRecord::Base.connection, index_col: :id)
select id, name, sex from people;
SQL
df_csv = Pandas.read_csv(file_fixture('people.csv').to_s)
expect(df_ar.reset_index(drop: true)).to eq(df_csv[[:name, :sex]])
end
end
end
end
end
| ruby | MIT | 051633c8158a9c99b902289b771ca590d8b32b92 | 2026-01-04T17:56:21.148862Z | false |
red-data-tools/pandas.rb | https://github.com/red-data-tools/pandas.rb/blob/051633c8158a9c99b902289b771ca590d8b32b92/spec/pandas/index_spec.rb | spec/pandas/index_spec.rb | require 'spec_helper'
module Pandas
::RSpec.describe Index do
describe '#monotonic_decreasing?' do
specify do
idx = Pandas::Index.new([1, 2, 3, 4, 5])
expect(idx).not_to be_monotonic_decreasing
end
specify do
idx = Pandas::Index.new([5, 4, 3, 2, 1])
expect(idx).to be_monotonic_decreasing
end
specify do
idx = Pandas::Index.new([1, 2, 6, 4, 5])
expect(idx).not_to be_monotonic_decreasing
end
end
describe '#monotonic_increasing?' do
specify do
idx = Pandas::Index.new([1, 2, 3, 4, 5])
expect(idx).to be_monotonic_increasing
end
specify do
idx = Pandas::Index.new([5, 4, 3, 2, 1])
expect(idx).not_to be_monotonic_increasing
end
specify do
idx = Pandas::Index.new([1, 2, 6, 4, 5])
expect(idx).not_to be_monotonic_increasing
end
end
describe '#unique?' do
specify do
idx = Pandas::Index.new([1, 2, 3, 4, 5])
expect(idx).to be_unique
end
specify do
idx = Pandas::Index.new([1, 5, 3, 4, 5])
expect(idx).not_to be_unique
end
end
describe "#length" do
specify do
idx = Pandas::Index.new([1, 2, 3, 4, 5])
expect(idx.length).to eq(5)
end
end
describe "#to_a" do
specify do
idx = Pandas::Index.new([1, 2, 3, 4, 5])
a = idx.to_a
expect(a).to be_an(Array)
expect(a).to eq([1, 2, 3, 4, 5])
end
context "after dropna" do
specify "without NaNs" do
s = Pandas::Index.new([1, 2, 3, 4, 5])
a = s.dropna.to_a
expect(a).to be_an(Array)
expect(a).to eq([1, 2, 3, 4, 5])
end
specify "with NaNs" do
s = Pandas::Index.new([1, 2, nil, 4, 5])
a = s.dropna.to_a
expect(a).to be_an(Array)
expect(a).to eq([1, 2, 4, 5])
end
end
end
end
end
| ruby | MIT | 051633c8158a9c99b902289b771ca590d8b32b92 | 2026-01-04T17:56:21.148862Z | false |
red-data-tools/pandas.rb | https://github.com/red-data-tools/pandas.rb/blob/051633c8158a9c99b902289b771ca590d8b32b92/lib/pandas.rb | lib/pandas.rb | require "pandas/version"
require "numpy"
Pandas = PyCall.import_module("pandas")
module Pandas
VERSION = PANDAS_VERSION
Object.send :remove_const, :PANDAS_VERSION
DataFrame = self.core.frame.DataFrame
DataFrame.__send__ :register_python_type_mapping
Series = self.core.series.Series
Series.__send__ :register_python_type_mapping
IlocIndexer = self.core.indexing._iLocIndexer
IlocIndexer.__send__ :register_python_type_mapping
LocIndexer = self.core.indexing._LocIndexer
LocIndexer.__send__ :register_python_type_mapping
if self.__version__ < "1.0"
IXIndexer = self.core.indexing._IXIndexer
IXIndexer.__send__ :register_python_type_mapping
end
if self.__version__ >= "1.0"
MultiIndex = self.core.indexes.multi.MultiIndex
else
MultiIndex = self.core.indexing.MultiIndex
end
MultiIndex.__send__ :register_python_type_mapping
DatetimeIndex = if self.__version__ >= "0.20"
self.core.indexes.datetimes.DatetimeIndex
else
self.tseries.index.DatetimeIndex
end
DatetimeIndex.__send__ :register_python_type_mapping
if self.__version__ >= "1.0"
Index = self.core.indexes.base.Index
else
Index = self.core.index.Index
end
Index.__send__ :register_python_type_mapping
DataFrameGroupBy = self.core.groupby.DataFrameGroupBy
DataFrameGroupBy.__send__ :register_python_type_mapping
SeriesGroupBy = self.core.groupby.SeriesGroupBy
SeriesGroupBy.__send__ :register_python_type_mapping
IO = self.io
def self.read_sql_table(table_name, conn=nil, *args, **kwargs)
if conn.nil? && IO.is_activerecord_model?(table_name)
unless table_name.table_name
raise ArgumentError, "The given model does not have its table_name"
end
table_name, conn = table_name.table_name, table_name.connection
end
unless conn
raise ArgumentError, "wrong number of arguments (given 1, expected 2+)"
end
if IO.is_activerecord_datasource?(conn)
require 'pandas/io/active_record'
return IO::Helpers.read_sql_table_from_active_record(table_name, conn, *args, **kwargs)
end
super
end
def self.read_sql_query(query, conn, *args, **kwargs)
if IO.is_activerecord_datasource?(conn)
require 'pandas/io/active_record'
return IO::Helpers.read_sql_query_from_active_record(query, conn, *args, **kwargs)
end
super
end
require 'pandas/data_frame'
require 'pandas/index'
require 'pandas/io'
require 'pandas/loc_indexer'
require 'pandas/options'
require 'pandas/series'
end
| ruby | MIT | 051633c8158a9c99b902289b771ca590d8b32b92 | 2026-01-04T17:56:21.148862Z | false |
red-data-tools/pandas.rb | https://github.com/red-data-tools/pandas.rb/blob/051633c8158a9c99b902289b771ca590d8b32b92/lib/pandas/io.rb | lib/pandas/io.rb | require 'pandas' unless defined?(Pandas)
module Pandas
module IO
def self.is_activerecord_model?(obj)
return false unless defined?(::ActiveRecord)
return true if obj.is_a?(Class) && obj < ActiveRecord::Base
false
end
def self.is_activerecord_datasource?(obj)
return false unless defined?(::ActiveRecord)
return true if obj.is_a?(::ActiveRecord::ConnectionAdapters::AbstractAdapter)
false
end
end
end
| ruby | MIT | 051633c8158a9c99b902289b771ca590d8b32b92 | 2026-01-04T17:56:21.148862Z | false |
red-data-tools/pandas.rb | https://github.com/red-data-tools/pandas.rb/blob/051633c8158a9c99b902289b771ca590d8b32b92/lib/pandas/data_frame.rb | lib/pandas/data_frame.rb | require 'pandas' unless defined?(Pandas)
module Pandas
class DataFrame
def [](key)
key = PyCall::List.new(key) if key.is_a?(Array)
super
end
def to_narray
to_numpy.to_narray
end
def to_iruby_mimebundle(include: [], exclude: [])
include = ["text/html", "text/latex", "text/plain"] if include.empty?
include -= exclude unless exclude.empty?
include.map { |mime|
data = case mime
when "text/html"
_repr_html_
when "text/latex"
_repr_latex_
when "text/plain"
if respond_to?(:_repr_pretty_)
_repr_pretty_
else
__repr__
end
end
[mime, data] if data
}.compact.to_h
end
end
end
| ruby | MIT | 051633c8158a9c99b902289b771ca590d8b32b92 | 2026-01-04T17:56:21.148862Z | false |
red-data-tools/pandas.rb | https://github.com/red-data-tools/pandas.rb/blob/051633c8158a9c99b902289b771ca590d8b32b92/lib/pandas/version.rb | lib/pandas/version.rb | PANDAS_VERSION = "0.3.8"
| ruby | MIT | 051633c8158a9c99b902289b771ca590d8b32b92 | 2026-01-04T17:56:21.148862Z | false |
red-data-tools/pandas.rb | https://github.com/red-data-tools/pandas.rb/blob/051633c8158a9c99b902289b771ca590d8b32b92/lib/pandas/index.rb | lib/pandas/index.rb | require 'pandas' unless defined?(Pandas)
module Pandas
class Index
def monotonic_decreasing?
is_monotonic_decreasing
end
def monotonic_increasing?
is_monotonic_increasing
end
def unique?
is_unique
end
def length
size
end
def to_a
Array.new(length) {|i| self[i] }
end
def to_narray
to_numpy.to_narray
end
end
end
| ruby | MIT | 051633c8158a9c99b902289b771ca590d8b32b92 | 2026-01-04T17:56:21.148862Z | false |
red-data-tools/pandas.rb | https://github.com/red-data-tools/pandas.rb/blob/051633c8158a9c99b902289b771ca590d8b32b92/lib/pandas/options.rb | lib/pandas/options.rb | require 'pandas' unless defined?(Pandas)
module Pandas
module OptionsHelper
module_function
def setup_options(options)
PyCall::LibPython::Helpers.define_wrapper_method(options, :display)
options
end
end
def self.options
@options ||= begin
o = PyCall::LibPython::Helpers.getattr(__pyptr__, :options)
OptionsHelper.setup_options(o)
end
end
end
| ruby | MIT | 051633c8158a9c99b902289b771ca590d8b32b92 | 2026-01-04T17:56:21.148862Z | false |
red-data-tools/pandas.rb | https://github.com/red-data-tools/pandas.rb/blob/051633c8158a9c99b902289b771ca590d8b32b92/lib/pandas/loc_indexer.rb | lib/pandas/loc_indexer.rb | require 'pandas' unless defined?(Pandas)
module Pandas
class LocIndexer
def [](*keys)
for i in 0...keys.length
if keys[i].is_a? Array
keys[i] = PyCall::List.new(keys[i])
end
end
super
end
end
class IlocIndexer
def [](*keys)
for i in 0...keys.length
if keys[i].is_a? Array
keys[i] = PyCall::List.new(keys[i])
end
end
super
end
end
end
| ruby | MIT | 051633c8158a9c99b902289b771ca590d8b32b92 | 2026-01-04T17:56:21.148862Z | false |
red-data-tools/pandas.rb | https://github.com/red-data-tools/pandas.rb/blob/051633c8158a9c99b902289b771ca590d8b32b92/lib/pandas/series.rb | lib/pandas/series.rb | require 'pandas' unless defined?(Pandas)
module Pandas
class Series
def [](*key)
if key.length == 1
key[0] = fix_array_reference_key(key[0])
end
super
end
def []=(*args)
if args.length == 2
args[0] = fix_array_reference_key(args[0])
end
super
end
private def fix_array_reference_key(key)
case key
when Array
PyCall::List.new(key)
when Range
case key.begin
when String
# Force exclude-end
key.begin ... key.end
else
key
end
else
key
end
end
def monotonic_decreasing?
is_monotonic_decreasing
end
def monotonic_increasing?
is_monotonic_increasing
end
def unique?
is_unique
end
def length
size
end
def to_a
Array.new(length) {|i| self.iloc[i] }
end
def to_narray
to_numpy.to_narray
end
end
end
| ruby | MIT | 051633c8158a9c99b902289b771ca590d8b32b92 | 2026-01-04T17:56:21.148862Z | false |
red-data-tools/pandas.rb | https://github.com/red-data-tools/pandas.rb/blob/051633c8158a9c99b902289b771ca590d8b32b92/lib/pandas/io/active_record.rb | lib/pandas/io/active_record.rb | require 'pandas'
require 'active_record'
module Pandas
module IO
module Helpers
module_function
def read_sql_table_from_active_record(table_name, conn, *args)
case conn
when ActiveRecord::ConnectionAdapters::AbstractAdapter
read_sql_table_from_active_record_connection(table_name, conn, *args)
else
raise TypeError, "unexpected type of argument #{conn.class}"
end
end
def read_sql_query_from_active_record(query, conn, *args)
case conn
when ActiveRecord::ConnectionAdapters::AbstractAdapter
read_sql_query_from_active_record_connection(query, conn, *args)
else
raise TypeError, "unexpected type of argument #{conn.class}"
end
end
def read_sql_table_from_active_record_connection(table_name, conn, *args)
args = parse_read_sql_table_args(*args)
index_col, coerce_float, parse_dates, columns, schema, chunksize = *args
if columns
table_columns = conn.columns(table_name)
column_names = columns.select {|c| table_columns.include?(c) }.map do |c|
conn.quote_column_name(c.to_s)
end
else
column_names = '*'
end
query = <<-SQL
select #{column_names} from #{conn.quote_table_name(table_name)};
SQL
# TODO: chunksize
result = conn.exec_query(query, 'pandas_sql')
data_frame_from_query_result(result, index_col, coerce_float, parse_dates)
end
def read_sql_query_from_active_record_connection(query, conn, *args)
args = parse_read_sql_query_args(*args)
index_col, coerce_float, parse_dates, chunksize = *args
# TODO: chunksize
result = conn.exec_query(query, 'pandas_sql')
data_frame_from_query_result(result, index_col, coerce_float, parse_dates)
end
def data_frame_from_query_result(result, index_col, coerce_float, parse_dates)
records = result.map {|row| row.values }
df = Pandas::DataFrame.from_records(
records,
columns: result.columns,
coerce_float: coerce_float
)
# TODO: self.sql._harmonize_columns(parse_dates: parse_dates)
df.set_index(index_col, inplace: true) if index_col
df
end
def parse_read_sql_table_args(*args)
kwargs = args.pop if args.last.is_a? Hash
if kwargs
names = [:index_col, :coerce_float, :parse_dates, :columns, :schema, :chunksize]
names.each_with_index do |name, index|
if kwargs.has_key? name
if args[index]
warn "#{name} is given as both positional and keyword arguments"
else
args[index] = kwargs[name]
end
end
end
end
args
end
def parse_read_sql_query_args(*args)
kwargs = args.pop if args.last.is_a? Hash
if kwargs
names = [:index_col, :coerce_float, :parse_dates, :chunksize]
names.each_with_index do |name, index|
if kwargs.has_key? name
if args[index]
warn "#{name} is given as both positional and keyword arguments"
else
args[index] = kwargs[name]
end
end
end
end
args
end
end
end
end
| ruby | MIT | 051633c8158a9c99b902289b771ca590d8b32b92 | 2026-01-04T17:56:21.148862Z | false |
ryan-allen/lispy | https://github.com/ryan-allen/lispy/blob/b278da833b39037715fda744e0b9b8e7ebe4363d/test/lispy_test.rb | test/lispy_test.rb | require 'test/unit'
require 'lispy'
class LispyTest < Test::Unit::TestCase
def test_lispy
output = Lispy.new.to_data do
setup :workers => 30, :connections => 1024
http :access_log => :off do
server :listen => 80 do
location '/' do
doc_root '/var/www/website'
end
location '~ .php$' do
fcgi :port => 8877
script_root '/var/www/website'
end
end
end
end
expected = [[:setup, {:workers=>30, :connections=>1024}],
[:http,
{:access_log=>:off},
[[:server,
{:listen=>80},
[[:location, "/", [[:doc_root, "/var/www/website"]]],
[:location,
"~ .php$",
[[:fcgi, {:port=>8877}], [:script_root, "/var/www/website"]]]]]]]]
assert_equal expected, output
end
def test_moar_lispy
output = Lispy.new.to_data do
setup
setup do
lol
lol do
hi
hi
end
end
end
expected = [[:setup, []], [:setup, [], [[:lol, []], [:lol, [], [[:hi, []], [:hi, []]]]]]]
assert_equal expected, output
end
def lispy_but_conditionally_preserving_procs
Lispy.new.to_data(:retain_blocks_for => [:Given, :When, :Then]) do
Scenario "My first awesome scenario" do
Given "teh shiznit" do
#shiznit
end
When "I do something" do
#komg.do_something
end
Then "this is pending"
end
end
end
def test_conditionally_preserving_procs
quasi_sexp = lispy_but_conditionally_preserving_procs
assert_equal :Scenario, quasi_sexp[0][0]
assert_equal "My first awesome scenario", quasi_sexp[0][1]
assert_equal :Given, quasi_sexp[0][2][0][0]
assert_instance_of Proc, quasi_sexp[0][2][0].last
end
end
| ruby | MIT | b278da833b39037715fda744e0b9b8e7ebe4363d | 2026-01-04T17:56:21.363210Z | false |
ryan-allen/lispy | https://github.com/ryan-allen/lispy/blob/b278da833b39037715fda744e0b9b8e7ebe4363d/lib/lispy.rb | lib/lispy.rb | class Lispy
VERSION = '0.0.5'
@@methods_to_keep = /^__/, /class/, /instance_/, /method_missing/, /object_id/
instance_methods.each do |m|
undef_method m unless @@methods_to_keep.find { |r| r.match m }
end
def method_missing(sym, *args, &block)
args = (args.length == 1 ? args.first : args)
@scope.last << [sym, args]
if block
# there is some simpler recursive way of doing this, will fix it shortly
if @remember_blocks_starting_with.include? sym
@scope.last.last << block
else
@scope.last.last << []
@scope.push(@scope.last.last.last)
instance_exec(&block)
@scope.pop
end
end
end
def to_data(opts = {}, &block)
@remember_blocks_starting_with = Array(opts[:retain_blocks_for])
_(&block)
@output
end
private
def _(&block)
@output = []
@scope = [@output]
instance_exec(&block)
@output
end
end
| ruby | MIT | b278da833b39037715fda744e0b9b8e7ebe4363d | 2026-01-04T17:56:21.363210Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/js_from_routes/lib/js_from_routes.rb | js_from_routes/lib/js_from_routes.rb | # frozen_string_literal: true
# Splitting the generator file allows consumers to skip the Railtie if desired:
# - gem 'js_from_routes', require: false
# - require 'js_from_routes/generator'
require "js_from_routes/generator"
require "js_from_routes/railtie"
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/js_from_routes/lib/js_from_routes/version.rb | js_from_routes/lib/js_from_routes/version.rb | # frozen_string_literal: true
# Public: Automatically generates JS for Rails routes with { export: true }.
# Generates one file per controller, and one function per route.
module JsFromRoutes
# Public: This library adheres to semantic versioning.
VERSION = "4.0.2"
end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/js_from_routes/lib/js_from_routes/railtie.rb | js_from_routes/lib/js_from_routes/railtie.rb | # frozen_string_literal: true
require "rails/railtie"
# NOTE: Not strictly required, but it helps to simplify the setup.
class JsFromRoutes::Railtie < Rails::Railtie
railtie_name :js_from_routes
if Rails.env.development?
# Allows to automatically trigger code generation after updating routes.
initializer "js_from_routes.reloader" do |app|
app.config.to_prepare do
JsFromRoutes.generate!(app)
end
end
end
# Suitable when triggering code generation manually.
rake_tasks do |app|
namespace :js_from_routes do
desc "Generates JavaScript files from Rails routes, one file per controller, and one function per route."
task generate: :environment do
JsFromRoutes.generate!(app)
end
end
end
# Prevents Rails from interpreting the :export option as a required default,
# which would cause controller tests to fail.
initializer "js_from_routes.required_defaults" do |app|
ActionDispatch::Journey::Route.prepend Module.new {
def required_default?(key)
(key == :export) ? false : super
end
}
end
end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/js_from_routes/lib/js_from_routes/generator.rb | js_from_routes/lib/js_from_routes/generator.rb | # frozen_string_literal: true
require "digest"
require "erubi"
require "fileutils"
require "pathname"
# Public: Automatically generates JS for Rails routes with { export: true }.
# Generates one file per controller, and one function per route.
module JsFromRoutes
# Internal: Helper class used as a presenter for the routes template.
class ControllerRoutes
attr_reader :routes
def initialize(controller, routes, config)
@controller, @config = controller, config
@routes = routes
.reject { |route| route.requirements[:action] == "update" && route.verb == "PUT" }
.group_by { |route| route.requirements.fetch(:action) }
.flat_map { |action, routes|
routes.each_with_index.map { |route, index|
Route.new(route, mappings: config.helper_mappings, index:, controller:)
}
}
end
# Public: Used to check whether the file should be generated again, changes
# based on the configuration, and route definition.
def cache_key
routes.map(&:inspect).join + [File.read(@config.template_path), @config.helper_mappings.inspect, @config.client_library].join
end
# Public: Exposes the preferred import library to the generator.
def client_library
@config.client_library
end
# Internal: Name of the JS file with helpers for the the given controller.
def filename
@config.output_folder.join(basename)
end
# Public: Name of the JS file with helpers for the the given controller.
def import_filename
filename.relative_path_from(@config.output_folder).to_s.sub(/\.\w+$/, "")
end
# Public: Name of the file as a valid JS variable.
def js_name
@controller.camelize(:lower).tr(":", "")
end
# Internal: The base name of the JS file to be written.
def basename
"#{@controller.camelize}#{@config.file_suffix}".tr_s(":", "/")
end
end
# Internal: A presenter for an individual Rails action.
class Route
def initialize(route, mappings:, controller:, index: 0)
@route, @mappings, @controller, @index = route, mappings, controller, index
end
# Public: The `export` setting specified for the action.
def export
@route.defaults[:export]
end
# Public: The HTTP verb for the action. Example: 'patch'
def verb
@route.verb.split("|").last.downcase
end
# Public: The path for the action. Example: '/users/:id/edit'
def path
@route.path.spec.to_s.chomp("(.:format)")
end
# Public: The name of the JS helper for the action. Example: 'destroyAll'
def helper
action = @route.requirements.fetch(:action)
if @index > 0
action = @route.name&.sub(@controller.tr(":/", "_"), "") || "#{action}#{verb.titleize}"
end
helper = action.camelize(:lower)
@mappings.fetch(helper, helper)
end
# Internal: Useful as a cache key for the route, and for debugging purposes.
def inspect
"#{verb} #{helper} #{path}"
end
end
# Internal: Represents a compiled template that can write itself to a file.
class Template
def initialize(template_path)
# NOTE: The compiled ERB template, used to generate JS code.
@compiled_template = Erubi::Engine.new(File.read(template_path), filename: template_path).src
end
# Public: Checks if the cache is fresh, or renders the template with the
# specified variables, and writes the updated result to a file.
def write_if_changed(object)
write_file_if_changed(object.filename, object.cache_key) { render_template(object) }
end
private
# Internal: Returns a String with the generated JS code.
def render_template(object)
object.instance_eval(@compiled_template)
end
# Internal: Returns true if the cache key has changed since the last codegen.
def stale?(file, cache_key_comment)
ENV["JS_FROM_ROUTES_FORCE"] || file.gets != cache_key_comment
end
# Internal: Writes if the file does not exist or the cache key has changed.
# The cache strategy consists of a comment on the first line of the file.
#
# Yields to receive the rendered file content when it needs to.
def write_file_if_changed(name, cache_key)
FileUtils.mkdir_p(name.dirname)
cache_key_comment = "// JsFromRoutes CacheKey #{Digest::MD5.hexdigest(cache_key)}\n"
File.open(name, "a+") { |file|
if stale?(file, cache_key_comment)
file.truncate(0)
file.write(cache_key_comment)
file.write(yield)
end
}
end
end
class Configuration
attr_accessor :all_helpers_file, :client_library, :export_if, :file_suffix,
:helper_mappings, :output_folder, :template_path,
:template_all_path, :template_index_path
def initialize(root)
dir = %w[frontend packs javascript assets].find { |dir| root.join("app", dir).exist? }
@all_helpers_file = true
@client_library = "@js-from-routes/client"
@export_if = ->(route) { route.defaults.fetch(:export, nil) }
@file_suffix = "Api.js"
@helper_mappings = {}
@output_folder = root.join("app", dir, "api")
@template_path = File.expand_path("template.js.erb", __dir__)
@template_all_path = File.expand_path("template_all.js.erb", __dir__)
@template_index_path = File.expand_path("template_index.js.erb", __dir__)
end
end
class TemplateConfig
attr_reader :cache_key, :filename, :helpers
def initialize(cache_key:, filename:, helpers: nil)
@cache_key = cache_key
@filename = filename
@helpers = helpers
end
end
class << self
# Public: Configuration of the code generator.
def config
@config ||= Configuration.new(::Rails.root || Pathname.new(Dir.pwd))
yield(@config) if block_given?
@config
end
# Public: Generates code for the specified routes with { export: true }.
def generate!(app_or_routes = Rails.application)
raise ArgumentError, "A Rails app must be defined, or you must specify a custom `output_folder`" if config.output_folder.to_s.blank?
rails_routes = app_or_routes.is_a?(::Rails::Engine) ? app_or_routes.routes.routes : app_or_routes
generate_files exported_routes_by_controller(rails_routes)
end
private
def generate_files(exported_routes)
template = Template.new(config.template_path)
generate_file_for_all exported_routes.filter_map { |controller, routes|
next unless controller
ControllerRoutes.new(controller, routes, config).tap do |routes|
template.write_if_changed routes
end
}
end
def generate_file_for_all(routes)
return unless config.all_helpers_file && !routes.empty?
preferred_extension = File.extname(config.file_suffix)
index_file = (config.all_helpers_file == true) ? "index#{preferred_extension}" : config.all_helpers_file
Template.new(config.template_all_path).write_if_changed TemplateConfig.new(
cache_key: routes.map(&:import_filename).join + File.read(config.template_all_path),
filename: config.output_folder.join("all#{preferred_extension}"),
helpers: routes,
)
Template.new(config.template_index_path).write_if_changed TemplateConfig.new(
cache_key: File.read(config.template_index_path),
filename: config.output_folder.join(index_file),
)
end
def namespace_for_route(route)
if (export = route.defaults[:export]).is_a?(Hash)
export[:namespace]
end || route.requirements[:controller]
end
# Internal: Returns exported routes grouped by controller name.
def exported_routes_by_controller(routes)
routes
.select { |route| config.export_if.call(route) }
.group_by { |route| namespace_for_route(route)&.to_s }
end
end
end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/spec/spec_helper.rb | spec/spec_helper.rb | require "simplecov"
SimpleCov.start {
add_filter "/spec/"
add_filter "/playground/"
}
require "rails"
require "js_from_routes"
require "rspec/given"
require "pry-byebug"
$LOAD_PATH.push File.expand_path("../playground", __dir__)
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/spec/js_from_routes/js_from_routes_spec.rb | spec/js_from_routes/js_from_routes_spec.rb | require "vanilla/config/application"
require "vanilla/config/routes"
describe JsFromRoutes do
original_template_path = JsFromRoutes.config.template_path
let(:output_dir) { Pathname.new File.expand_path("../support/generated", __dir__) }
let(:sample_dir) { Rails.root.join("app", "javascript", "api") }
let(:different_template_path) { File.expand_path("../support/jquery_template.js.erb", __dir__) }
let(:controllers_with_exported_routes) { %w[Comments Settings/UserPreferences VideoClips] }
def file_for(dir, name)
dir.join("#{name}Api.ts")
end
def sample_file_for(name)
file_for(sample_dir, name)
end
def output_file_for(name)
file_for(output_dir, name)
end
def expect_templates
expect_any_instance_of(JsFromRoutes::Template)
end
def be_rendered
receive(:render_template)
end
before do
# Sanity checks
expect(sample_dir.exist?).to eq true
expect(Rails.application.routes.routes).to be_present
# Remove directory from a previous test run.
begin
FileUtils.remove_dir(output_dir)
rescue
nil
end
# Change the configuration to use a different directory.
JsFromRoutes.config do |config|
config.file_suffix = "Api.ts"
config.all_helpers_file = false
config.output_folder = output_dir
config.template_path = original_template_path
end
end
# NOTE: We do a manual snapshot test for now, more tests coming in the future.
it "should generate the files as expected" do
expect_templates.to be_rendered.exactly(3).times.and_call_original
JsFromRoutes.generate!
# It does not generate routes that don't have `export: true`.
expect(output_file_for("Welcome").exist?).to eq false
# It generates one file per controller with exported routes.
controllers_with_exported_routes.each do |file_name|
expect(output_file_for(file_name).read).to eq sample_file_for(file_name).read
end
# It does not render if generating again.
JsFromRoutes.generate!
end
context "changing the template" do
before do
JsFromRoutes.generate!
JsFromRoutes.config do |config|
config.template_path = different_template_path
end
end
it "detects changes and re-renders" do
expect_templates.to be_rendered.exactly(3).times.and_call_original
JsFromRoutes.generate!
# These files should no longer match the sample ones.
controllers_with_exported_routes.each do |file_name|
expect(output_file_for(file_name).read).not_to eq sample_file_for(file_name).read
end
# It should not rewrite the files if the cache key has not changed.
JsFromRoutes.generate!
end
end
context "when generating all_helpers_file" do
before do
JsFromRoutes.generate!
JsFromRoutes.config do |config|
config.all_helpers_file = true
end
end
it "generates a file with all helpers" do
JsFromRoutes.generate!
expect(output_dir.join("all.ts").exist?).to eq true
expect(output_dir.join("index.ts").exist?).to eq true
# Should not trigger another render.
expect_templates.not_to be_rendered
JsFromRoutes.generate!
end
end
it "should have a rake task available" do
Rails.application.load_tasks
expect_templates.to be_rendered.exactly(3).times
expect { Rake::Task["js_from_routes:generate"].invoke }.not_to raise_error
end
end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/app/controllers/video_clips_controller.rb | playground/vanilla/app/controllers/video_clips_controller.rb | class VideoClipsController < ApplicationController
def download
render body: "", status: 204
end
def latest
render json: [
{id: 11, title: "Smoke Signals", composer_name: "Dylan Ryche"},
{id: 10, title: "Camino Libre", composer_name: "Máximo Mussini"},
{id: 9, title: "Sin Querer", composer_name: "León Gieco"},
{id: 8, title: "Tabula Rasa", composer_name: "Calum Graham"},
{id: 7, title: "Raindance", composer_name: "Matteo Brenci"},
{id: 6, title: "Ragamuffin", composer_name: "Michael Hedges"},
{id: 5, title: "Vals Venezolano Nº 2", composer_name: "Antonio Lauro"},
{id: 4, title: "Xaranga do Vovô", composer_name: "Celso Machado"},
{id: 3, title: "Café 1930", composer_name: "Astor Piazzolla"},
{id: 2, title: "Milonga (Uruguay)", composer_name: "Jorge Cardoso"},
{id: 1, title: "Divagando", composer_name: "Domingos Semenzato"}
]
end
end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/app/controllers/welcome_controller.rb | playground/vanilla/app/controllers/welcome_controller.rb | class WelcomeController < ApplicationController
end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/app/controllers/comments_controller.rb | playground/vanilla/app/controllers/comments_controller.rb | class CommentsController < ApplicationController
end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/app/controllers/application_controller.rb | playground/vanilla/app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/app/controllers/settings/user_preferences_controller.rb | playground/vanilla/app/controllers/settings/user_preferences_controller.rb | class Settings::UserPreferencesController < ApplicationController
end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/spec/rails_helper.rb | playground/vanilla/spec/rails_helper.rb | # This file is copied to spec/ when you run 'rails generate rspec:install'
require "spec_helper"
ENV["RAILS_ENV"] ||= "test"
require File.expand_path("../config/environment", __dir__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require "rspec/rails"
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }
RSpec.configure do |config|
# Remove this line to enable support for ActiveRecord
config.use_active_record = false
# If you enable ActiveRecord support you should unncomment these lines,
# note if you'd prefer not to run each example within a transaction, you
# should set use_transactional_fixtures to false.
#
# config.fixture_path = "#{::Rails.root}/spec/fixtures"
# config.use_transactional_fixtures = true
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, type: :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/spec/spec_helper.rb | playground/vanilla/spec/spec_helper.rb | # This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
# # This allows you to limit a spec run to individual examples or groups
# # you care about by tagging them with `:focus` metadata. When nothing
# # is tagged with `:focus`, all examples get run. RSpec also provides
# # aliases for `it`, `describe`, and `context` that include `:focus`
# # metadata: `fit`, `fdescribe` and `fcontext`, respectively.
# config.filter_run_when_matching :focus
#
# # Allows RSpec to persist some state between runs in order to support
# # the `--only-failures` and `--next-failure` CLI options. We recommend
# # you configure your source control system to ignore this file.
# config.example_status_persistence_file_path = "spec/examples.txt"
#
# # Limits the available syntax to the non-monkey patched syntax that is
# # recommended. For more details, see:
# # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
# config.disable_monkey_patching!
#
# # Many RSpec users commonly either run the entire suite or an individual
# # file, and it's useful to allow more verbose output when running an
# # individual spec file.
# if config.files_to_run.one?
# # Use the documentation formatter for detailed output,
# # unless a formatter has already been configured
# # (e.g. via a command-line flag).
# config.default_formatter = "doc"
# end
#
# # Print the 10 slowest examples and example groups at the
# # end of the spec run, to help surface which specs are running
# # particularly slow.
# config.profile_examples = 10
#
# # Run specs in random order to surface order dependencies. If you find an
# # order dependency and want to debug it, you can fix the order by providing
# # the seed, which is printed after each run.
# # --seed 1234
# config.order = :random
#
# # Seed global randomization in this process using the `--seed` CLI option.
# # Setting this allows you to use `--seed` to deterministically reproduce
# # test failures related to randomization by passing the same `--seed` value
# # as the one that triggered the failure.
# Kernel.srand config.seed
end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/spec/controllers/video_clips_spec.rb | playground/vanilla/spec/controllers/video_clips_spec.rb | require "rails_helper"
RSpec.describe VideoClipsController, type: :controller do
describe "GET /" do
it "should make a request" do
get :new
expect(response).to render_template(:new)
end
end
end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/config/application.rb | playground/vanilla/config/application.rb | require_relative "boot"
require "action_controller/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module SampleApp
class Application < Rails::Application
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
end
end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/config/environment.rb | playground/vanilla/config/environment.rb | # Load the Rails application.
require_relative "application"
# Initialize the Rails application.
Rails.application.initialize!
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/config/puma.rb | playground/vanilla/config/puma.rb | # Puma can serve each request in a thread from an internal thread pool.
# The `threads` method setting takes two numbers: a minimum and maximum.
# Any libraries that use thread pools should be configured to match
# the maximum value specified for Puma. Default is set to 5 threads for minimum
# and maximum; this matches the default thread size of Active Record.
#
max_threads_count = ENV.fetch("RAILS_MAX_THREADS", 5)
min_threads_count = ENV.fetch("RAILS_MIN_THREADS", max_threads_count)
threads min_threads_count, max_threads_count
# Specifies the `port` that Puma will listen on to receive requests; default is 3000.
#
port ENV.fetch("PORT", 3000)
# Specifies the `environment` that Puma will run in.
#
environment ENV.fetch("RAILS_ENV") { "development" }
# Specifies the `pidfile` that Puma will use.
pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" }
# Specifies the number of `workers` to boot in clustered mode.
# Workers are forked web server processes. If using threads and workers together
# the concurrency of the application would be max `threads` * `workers`.
# Workers do not work on JRuby or Windows (both of which do not support
# processes).
#
# workers ENV.fetch("WEB_CONCURRENCY") { 2 }
# Use the `preload_app!` method when specifying a `workers` number.
# This directive tells Puma to first boot the application and load code
# before forking the application. This takes advantage of Copy On Write
# process behavior so workers use less memory.
#
# preload_app!
# Allow puma to be restarted by `rails restart` command.
plugin :tmp_restart
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/config/routes.rb | playground/vanilla/config/routes.rb | Rails.application.routes.draw do
root to: "welcome#home"
defaults export: true do
get "/hi" => redirect("/welcome")
end
resources :welcome
resources :video_clips, only: [:new, :edit, :create, :update, :destroy], export: true do
get :download, on: :member
patch :add_to_playlist, on: :member
patch :remove_from_playlist, on: :member
get :latest, on: :collection
get "/thumbnail/:thumbnail_id", as: :thumbnail, action: :thumbnail, on: :member
resources :comments, only: [:show, :index], shallow: true
end
namespace :settings, path: "/" do
resources :user_preferences, only: [], export: true do
patch :switch_to_classic_navbar, on: :collection
get :switch_to_beta_navbar, on: :collection, export: false
get "/switch_to_classic/:page", action: :switch_to_classic, on: :collection
get "/switch_to_beta/:page", action: :switch_to_beta, on: :collection, as: :switch_to_beta_page
end
end
end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/config/boot.rb | playground/vanilla/config/boot.rb | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__)
require "bundler/setup" # Set up gems listed in the Gemfile.
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/config/initializers/content_security_policy.rb | playground/vanilla/config/initializers/content_security_policy.rb | # Be sure to restart your server when you modify this file.
# Define an application-wide content security policy
# For further information see the following documentation
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
# Rails.application.config.content_security_policy do |policy|
# policy.default_src :self, :https
# policy.font_src :self, :https, :data
# policy.img_src :self, :https, :data
# policy.object_src :none
# policy.script_src :self, :https
# Allow @vite/client to hot reload changes in development
# policy.script_src *policy.script_src, :unsafe_eval, "http://localhost:3036" if Rails.env.development?
# You may need to enable this in production as well depending on your setup.
# policy.script_src *policy.script_src, :blob if Rails.env.test?
# policy.style_src :self, :https
# # If you are using webpack-dev-server then specify webpack-dev-server host
# policy.connect_src :self, :https, "http://localhost:3035", "ws://localhost:3035" if Rails.env.development?
# Allow @vite/client to hot reload changes in development
# policy.connect_src *policy.connect_src, "ws://#{ ViteRuby.config.host_with_port }" if Rails.env.development?
# # Specify URI for violation reports
# # policy.report_uri "/csp-violation-report-endpoint"
# end
# If you are using UJS then enable automatic nonce generation
# Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
# Set the nonce only to specific directives
# Rails.application.config.content_security_policy_nonce_directives = %w(script-src)
# Report CSP violations to a specified URI
# For further information see the following documentation:
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
# Rails.application.config.content_security_policy_report_only = true
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/config/initializers/filter_parameter_logging.rb | playground/vanilla/config/initializers/filter_parameter_logging.rb | # Be sure to restart your server when you modify this file.
# Configure sensitive parameters which will be filtered from the log file.
Rails.application.config.filter_parameters += [:password]
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/config/initializers/application_controller_renderer.rb | playground/vanilla/config/initializers/application_controller_renderer.rb | # Be sure to restart your server when you modify this file.
# ActiveSupport::Reloader.to_prepare do
# ApplicationController.renderer.defaults.merge!(
# http_host: 'example.org',
# https: false
# )
# end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/config/initializers/js_from_routes.rb | playground/vanilla/config/initializers/js_from_routes.rb | if Rails.env.development?
# Example: Generate TypeScript files.
JsFromRoutes.config do |config|
config.file_suffix = "Api.ts"
end
end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/config/initializers/wrap_parameters.rb | playground/vanilla/config/initializers/wrap_parameters.rb | # Be sure to restart your server when you modify this file.
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) { wrap_parameters format: [:json] }
# To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do
# self.include_root_in_json = true
# end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/config/initializers/inflections.rb | playground/vanilla/config/initializers/inflections.rb | # Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format. Inflections
# are locale specific, and you may define rules for as many different
# locales as you wish. All of these examples are active by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.acronym 'RESTful'
# end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/config/initializers/cookies_serializer.rb | playground/vanilla/config/initializers/cookies_serializer.rb | # Be sure to restart your server when you modify this file.
# Specify a serializer for the signed and encrypted cookie jars.
# Valid options are :json, :marshal, and :hybrid.
Rails.application.config.action_dispatch.cookies_serializer = :json
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/config/initializers/backtrace_silencers.rb | playground/vanilla/config/initializers/backtrace_silencers.rb | # Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/config/initializers/mime_types.rb | playground/vanilla/config/initializers/mime_types.rb | # Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/config/environments/test.rb | playground/vanilla/config/environments/test.rb | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
config.cache_classes = true
config.eager_load = true
end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
ElMassimo/js_from_routes | https://github.com/ElMassimo/js_from_routes/blob/dcd67342892987c3ae70d887b5aa21360c9b8ed7/playground/vanilla/config/environments/development.rb | playground/vanilla/config/environments/development.rb | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Store uploaded files on the local file system (see config/storage.yml for options).
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
| ruby | MIT | dcd67342892987c3ae70d887b5aa21360c9b8ed7 | 2026-01-04T17:56:29.052124Z | false |
sous-chefs/git | https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/metadata.rb | metadata.rb | name 'git'
maintainer 'Sous Chefs'
maintainer_email 'help@sous-chefs.org'
license 'Apache-2.0'
description 'Installs git and/or sets up a Git server daemon'
version '12.1.10'
source_url 'https://github.com/sous-chefs/git'
issues_url 'https://github.com/sous-chefs/git/issues'
chef_version '>= 15.3'
depends 'ark'
supports 'amazon'
supports 'centos'
supports 'debian'
supports 'fedora'
supports 'freebsd'
supports 'mac_os_x'
supports 'omnios'
supports 'opensuseleap'
supports 'oracle'
supports 'redhat'
supports 'scientific'
supports 'smartos'
supports 'suse'
supports 'ubuntu'
supports 'windows'
| ruby | Apache-2.0 | 83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43 | 2026-01-04T17:56:43.177115Z | false |
sous-chefs/git | https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/test/integration/source/git_installed_spec.rb | test/integration/source/git_installed_spec.rb | describe command('/usr/local/bin/git --version') do
its('exit_status') { should eq 0 }
its('stdout') { should match /git version/ }
end
| ruby | Apache-2.0 | 83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43 | 2026-01-04T17:56:43.177115Z | false |
sous-chefs/git | https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/test/integration/server/git_daemon_spec.rb | test/integration/server/git_daemon_spec.rb | describe port(9418) do
it { should be_listening }
its('protocols') { should eq ['tcp'] }
end
| ruby | Apache-2.0 | 83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43 | 2026-01-04T17:56:43.177115Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.