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 |
|---|---|---|---|---|---|---|---|---|
thoughtbot/kumade | https://github.com/thoughtbot/kumade/blob/271510307b7037695988aa4881c7c17445cc9d1d/lib/kumade/deployment_error.rb | lib/kumade/deployment_error.rb | module Kumade
class DeploymentError < StandardError
end
end
| ruby | MIT | 271510307b7037695988aa4881c7c17445cc9d1d | 2026-01-04T17:45:11.500917Z | false |
thoughtbot/kumade | https://github.com/thoughtbot/kumade/blob/271510307b7037695988aa4881c7c17445cc9d1d/lib/kumade/railtie.rb | lib/kumade/railtie.rb | if defined?(Rails::Railtie)
module Kumade
class Railtie < ::Rails::Railtie
rake_tasks do
load "kumade/tasks/deploy.rake"
end
end
end
end
| ruby | MIT | 271510307b7037695988aa4881c7c17445cc9d1d | 2026-01-04T17:45:11.500917Z | false |
thoughtbot/kumade | https://github.com/thoughtbot/kumade/blob/271510307b7037695988aa4881c7c17445cc9d1d/lib/kumade/configuration.rb | lib/kumade/configuration.rb | module Kumade
class Configuration
attr_writer :pretending, :environment
def pretending?
@pretending || false
end
def environment
@environment || "staging"
end
def outputter
@outputter ||= Outputter.new
end
def outputter=(new_outputter)
@outputter = new_outputter
end
end
end
| ruby | MIT | 271510307b7037695988aa4881c7c17445cc9d1d | 2026-01-04T17:45:11.500917Z | false |
thoughtbot/kumade | https://github.com/thoughtbot/kumade/blob/271510307b7037695988aa4881c7c17445cc9d1d/lib/kumade/packager_list.rb | lib/kumade/packager_list.rb | module Kumade
class PackagerList
include Enumerable
PACKAGERS = [JammitPackager]
def initialize
@packagers = build_packagers_list
end
def each(&block)
@packagers.each(&block)
end
private
def build_packagers_list
if installed_packagers.any?
installed_packagers
else
[NoopPackager]
end
end
def installed_packagers
PACKAGERS.select(&:installed?)
end
end
end
| ruby | MIT | 271510307b7037695988aa4881c7c17445cc9d1d | 2026-01-04T17:45:11.500917Z | false |
thoughtbot/kumade | https://github.com/thoughtbot/kumade/blob/271510307b7037695988aa4881c7c17445cc9d1d/lib/kumade/heroku.rb | lib/kumade/heroku.rb | require 'cocaine'
module Kumade
class Heroku
DEPLOY_BRANCH = "deploy"
attr_reader :git
def initialize
@git = Git.new
@branch = @git.current_branch
end
def sync
git.create(DEPLOY_BRANCH)
git.push("#{DEPLOY_BRANCH}:master", Kumade.configuration.environment, true)
end
def migrate_database
heroku("rake db:migrate") unless Kumade.configuration.pretending?
Kumade.configuration.outputter.success("Migrated #{Kumade.configuration.environment}")
end
def restart_app
unless Kumade.configuration.pretending?
heroku("restart")
end
Kumade.configuration.outputter.success("Restarted #{Kumade.configuration.environment}")
end
def delete_deploy_branch
git.delete(DEPLOY_BRANCH, @branch)
end
def heroku(command)
full_heroku_command = "#{bundle_exec_heroku(command)} --remote #{Kumade.configuration.environment}"
command_line = CommandLine.new(full_heroku_command)
command_line.run_or_error("Failed to run #{command} on Heroku")
end
def cedar?
return @cedar unless @cedar.nil?
command_line = CommandLine.new("bundle exec heroku stack --remote #{Kumade.configuration.environment}")
@cedar = command_line.run_or_error.split("\n").grep(/\*/).any? do |line|
line.include?("cedar")
end
end
private
def bundle_exec_heroku(command)
if cedar? && command != 'restart'
"bundle exec heroku run #{command}"
else
"bundle exec heroku #{command}"
end
end
end
end
| ruby | MIT | 271510307b7037695988aa4881c7c17445cc9d1d | 2026-01-04T17:45:11.500917Z | false |
thoughtbot/kumade | https://github.com/thoughtbot/kumade/blob/271510307b7037695988aa4881c7c17445cc9d1d/lib/kumade/cli.rb | lib/kumade/cli.rb | require 'optparse'
require 'stringio'
module Kumade
class CLI
class << self
attr_writer :deployer
def deployer
@deployer || Kumade::Deployer
end
end
def initialize(args = ARGV, out = StringIO.new)
@options = {}
parse_arguments!(args)
Kumade.configuration.pretending = !!@options[:pretend]
Kumade.configuration.environment = args.shift
self.class.swapping_stdout_for(out, print_output?) do
deploy
end
end
def self.swapping_stdout_for(io, print_output = false)
if print_output
yield
else
begin
real_stdout = $stdout
$stdout = io
yield
rescue Kumade::DeploymentError
io.rewind
real_stdout.print(io.read)
exit 1
ensure
$stdout = real_stdout
end
end
end
private
def deploy
if Kumade.configuration.pretending?
Kumade.configuration.outputter.info("In Pretend Mode")
end
Kumade.configuration.outputter.info("Deploying to: #{Kumade.configuration.environment}")
self.class.deployer.new.deploy
Kumade.configuration.outputter.info("Deployed to: #{Kumade.configuration.environment}")
end
def parse_arguments!(args)
OptionParser.new do |opts|
opts.banner = "Usage: kumade <environment> [options]"
opts.on("-p", "--pretend", "Pretend mode: print what kumade would do") do |p|
@options[:pretend] = true
end
opts.on_tail("-v", "--verbose", "Print what kumade is doing") do
@options[:verbose] = true
end
opts.on_tail('--version', 'Show version') do
puts "kumade #{Kumade::VERSION}"
exit
end
opts.on_tail('-h', '--help', 'Show this message') do
puts opts
exit
end
end.parse!(args)
end
def verbose?
@options[:verbose]
end
def print_output?
Kumade.configuration.pretending? || verbose?
end
end
end
| ruby | MIT | 271510307b7037695988aa4881c7c17445cc9d1d | 2026-01-04T17:45:11.500917Z | false |
thoughtbot/kumade | https://github.com/thoughtbot/kumade/blob/271510307b7037695988aa4881c7c17445cc9d1d/lib/kumade/command_line.rb | lib/kumade/command_line.rb | require 'cocaine'
module Kumade
class CommandLine
def initialize(command_to_run)
@command_line = Cocaine::CommandLine.new(command_to_run)
end
def run_or_error(error_message = nil)
run_with_status || Kumade.configuration.outputter.error(error_message)
end
def run_with_status
Kumade.configuration.outputter.say_command(command)
Kumade.configuration.pretending? || run
end
def run
begin
@command_line.run
rescue Cocaine::ExitStatusError, Cocaine::CommandNotFoundError
false
end
end
private
def command
@command_line.command
end
end
end
| ruby | MIT | 271510307b7037695988aa4881c7c17445cc9d1d | 2026-01-04T17:45:11.500917Z | false |
thoughtbot/kumade | https://github.com/thoughtbot/kumade/blob/271510307b7037695988aa4881c7c17445cc9d1d/lib/kumade/deployer.rb | lib/kumade/deployer.rb | require "rake"
require 'cocaine'
module Kumade
class Deployer
attr_reader :git, :heroku, :packager
def initialize
@git = Git.new
@heroku = Heroku.new
@branch = @git.current_branch
@packager = Packager.new(@git)
end
def deploy
begin
ensure_heroku_remote_exists
pre_deploy
heroku.sync
heroku.migrate_database
heroku.restart_app
post_deploy_success
rescue => deploying_error
Kumade.configuration.outputter.error("#{deploying_error.class}: #{deploying_error.message}")
ensure
post_deploy
end
end
def pre_deploy
ensure_clean_git
run_pre_deploy_task
package_assets
sync_origin
end
def post_deploy_success
run_post_deploy_task
end
def package_assets
@packager.run
end
def sync_origin
git.push(@branch)
end
def post_deploy
heroku.delete_deploy_branch
end
def ensure_clean_git
git.ensure_clean_git
end
def ensure_heroku_remote_exists
if git.remote_exists?(Kumade.configuration.environment)
if git.heroku_remote?
Kumade.configuration.outputter.success("#{Kumade.configuration.environment} is a Heroku remote")
else
Kumade.configuration.outputter.error(%{Cannot deploy: "#{Kumade.configuration.environment}" remote does not point to Heroku})
end
else
Kumade.configuration.outputter.error(%{Cannot deploy: "#{Kumade.configuration.environment}" remote does not exist})
end
end
private
def run_pre_deploy_task
RakeTaskRunner.new("kumade:pre_deploy").invoke
end
def run_post_deploy_task
RakeTaskRunner.new("kumade:post_deploy").invoke
end
end
end
| ruby | MIT | 271510307b7037695988aa4881c7c17445cc9d1d | 2026-01-04T17:45:11.500917Z | false |
thoughtbot/kumade | https://github.com/thoughtbot/kumade/blob/271510307b7037695988aa4881c7c17445cc9d1d/lib/kumade/rake_task_runner.rb | lib/kumade/rake_task_runner.rb | module Kumade
class RakeTaskRunner
def initialize(task_name)
@task_name = task_name
end
def invoke
return unless task_defined?
Kumade.configuration.outputter.success("Running rake task: #{@task_name}")
Rake::Task[@task_name].invoke if task_should_be_run?
end
private
def task_defined?
load_rakefile
Rake::Task.task_defined?(@task_name)
end
def task_should_be_run?
!Kumade.configuration.pretending?
end
def load_rakefile
load("Rakefile") if File.exist?("Rakefile")
end
end
end
| ruby | MIT | 271510307b7037695988aa4881c7c17445cc9d1d | 2026-01-04T17:45:11.500917Z | false |
thoughtbot/kumade | https://github.com/thoughtbot/kumade/blob/271510307b7037695988aa4881c7c17445cc9d1d/lib/kumade/outputter.rb | lib/kumade/outputter.rb | module Kumade
class Outputter
def success(message)
STDOUT.puts "==> #{message}"
end
def info(message)
STDOUT.puts "==> #{message}"
end
def error(message)
STDOUT.puts "==> ! #{message}"
raise Kumade::DeploymentError, message
end
def say_command(command)
prefix = " " * 8
STDOUT.puts "#{prefix}#{command}"
end
end
end
| ruby | MIT | 271510307b7037695988aa4881c7c17445cc9d1d | 2026-01-04T17:45:11.500917Z | false |
thoughtbot/kumade | https://github.com/thoughtbot/kumade/blob/271510307b7037695988aa4881c7c17445cc9d1d/lib/kumade/git.rb | lib/kumade/git.rb | require 'cocaine'
module Kumade
class Git
def heroku_remote?
remote_url = `git config --get remote.#{Kumade.configuration.environment}.url`.strip
!! remote_url.strip.match(/^git@heroku\..+:(.+)\.git$/)
end
def self.environments
url_remotes = `git remote`.strip.split("\n").map{|remote| [remote, `git config --get remote.#{remote}.url`.strip] }.select{|remote| remote.last =~ /^git@heroku\.com:(.+)\.git$/}.map{|remote| remote.first}
end
def push(branch, remote = 'origin', force = false)
return unless remote_exists?(remote)
command = ["git push"]
command << "-f" if force
command << remote
command << branch
command = command.join(" ")
command_line = CommandLine.new(command)
command_line.run_or_error("Failed to push #{branch} -> #{remote}")
Kumade.configuration.outputter.success("Pushed #{branch} -> #{remote}")
end
def create(branch)
unless has_branch?(branch)
CommandLine.new("git branch #{branch} >/dev/null").run_or_error("Failed to create #{branch}")
end
end
def delete(branch_to_delete, branch_to_checkout)
if has_branch?(branch_to_delete)
command_line = CommandLine.new("git checkout #{branch_to_checkout} 2>/dev/null && git branch -D #{branch_to_delete}")
command_line.run_or_error("Failed to clean up #{branch_to_delete} branch")
end
end
def add_and_commit_all_assets_in(dir)
command = ["git checkout -b #{Kumade::Heroku::DEPLOY_BRANCH} 2>/dev/null",
"git add -f #{dir}",
"git commit -m 'Compiled assets.'"].join(' && ')
command_line = CommandLine.new(command)
command_line.run_or_error("Cannot deploy: couldn't commit assets")
Kumade.configuration.outputter.success("Added and committed all assets")
end
def current_branch
`git symbolic-ref HEAD`.sub("refs/heads/", "").strip
end
def remote_exists?(remote_name)
if Kumade.configuration.pretending?
true
else
`git remote` =~ /^#{remote_name}$/
end
end
def dirty?
! CommandLine.new("git diff --exit-code").run
end
def ensure_clean_git
if ! Kumade.configuration.pretending? && dirty?
Kumade.configuration.outputter.error("Cannot deploy: repo is not clean.")
else
Kumade.configuration.outputter.success("Git repo is clean")
end
end
def has_untracked_files_in?(directory)
relative_dir = directory.sub(Dir.pwd + '/', '')
untracked_output = CommandLine.new("git status --porcelain --untracked-files").run
untracked_output.split("\n").grep(/^\?{2} #{relative_dir}/).size > 0
end
private
def has_branch?(branch)
CommandLine.new("git show-ref #{branch}").run
end
end
end
| ruby | MIT | 271510307b7037695988aa4881c7c17445cc9d1d | 2026-01-04T17:45:11.500917Z | false |
thoughtbot/kumade | https://github.com/thoughtbot/kumade/blob/271510307b7037695988aa4881c7c17445cc9d1d/lib/kumade/packagers/jammit_packager.rb | lib/kumade/packagers/jammit_packager.rb | begin
require "jammit"
rescue LoadError
end
module Kumade
class JammitPackager
def self.assets_path
File.join(public_root, Jammit.package_path)
end
def self.installed?
!!defined?(Jammit)
end
def self.package
Jammit.package!
end
private
def self.public_root
defined?(Jammit.public_root) ? Jammit.public_root : Jammit::PUBLIC_ROOT
end
end
end
| ruby | MIT | 271510307b7037695988aa4881c7c17445cc9d1d | 2026-01-04T17:45:11.500917Z | false |
thoughtbot/kumade | https://github.com/thoughtbot/kumade/blob/271510307b7037695988aa4881c7c17445cc9d1d/lib/kumade/packagers/noop_packager.rb | lib/kumade/packagers/noop_packager.rb | module Kumade
class NoopPackager
def self.assets_path
""
end
def self.package
end
def self.installed?
false
end
end
end
| ruby | MIT | 271510307b7037695988aa4881c7c17445cc9d1d | 2026-01-04T17:45:11.500917Z | false |
altmetric/embiggen | https://github.com/altmetric/embiggen/blob/45ef6fb3d0cfb389a5374994e3ec3bd406dc3756/spec/embiggen_spec.rb | spec/embiggen_spec.rb | require 'embiggen'
RSpec.describe Embiggen do
describe '#URI' do
it 'returns an Embiggen::URI' do
uri = described_class::URI('http://www.altmetric.com')
expect(uri).to be_a(described_class::URI)
end
it 'accepts an existing Embiggen::URI' do
uri = described_class::URI.new('http://www.altmetric.com')
expect(described_class::URI(uri)).to be_a(described_class::URI)
end
end
describe '#configure' do
it 'can be used to set global configuration' do
described_class.configure do |config|
config.timeout = 10
end
expect(described_class::Configuration.timeout).to eq(10)
end
after do
described_class::Configuration.timeout = 1
end
end
end
| ruby | MIT | 45ef6fb3d0cfb389a5374994e3ec3bd406dc3756 | 2026-01-04T17:45:12.071471Z | false |
altmetric/embiggen | https://github.com/altmetric/embiggen/blob/45ef6fb3d0cfb389a5374994e3ec3bd406dc3756/spec/spec_helper.rb | spec/spec_helper.rb | require 'webmock/rspec'
RSpec.configure do |config|
config.filter_run :focus
config.run_all_when_everything_filtered = true
config.disable_monkey_patching!
config.warnings = true
config.order = :random
Kernel.srand config.seed
config.default_formatter = 'doc' if config.files_to_run.one?
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
end
| ruby | MIT | 45ef6fb3d0cfb389a5374994e3ec3bd406dc3756 | 2026-01-04T17:45:12.071471Z | false |
altmetric/embiggen | https://github.com/altmetric/embiggen/blob/45ef6fb3d0cfb389a5374994e3ec3bd406dc3756/spec/embiggen/shortener_list_spec.rb | spec/embiggen/shortener_list_spec.rb | require 'embiggen/shortener_list'
RSpec.describe Embiggen::ShortenerList do
describe '#new' do
it 'can be given a set' do
list = described_class.new(Set['a.com', 'b.com', 'b.com'])
expect(list.size).to eq(2)
end
it 'converts a given enumerable to a set' do
list = described_class.new(%w[a.com a.com])
expect(list.size).to eq(1)
end
end
describe '#include?' do
it 'returns true if a URL host is on the whitelist' do
list = described_class.new(%w[bit.ly])
expect(list).to include(URI('http://bit.ly/foo'))
end
it 'returns false if a URL host is not on the whitelist' do
list = described_class.new(%w[bit.ly])
expect(list).to_not include(URI('http://www.altmetric.com'))
end
it 'returns true if a URL host without a subdomain is on the whitelist' do
list = described_class.new(%w[bit.ly])
expect(list).to include(URI('http://www.bit.ly/foo'))
end
end
describe '#<<' do
it 'appends domains to the list' do
list = described_class.new([])
list << 'bit.ly'
expect(list).to include(URI('http://bit.ly/foo'))
end
it 'can be chained' do
list = described_class.new([])
list << 'bit.ly' << 'a.com'
expect(list).to include(URI('http://bit.ly/foo'), URI('http://a.com/bar'))
end
end
describe '#size' do
it 'returns the number of domains in the list' do
list = described_class.new(%w[bit.ly ow.ly])
expect(list.size).to eq(2)
end
end
describe '#delete' do
it 'removes domains from the list' do
list = described_class.new(%w[bit.ly])
list.delete('bit.ly')
expect(list).to be_empty
end
end
describe '#+' do
it 'appends a list of domains to the existing one' do
list = described_class.new(%w[bit.ly])
list += %w[a.com]
expect(list).to include(URI('http://a.com/foo'))
end
it 'can combine two lists' do
list = described_class.new(%w[bit.ly])
list += described_class.new(%w[a.com])
expect(list).to include(URI('http://a.com/foo'))
end
end
it 'is enumerable for 1.8 compatiblity' do
list = described_class.new([])
expect(list).to be_kind_of(Enumerable)
end
end
| ruby | MIT | 45ef6fb3d0cfb389a5374994e3ec3bd406dc3756 | 2026-01-04T17:45:12.071471Z | false |
altmetric/embiggen | https://github.com/altmetric/embiggen/blob/45ef6fb3d0cfb389a5374994e3ec3bd406dc3756/spec/embiggen/configuration_spec.rb | spec/embiggen/configuration_spec.rb | require 'embiggen'
module Embiggen
RSpec.describe Configuration do
describe '#timeout' do
it 'defaults to 1 second' do
expect(described_class.timeout).to eq(1)
end
it 'can be overridden' do
described_class.timeout = 10
expect(described_class.timeout).to eq(10)
end
after do
described_class.timeout = 1
end
end
describe '#redirects' do
it 'defaults to 5' do
expect(described_class.redirects).to eq(5)
end
it 'can be overridden' do
described_class.redirects = 2
expect(described_class.redirects).to eq(2)
end
after do
described_class.redirects = 5
end
end
describe '#shorteners' do
it 'defaults to a list of shorteners' do
expect(described_class.shorteners).to_not be_empty
end
it 'can be overridden' do
expect { described_class.shorteners << 'foo.bar' }
.to change { described_class.shorteners.size }.by(1)
end
after do
described_class.shorteners.delete('foo.bar')
end
end
end
end
| ruby | MIT | 45ef6fb3d0cfb389a5374994e3ec3bd406dc3756 | 2026-01-04T17:45:12.071471Z | false |
altmetric/embiggen | https://github.com/altmetric/embiggen/blob/45ef6fb3d0cfb389a5374994e3ec3bd406dc3756/spec/embiggen/uri_spec.rb | spec/embiggen/uri_spec.rb | # encoding: utf-8
require 'embiggen'
module Embiggen
RSpec.describe URI do
describe '#expand' do
it 'expands HTTP URIs' do
stub_redirect('http://bit.ly/1ciyUPh',
'http://us.macmillan.com/books/9781466879980')
uri = described_class.new(URI('http://bit.ly/1ciyUPh'))
expect(uri.expand).to eq(URI('http://us.macmillan.com/books/9781466879980'))
end
it 'expands HTTPS URIs' do
stub_redirect('https://youtu.be/dQw4w9WgXcQ',
'https://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtu.be')
uri = described_class.new(URI('https://youtu.be/dQw4w9WgXcQ'))
expect(uri.expand).to eq(URI('https://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtu.be'))
end
it 'expands URIs passed as strings' do
stub_redirect('http://bit.ly/1ciyUPh',
'http://us.macmillan.com/books/9781466879980')
uri = described_class.new('http://bit.ly/1ciyUPh')
expect(uri.expand).to eq(URI('http://us.macmillan.com/books/9781466879980'))
end
it 'expands URIs with encoded locations' do
stub_redirect('http://bit.ly/1ciyUPh',
'http://www.example.com/%C3%A9%20%C3%BC')
uri = described_class.new('http://bit.ly/1ciyUPh')
expect(uri.expand).to eq(URI('http://www.example.com/%C3%A9%20%C3%BC'))
end
it 'expands URIs with unencoded locations' do
stub_redirect('http://bit.ly/1ciyUPh',
'http://www.example.com/é ü')
uri = described_class.new('http://bit.ly/1ciyUPh')
expect(uri.expand).to eq(URI('http://www.example.com/%C3%A9%20%C3%BC'))
end
it 'does not expand unshortened URIs' do
uri = described_class.new(URI('http://www.altmetric.com'))
expect(uri.expand).to eq(URI('http://www.altmetric.com'))
end
it 'does not make requests for unshortened URIs' do
uri = described_class.new(URI('http://www.altmetric.com'))
expect { uri.expand }.to_not raise_error
end
it 'raises an error if the URI redirects too many times' do
stub_redirect('http://bit.ly/1', 'http://bit.ly/2')
stub_redirect('http://bit.ly/2', 'http://bit.ly/3')
stub_redirect('http://bit.ly/3', 'http://bit.ly/4')
uri = described_class.new('http://bit.ly/1')
expect { uri.expand(redirects: 2) }
.to raise_error(TooManyRedirects)
end
it 'retains the last URI when redirecting too many times' do
stub_redirect('http://bit.ly/1', 'http://bit.ly/2')
stub_redirect('http://bit.ly/2', 'http://bit.ly/3')
stub_redirect('http://bit.ly/3', 'http://bit.ly/4')
uri = described_class.new('http://bit.ly/1')
last_uri = nil
begin
uri.expand(redirects: 2)
rescue TooManyRedirects => ex
last_uri = ex.uri
end
expect(last_uri).to eq(URI('http://bit.ly/3'))
end
it 'raises an error if a shortened URI does not redirect' do
stub_request(:get, 'http://bit.ly/bad').to_return(status: 500)
uri = described_class.new('http://bit.ly/bad')
expect { uri.expand }.to raise_error(BadShortenedURI)
end
it 'raises an error if the URI returned is not valid' do
stub_redirect('http://bit.ly/suspicious', '|cat /etc/passwd')
uri = described_class.new('http://bit.ly/suspicious')
expect { uri.expand }.to raise_error(BadShortenedURI)
end
it 'raises an error if the URI returned is not valid' do
stub_redirect('http://bit.ly/suspicious', 'http:')
uri = described_class.new('http://bit.ly/suspicious')
expect { uri.expand }.to raise_error(BadShortenedURI)
end
it 'retains the last URI if a shortened URI does not redirect' do
stub_redirect('http://bit.ly/bad', 'http://bit.ly/bad2')
stub_request(:get, 'http://bit.ly/bad2').to_return(status: 500)
uri = described_class.new('http://bit.ly/bad')
last_uri = nil
begin
uri.expand
rescue BadShortenedURI => ex
last_uri = ex.uri
end
expect(last_uri).to eq(URI('http://bit.ly/bad2'))
end
it 'raises a network error if the URI times out' do
stub_request(:get, 'http://bit.ly/bad').to_timeout
uri = described_class.new('http://bit.ly/bad')
expect { uri.expand }.to raise_error(NetworkError)
end
it 'raises a network error if the connection resets' do
stub_request(:get, 'http://bit.ly/bad').to_raise(::Errno::ECONNRESET)
uri = described_class.new('http://bit.ly/bad')
expect { uri.expand }.to raise_error(NetworkError)
end
it 'raises a network error if the host cannot be reached' do
stub_request(:get, 'http://bit.ly/bad').to_raise(::Errno::EHOSTUNREACH)
uri = described_class.new('http://bit.ly/bad')
expect { uri.expand }.to raise_error(NetworkError)
end
it 'retains the last URI if there is a network error' do
stub_redirect('http://bit.ly/bad', 'http://bit.ly/bad2')
stub_request(:get, 'http://bit.ly/bad2').to_timeout
uri = described_class.new('http://bit.ly/bad')
begin
uri.expand
rescue NetworkError => ex
last_uri = ex.uri
end
expect(last_uri).to eq(URI('http://bit.ly/bad2'))
end
it 'expands redirects to other shorteners' do
stub_redirect('http://bit.ly/98K8eH',
'https://youtu.be/dQw4w9WgXcQ')
stub_redirect('https://youtu.be/dQw4w9WgXcQ',
'https://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtu.be')
uri = described_class.new(URI('http://bit.ly/98K8eH'))
expect(uri.expand).to eq(URI('https://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtu.be'))
end
it 'stops expanding redirects after a default threshold of 5' do
stub_redirect('http://bit.ly/1', 'http://bit.ly/2')
stub_redirect('http://bit.ly/2', 'http://bit.ly/3')
stub_redirect('http://bit.ly/3', 'http://bit.ly/4')
stub_redirect('http://bit.ly/4', 'http://bit.ly/5')
stub_redirect('http://bit.ly/5', 'http://bit.ly/6')
stub_redirect('http://bit.ly/6', 'http://bit.ly/7')
uri = described_class.new(URI('http://bit.ly/1'))
expect { uri.expand }.to raise_error(TooManyRedirects)
end
it 'takes an optional redirect threshold' do
stub_redirect('http://bit.ly/1', 'http://bit.ly/2')
stub_redirect('http://bit.ly/2', 'http://bit.ly/3')
stub_redirect('http://bit.ly/3', 'http://bit.ly/4')
uri = described_class.new(URI('http://bit.ly/1'))
expect { uri.expand(redirects: 2) }.to raise_error(TooManyRedirects)
end
it 'uses the threshold from the configuration' do
stub_redirect('http://bit.ly/1', 'http://bit.ly/2')
stub_redirect('http://bit.ly/2', 'http://bit.ly/3')
stub_redirect('http://bit.ly/3', 'http://bit.ly/4')
uri = described_class.new(URI('http://bit.ly/1'))
Configuration.redirects = 2
expect { uri.expand }.to raise_error(TooManyRedirects)
end
it 'uses shorteners from the configuration' do
stub_redirect('http://altmetric.it', 'http://www.altmetric.com')
Configuration.shorteners << 'altmetric.it'
uri = described_class.new(URI('http://altmetric.it'))
expect(uri.expand).to eq(URI('http://www.altmetric.com'))
end
after do
Configuration.redirects = 5
Configuration.shorteners.delete('altmetric.it')
end
end
describe '#uri' do
it 'returns a URI' do
uri = described_class.new(URI('http://www.altmetric.com'))
expect(uri.uri).to eq(URI('http://www.altmetric.com'))
end
it 'returns a URI even if a string was passed' do
uri = described_class.new('http://www.altmetric.com')
expect(uri.uri).to eq(URI('http://www.altmetric.com'))
end
end
describe '#shortened?' do
it 'returns true if the link has been shortened' do
uri = described_class.new('http://bit.ly/1ciyUPh')
expect(uri).to be_shortened
end
it 'returns false if the link has not been shortened' do
uri = described_class.new('http://www.altmetric.com')
expect(uri).to_not be_shortened
end
it 'returns true if the link has been shortened with the wrong case' do
uri = described_class.new('http://BIT.LY/1ciyUPh')
expect(uri).to be_shortened
end
it 'returns false if link is not shortened but uses a similar ' \
'domain' do
uri = described_class.new('http://notbit.ly/1ciyUPh')
expect(uri).to_not be_shortened
end
it 'returns false if link is not shortened but uses a similar ' \
'domain without protocol' do
uri = described_class.new('notbit.ly/1ciyUPh')
expect(uri).to_not be_shortened
end
it 'returns false if link is not shortened but uses the same domain ' \
'with a different TLD' do
uri = described_class.new('http://nbc.com/1ciyUPh')
expect(uri).to_not be_shortened
end
it 'returns false if link is not shortened but uses the same domain ' \
'with a different TLD without protocol' do
uri = described_class.new('nbc.com/1ciyUPh')
expect(uri).to_not be_shortened
end
end
describe '#http_client' do
it 'returns the HTTP client for the given URI' do
uri = described_class.new('http://www.altmetric.com')
expect(uri.http_client.uri).to eq(URI('http://www.altmetric.com'))
end
end
def stub_redirect(short_url, expanded_url, status = 301)
stub_request(:get, short_url)
.to_return(status: status, headers: { 'Location' => expanded_url })
end
end
end
| ruby | MIT | 45ef6fb3d0cfb389a5374994e3ec3bd406dc3756 | 2026-01-04T17:45:12.071471Z | false |
altmetric/embiggen | https://github.com/altmetric/embiggen/blob/45ef6fb3d0cfb389a5374994e3ec3bd406dc3756/lib/embiggen.rb | lib/embiggen.rb | require 'embiggen/configuration'
require 'embiggen/uri'
module Embiggen
def URI(uri) # rubocop:disable Naming/MethodName
uri.is_a?(URI) ? uri : URI.new(uri)
end
def configure
yield(Configuration)
end
module_function :URI
module_function :configure
end
| ruby | MIT | 45ef6fb3d0cfb389a5374994e3ec3bd406dc3756 | 2026-01-04T17:45:12.071471Z | false |
altmetric/embiggen | https://github.com/altmetric/embiggen/blob/45ef6fb3d0cfb389a5374994e3ec3bd406dc3756/lib/embiggen/shortener_list.rb | lib/embiggen/shortener_list.rb | require 'forwardable'
module Embiggen
class ShortenerList
extend Forwardable
include Enumerable
attr_reader :domains
def initialize(domains)
@domains = Set.new(domains.map { |domain| host_pattern(domain) })
end
def include?(uri)
domains.any? { |domain| uri.host =~ domain }
end
def +(other)
self.class.new(domains + other)
end
def <<(domain)
domains << host_pattern(domain)
self
end
def delete(domain)
domains.delete(host_pattern(domain))
end
def_delegators :domains, :size, :empty?, :each
def host_pattern(domain)
/\b#{domain}\z/i
end
end
end
| ruby | MIT | 45ef6fb3d0cfb389a5374994e3ec3bd406dc3756 | 2026-01-04T17:45:12.071471Z | false |
altmetric/embiggen | https://github.com/altmetric/embiggen/blob/45ef6fb3d0cfb389a5374994e3ec3bd406dc3756/lib/embiggen/http_client.rb | lib/embiggen/http_client.rb | require 'embiggen/error'
require 'net/http'
module Embiggen
class GetWithoutBody < ::Net::HTTPRequest
METHOD = 'GET'.freeze
REQUEST_HAS_BODY = false
RESPONSE_HAS_BODY = false
end
class HttpClient
attr_reader :uri, :http
def initialize(uri)
@uri = uri
@http = ::Net::HTTP.new(uri.host, uri.port)
@http.use_ssl = true if uri.scheme == 'https'
end
def follow(timeout)
response = request(timeout)
return unless response.is_a?(::Net::HTTPRedirection)
response.fetch('Location')
rescue ::Timeout::Error => e
raise NetworkError.new(
"Timeout::Error: could not follow #{uri}: #{e.message}", uri
)
rescue StandardError => e
raise NetworkError.new(
"StandardError: could not follow #{uri}: #{e.message}", uri
)
end
private
def request(timeout)
request = GetWithoutBody.new(uri.request_uri)
http.open_timeout = timeout
http.read_timeout = timeout
http.request(request)
end
end
end
| ruby | MIT | 45ef6fb3d0cfb389a5374994e3ec3bd406dc3756 | 2026-01-04T17:45:12.071471Z | false |
altmetric/embiggen | https://github.com/altmetric/embiggen/blob/45ef6fb3d0cfb389a5374994e3ec3bd406dc3756/lib/embiggen/uri.rb | lib/embiggen/uri.rb | require 'embiggen/configuration'
require 'embiggen/error'
require 'embiggen/http_client'
require 'addressable/uri'
require 'uri'
module Embiggen
class URI
attr_reader :uri, :http_client
def initialize(uri)
@uri = URI(::Addressable::URI.parse(uri).normalize.to_s)
@http_client = HttpClient.new(@uri)
end
def expand(request_options = {})
return uri unless shortened?
redirects = extract_redirects(request_options)
location = follow(request_options)
self.class.new(location)
.expand(request_options.merge(redirects: redirects - 1))
end
def shortened?
Configuration.shorteners.include?(uri)
end
private
def extract_redirects(request_options = {})
redirects = request_options.fetch(:redirects) { Configuration.redirects }
if redirects.zero?
fail TooManyRedirects.new(
"following #{uri} reached the redirect limit", uri
)
end
redirects
end
def follow(request_options = {})
timeout = request_options.fetch(:timeout) { Configuration.timeout }
location = http_client.follow(timeout)
unless followable?(location)
fail BadShortenedURI.new(
"following #{uri} did not redirect", uri
)
end
location
end
def followable?(location)
return unless location
Addressable::URI.parse(location).absolute?
rescue Addressable::URI::InvalidURIError => e
raise BadShortenedURI.new(
"following #{uri} returns an invalid URI: #{e}", uri
)
end
end
end
| ruby | MIT | 45ef6fb3d0cfb389a5374994e3ec3bd406dc3756 | 2026-01-04T17:45:12.071471Z | false |
altmetric/embiggen | https://github.com/altmetric/embiggen/blob/45ef6fb3d0cfb389a5374994e3ec3bd406dc3756/lib/embiggen/configuration.rb | lib/embiggen/configuration.rb | # encoding: utf-8
require 'embiggen/shortener_list'
module Embiggen
class Configuration
class << self
attr_writer :timeout, :redirects, :shorteners
end
def self.timeout
@timeout ||= 1
end
def self.redirects
@redirects ||= 5
end
# From http://longurl.org/services
def self.shorteners
@shorteners ||= ShortenerList.new(shorteners_from_file)
end
def self.shorteners_from_file
file_path = File.expand_path('../../shorteners.txt', __dir__)
File.readlines(file_path).map(&:chomp)
end
end
end
| ruby | MIT | 45ef6fb3d0cfb389a5374994e3ec3bd406dc3756 | 2026-01-04T17:45:12.071471Z | false |
altmetric/embiggen | https://github.com/altmetric/embiggen/blob/45ef6fb3d0cfb389a5374994e3ec3bd406dc3756/lib/embiggen/error.rb | lib/embiggen/error.rb | module Embiggen
class Error < ::StandardError
attr_reader :uri
def initialize(message, uri)
super(message)
@uri = uri
end
end
class BadShortenedURI < Error; end
class NetworkError < Error; end
class TooManyRedirects < Error; end
end
| ruby | MIT | 45ef6fb3d0cfb389a5374994e3ec3bd406dc3756 | 2026-01-04T17:45:12.071471Z | false |
ranjib/etcd-ruby | https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/spec/spec_helper.rb | spec/spec_helper.rb | # encoding: utf-8
$LOAD_PATH.unshift(File.expand_path('../lib', __FILE__))
$LOAD_PATH.unshift(File.expand_path('../spec', __FILE__))
require 'coco'
require 'uuid'
require 'etcd'
require 'singleton'
module Etcd
class Spawner
include Singleton
def initialize
@pids = []
@cert_file = File.expand_path('../data/server.crt', __FILE__)
@key_file = File.expand_path('../data/server.key', __FILE__)
@ca_cert = File.expand_path('../data/ca.crt', __FILE__)
end
def etcd_ports
@pids.size.times.inject([]){|servers, n| servers << 4000 + n + 1 }
end
def start(numbers = 1)
raise "Already running etcd servers(#{@pids.inspect})" unless @pids.empty?
@tmpdir = Dir.mktmpdir
(1..numbers).each do |n|
@pids << daemonize(n, @tmpdir + n.to_s , numbers)
end
sleep 5
end
def daemonize(index, dir, total)
ad_url = "http://localhost:#{7000 + index}"
client_url = "http://localhost:#{4000 + index}"
cluster_urls = (1..total).map{|n| "node_#{n}=http://localhost:#{7000 + n}"}.join(",")
flags = " -name node_#{index} -initial-advertise-peer-urls #{ad_url}"
flags << " -listen-peer-urls #{ad_url}"
flags << " -listen-client-urls #{client_url}"
flags << " -initial-cluster #{cluster_urls}"
flags << " -data-dir #{dir} "
command = etcd_binary + flags
pid = spawn(command, out: '/dev/null', err: '/dev/null')
Process.detach(pid)
pid
end
def etcd_binary
if File.exists? './etcd/bin/etcd'
'./etcd/bin/etcd'
elsif !!ENV['ETCD_BIN']
ENV['ETCD_BIN']
else
fail 'etcd binary not found., you need to set ETCD_BIN'
end
end
def stop
@pids.each do |pid|
Process.kill('TERM', pid)
end
FileUtils.remove_entry_secure(@tmpdir, true)
@pids.clear
end
end
module SpecHelper
def spawner
Spawner.instance
end
def start_daemon(numbers = 1, opts={})
spawner.start(numbers, opts)
end
def stop_daemon
spawner.stop
end
def uuid
@uuid ||= UUID.new
end
def random_key(n = 1)
key = ''
n.times do
key << '/' + uuid.generate
end
key
end
def etcd_client(port = 4001)
Etcd.client(host: 'localhost', port: port)
end
def etcd_leader
clients = spawner.etcd_ports.map{|port| etcd_client(port)}
clients.detect{|c|c.stats(:self)['state'] == 'StateLeader'}
end
end
end
RSpec.configure do |c|
c.include Etcd::SpecHelper
c.before(:suite) do
Etcd::Spawner.instance.start(3)
end
c.after(:suite) do
Etcd::Spawner.instance.stop
end
c.fail_fast = false
end
| ruby | MIT | f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917 | 2026-01-04T17:45:15.670612Z | false |
ranjib/etcd-ruby | https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/spec/etcd/stats_spec.rb | spec/etcd/stats_spec.rb | # Encoding: utf-8
require 'spec_helper'
describe Etcd::Stats do
let(:client) do
etcd_client
end
let(:leader) do
etcd_leader
end
describe 'of leader' do
let(:stats) do
client.stats(:leader)
end
it 'should contain a key for leader' do
expect(leader.stats(:leader)).to_not be_nil
end
end
it 'should show self statsistics' do
expect(client.stats(:self)['name']).to_not be_nil
expect(client.stats(:self)['state']).to_not be_nil
end
it 'should show store statistics' do
expect(client.stats(:store).keys).to_not be_empty
end
it 'should raise error for invalid types' do
expect do
client.stats(:foo)
end.to raise_error
end
end
| ruby | MIT | f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917 | 2026-01-04T17:45:15.670612Z | false |
ranjib/etcd-ruby | https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/spec/etcd/client_spec.rb | spec/etcd/client_spec.rb | require 'spec_helper'
describe Etcd::Client do
let(:client) do
etcd_client
end
it '#version' do #etcd 2.0.0-rc.1
expect(client.version).to match(/^etcd v?\d+\.\d+\.\d+.*$/)
end
it '#version_prefix' do
expect(client.version_prefix).to eq('/v2')
end
context '#api_execute' do
it 'should raise exception when non http methods are passed' do
expect do
client.api_execute('/v2/keys/x', :do)
end.to raise_error
end
end
context '#http header based metadata' do
before(:all) do
key = random_key
value = uuid.generate
@response = etcd_client.set(key, value: value)
end
it '#etcd_index' do
expect(@response.etcd_index).to_not be_nil
end
it '#raft_index' do
expect(@response.raft_index).to_not be_nil
end
it '#raft_term' do
expect(@response.raft_term).to_not be_nil
end
end
end
| ruby | MIT | f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917 | 2026-01-04T17:45:15.670612Z | false |
ranjib/etcd-ruby | https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/spec/etcd/watch_spec.rb | spec/etcd/watch_spec.rb | # Encoding: utf-8
require 'spec_helper'
describe 'Etcd watch' do
let(:client) do
etcd_client
end
it 'without index, returns the value at a particular index' do
key = random_key(4)
value1 = uuid.generate
value2 = uuid.generate
index1 = client.create(key, value: value1).node.modifiedIndex
index2 = client.test_and_set(key, value: value2, prevValue: value1).node.modifiedIndex
expect(client.watch(key, index: index1).node.value).to eq(value1)
expect(client.watch(key, index: index2).node.value).to eq(value2)
end
it 'with index, waits and return when the key is updated' do
response = nil
key = random_key
value = uuid.generate
thr = Thread.new do
response = client.watch(key)
end
sleep 2
client.set(key, value: value)
thr.join
expect(response.node.value).to eq(value)
end
it 'with recrusive, waits and return when the key is updated' do
response = nil
key = random_key
value = uuid.generate
client.set("#{key}/subkey", value:"initial_value")
thr = Thread.new do
response = client.watch(key, recursive:true, timeout:3)
end
sleep 2
client.set("#{key}/subkey", value: value)
thr.join
expect(response.node.value).to eq(value)
end
end
| ruby | MIT | f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917 | 2026-01-04T17:45:15.670612Z | false |
ranjib/etcd-ruby | https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/spec/etcd/basic_auth_client_spec.rb | spec/etcd/basic_auth_client_spec.rb | # Encoding: utf-8
require 'spec_helper'
describe 'Etcd basic auth client' do
let(:client) do
Etcd.client(host: 'localhost') do |config|
config.user_name = 'test'
config.password = 'pwd'
end
end
it '#user_name' do
expect(client.user_name).to eq('test')
end
it '#password' do
expect(client.password).to eq('pwd')
end
end
| ruby | MIT | f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917 | 2026-01-04T17:45:15.670612Z | false |
ranjib/etcd-ruby | https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/spec/etcd/keys_spec.rb | spec/etcd/keys_spec.rb | require 'spec_helper'
describe Etcd::Keys do
shared_examples 'basic key operation' do
it '#set/#get' do
key = random_key
value = uuid.generate
client.set(key, value: value)
expect(client.get(key).value).to eq(value)
end
context '#exists?' do
it 'should be true for existing keys' do
key = random_key
client.create(key, value: 10)
expect(client.exists?(key)).to be(true)
end
it 'should be true for existing keys' do
expect(client.exists?(random_key)).to be(false)
end
end
context 'directory' do
it 'should be able to create a directory' do
d = random_key
client.create(d, dir: true)
expect(client.get(d)).to be_directory
end
context 'empty' do
it 'should be able to delete with dir flag' do
d = random_key
client.create(d, dir: true)
client.delete(d, dir: true)
expect(client.exist?(d)).to be(false)
end
it 'should not be able to delete without dir flag' do
d = random_key
client.create(d, dir: true)
client.create("#{d}/foobar", value: 10)
expect do
client.delete(d)
end.to raise_error(Etcd::NotFile)
end
end
context 'not empty' do
it 'should be able to delete with recursive flag' do
d = random_key
client.create(d, dir: true)
client.create("#{d}/foobar")
expect do
client.delete(d, dir: true, recursive: true)
end.to_not raise_error
end
it 'should be not able to delete without recursive flag' do
d = random_key
client.create(d, dir: true)
client.create("#{d}/foobar")
expect do
client.delete(d, dir: true)
end.to raise_error(Etcd::DirNotEmpty)
end
end
end
end
context 'without ssl' do
let(:client) do
etcd_client
end
it_should_behave_like 'basic key operation'
end
end
| ruby | MIT | f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917 | 2026-01-04T17:45:15.670612Z | false |
ranjib/etcd-ruby | https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/spec/etcd/test_and_set_spec.rb | spec/etcd/test_and_set_spec.rb | # Encoding: utf-8
require 'spec_helper'
describe 'Etcd test_and_set' do
let(:client) do
etcd_client
end
it 'should pass when prev value is correct' do
key = random_key(2)
old_value = uuid.generate
new_value = uuid.generate
resp = client.set(key, value: old_value)
expect(resp.node.value).to eq(old_value)
client.test_and_set(key, value: new_value, prevValue: old_value)
expect(client.get(key).value).to eq(new_value)
end
it 'should fail when prev value is incorrect' do
key = random_key(2)
value = uuid.generate
client.set(key, value: value)
expect { client.test_and_set(key, value: 10, prevValue: 2) }.to raise_error(Etcd::TestFailed)
end
it '#create should succeed when the key is absent and update should fail' do
key = random_key(2)
value = uuid.generate
expect do
client.update(key, value: value)
end.to raise_error
expect do
client.create(key, value: value)
end.to_not raise_error
expect(client.get(key).value).to eq(value)
end
it '#create should fail when the key is present and update should succeed' do
key = random_key(2)
value = uuid.generate
client.set(key, value: 1)
expect do
client.create(key, value: value)
end.to raise_error
expect do
client.update(key, value: value)
end.to_not raise_error
end
end
| ruby | MIT | f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917 | 2026-01-04T17:45:15.670612Z | false |
ranjib/etcd-ruby | https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/spec/etcd/readme_spec.rb | spec/etcd/readme_spec.rb | # Encoding: utf-8
require 'spec_helper'
describe 'Etcd specs for the main etcd README examples' do
let(:client) do
etcd_client
end
shared_examples 'response with valid node data' do |action|
if action == :delete
it 'should not have value' do
expect(@response.node.value).to be_nil
end
else
it 'should set the value correctly' do
expect(@response.node.value).to eq('PinkFloyd')
end
end
if action == :create
it 'should set the parent key correctly' do
expect(@response.node.key).to match /^\/queue\/+/
end
else
it 'should set the key properly' do
expect(@response.node.key).to eq('/message')
end
end
it 'modified index should be a positive integer' do
expect(@response.node.created_index).to be > 0
end
it 'created index should be a positive integer' do
expect(@response.node.modified_index).to be > 0
end
end
shared_examples 'response with valid http headers' do
it 'should have a positive etcd index (comes from http header)' do
expect(@response.etcd_index).to be > 0
end
it 'should have a positive raft index (comes from http header)' do
expect(@response.raft_index).to be > 0
end
it 'should have a positive raft term (comes from http header)' do
expect(@response.raft_term).to be >= 0
end
end
context 'set a key named "/message"' do
before(:all) do
@response = etcd_client.set('/message', value: 'PinkFloyd')
end
it_should_behave_like 'response with valid http headers'
it_should_behave_like 'response with valid node data'
it 'should set the return action to SET' do
expect(@response.action).to eq('set')
end
end
context 'get a key named "/message"' do
before(:all) do
etcd_client.set('/message', value: 'PinkFloyd')
@response = etcd_client.get('/message')
end
it_should_behave_like 'response with valid http headers'
it_should_behave_like 'response with valid node data'
it 'should set the return action to GET' do
expect(@response.action).to eq('get')
end
end
context 'change the value of a key named "/message"' do
before(:all) do
etcd_client.set('/message', value: 'World')
@response = etcd_client.set('/message', value: 'PinkFloyd')
end
it_should_behave_like 'response with valid http headers'
it_should_behave_like 'response with valid node data'
it 'should set the return action to SET' do
expect(@response.action).to eq('set')
end
end
context 'delete a key named "/message"' do
before(:all) do
etcd_client.set('/message', value: 'World')
etcd_client.set('/message', value: 'PinkFloyd')
@response = etcd_client.delete('/message')
end
it 'should set the return action to SET' do
expect(@response.action).to eq('delete')
end
it_should_behave_like 'response with valid http headers'
it_should_behave_like 'response with valid node data', :delete
end
context 'using ttl a key named "/message"' do
before(:all) do
etcd_client.set('/message', value: 'World')
@set_time = Time.now
@response = etcd_client.set('/message', value: 'PinkFloyd', ttl: 5)
end
it_should_behave_like 'response with valid http headers'
it_should_behave_like 'response with valid node data'
it 'should set the return action to SET' do
expect(@response.action).to eq('set')
end
it 'should have valid expiration time' do
expect(@response.node.expiration).to_not be_nil
end
it 'should have ttl available from the node' do
expect(@response.node.ttl).to eq(5)
end
it 'should throw exception after the expiration time' do
sleep 8
expect do
client.get('/message')
end.to raise_error
end
end
context 'waiting for a change against a key named "/message"' do
before(:all) do
etcd_client.set('/message', value: 'foo')
thr = Thread.new do
@response = etcd_client.watch('/message')
end
sleep 1
etcd_client.set('/message', value: 'PinkFloyd')
thr.join
end
it_should_behave_like 'response with valid http headers'
it_should_behave_like 'response with valid node data'
it 'should set the return action to SET' do
expect(@response.action).to eq('set')
end
it 'should get the exact value by specifying a waitIndex' do
client.set('/message', value: 'someshit')
w_response = client.watch('/message', index: @response.node.modified_index)
expect(w_response.node.value).to eq('PinkFloyd')
end
end
context 'atomic in-order keys' do
before(:all) do
@response = etcd_client.create_in_order('/queue', value: 'PinkFloyd')
end
it_should_behave_like 'response with valid http headers'
it_should_behave_like 'response with valid node data', :create
it 'should set the return action to create' do
expect(@response.action).to eq('create')
end
it 'should have the child key as a positive integer' do
expect(@response.key.split('/').last.to_i).to be > 0
end
it 'should have the child keys as monotonically increasing' do
first_response = client.create_in_order('/queue', value: 'The Jimi Hendrix Experience')
second_response = client.create_in_order('/queue', value: 'The Doors')
first_key = first_response.key.split('/').last.to_i
second_key = second_response.key.split('/').last.to_i
expect(first_key).to be < second_key
end
it 'should enlist all children in sorted manner' do
responses = []
10.times do |n|
responses << client.create_in_order('/queue', value: 'Deep Purple - Track #{n}')
end
directory = client.get('/queue', sorted: true)
past_index = directory.children.index(responses.first.node)
9.times do |n|
current_index = directory.children.index(responses[n + 1].node)
expect(current_index).to be > past_index
past_index = current_index
end
end
end
context 'directory with ttl' do
before(:all) do
@response = etcd_client.set('/directory', dir: true, ttl: 4)
end
it 'should create a directory' do
expect(client.get('/directory')).to be_directory
end
it 'should have valid expiration time' do
expect(client.get('/directory').node.expiration).to_not be_nil
end
it 'should have pre-designated ttl' do
expect(client.get('/directory').node.ttl).to eq(4)
end
it 'will throw error if updated without setting prevExist' do
expect do
client.set('/directory', dir: true, ttl: 5)
end.to raise_error
end
it 'can be updated by setting prevExist to true' do
client.set('/directory', prevExist: true, dir: true, ttl: 5)
expect(client.get('/directory').node.ttl).to eq(5)
end
it 'watchers should get expriy notification' do
client.set('/directory/a', value: 'Test')
client.set('/directory', prevExist: true, dir: true, ttl: 2)
response = client.watch('/directory/a', consistent: true, timeout: 3)
expect(response.action).to eq('expire')
end
it 'should be expired after ttl' do
sleep 5
expect do
client.get('/directory')
end.to raise_error
end
end
context 'atomic compare and swap' do
it 'should raise error if prevExist is passed a false' do
client.set('/foo', value: 'one')
expect do
client.set('/foo', value: 'three', prevExist: false)
end.to raise_error
end
it 'should raise error is prevValue is wrong' do
client.set('/foo', value: 'one')
expect do
client.set('/foo', value: 'three', prevValue: 'two')
end.to raise_error
end
it 'should allow setting the value when prevValue is right' do
client.set('/foo', value: 'one')
expect(client.set('/foo', value: 'three', prevValue: 'one').value).to eq('three')
end
end
context 'directory manipulation' do
it 'should allow creating directory' do
expect(client.set('/dir', dir: true)).to be_directory
end
it 'should allow listing directory' do
client.set('/foo_dir/foo', value: 'bar')
expect(client.get('/').children.map(&:key)).to include('/foo_dir')
end
it 'should allow recursive directory listing' do
response = client.get('/', recursive: true)
expect(response.children.find { |n|n.key == '/foo_dir' }.children).to_not be_empty
end
it 'should be able to delete empty directory without the recusrive flag' do
expect(client.delete('/dir', dir: true).action).to eq('delete')
end
it 'should be able to delete directory with children with the recusrive flag' do
expect(client.delete('/foo_dir', recursive: true).action).to eq('delete')
end
end
context 'hidden nodes' do
before(:all) do
etcd_client.set('/_message', value: 'Hello Hidden World')
etcd_client.set('/message', value: 'Hello World')
end
it 'should not be visible in directory listing' do
expect(client.get('/').children.map(&:key)).to_not include('_message')
end
end
end
| ruby | MIT | f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917 | 2026-01-04T17:45:15.670612Z | false |
ranjib/etcd-ruby | https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/spec/etcd/node_spec.rb | spec/etcd/node_spec.rb | require 'spec_helper'
describe Etcd::Node do
let(:client) do
etcd_client
end
it 'should create a directory with parent key when nested keys are set' do
parent = random_key
child = random_key
value = uuid.generate
client.set(parent + child, value: value)
expect(client.get(parent + child)).to_not be_directory
expect(client.get(parent)).to be_directory
end
context '#children' do
it 'should raise exception when invoked against a leaf node' do
parent = random_key
client.create(random_key, value: 10)
expect do
client.get(random_key).children
end.to raise_error
end
end
end
| ruby | MIT | f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917 | 2026-01-04T17:45:15.670612Z | false |
ranjib/etcd-ruby | https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/lib/etcd.rb | lib/etcd.rb | # Encoding: utf-8
require 'etcd/client'
##
# This module provides the Etcd:: name space for the gem and few
# factory methods for Etcd domain objects
module Etcd
##
# Create and return a Etcd::Client object. It takes a hash +opts+
# as an argument which gets passed to the Etcd::Client.new method
# directly
# If +opts+ is not passed default options are used, defined by Etcd::Client.new
def self.client(opts = {})
Etcd::Client.new(opts) do |config|
yield config if block_given?
end
end
end
| ruby | MIT | f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917 | 2026-01-04T17:45:15.670612Z | false |
ranjib/etcd-ruby | https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/lib/etcd/version.rb | lib/etcd/version.rb | # Encoding: utf-8
# Version const
module Etcd
VERSION = '0.3.0'
end
| ruby | MIT | f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917 | 2026-01-04T17:45:15.670612Z | false |
ranjib/etcd-ruby | https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/lib/etcd/exceptions.rb | lib/etcd/exceptions.rb | # Encoding: utf-8
require 'json'
# Provides Etcd namespace
module Etcd
# Represents all etcd custom errors
class Error < StandardError
attr_reader :caused_by, :error_code, :index
def initialize(opts = {})
super(opts['message'])
@caused_by = opts['cause']
@index = opts['index']
@error_code = opts['errorCode']
end
def self.from_http_response(response)
opts = JSON.parse(response.body)
unless ERROR_CODE_MAPPING.key?(opts['errorCode'])
fail "Unknown error code: #{opts['errorCode']}"
end
ERROR_CODE_MAPPING[opts['errorCode']].new(opts)
end
def inspect
"<#{self.class}: index:#{index}, code:#{error_code}, cause:'#{caused_by}'>"
end
end
# command related error
class KeyNotFound < Error; end
class TestFailed < Error; end
class NotFile < Error; end
class NoMorePeer < Error; end
class NotDir < Error; end
class NodeExist < Error; end
class KeyIsPreserved < Error; end
class DirNotEmpty < Error; end
# Post form related error
class ValueRequired < Error; end
class PrevValueRequired < Error; end
class TTLNaN < Error; end
class IndexNaN < Error; end
# Raft related error
class RaftInternal < Error; end
class LeaderElect < Error; end
# Etcd related error
class WatcherCleared < Error; end
class EventIndexCleared < Error; end
ERROR_CODE_MAPPING = {
# command related error
100 => KeyNotFound,
101 => TestFailed,
102 => NotFile,
103 => NoMorePeer,
104 => NotDir,
105 => NodeExist,
106 => KeyIsPreserved,
108 => DirNotEmpty,
# Post form related error
200 => ValueRequired,
201 => PrevValueRequired,
202 => TTLNaN,
203 => IndexNaN,
# Raft related error
300 => RaftInternal,
301 => LeaderElect,
# Etcd related error
400 => WatcherCleared,
401 => EventIndexCleared
}
end
| ruby | MIT | f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917 | 2026-01-04T17:45:15.670612Z | false |
ranjib/etcd-ruby | https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/lib/etcd/log.rb | lib/etcd/log.rb | # Encoding: utf-8
require 'mixlib/log'
module Etcd
##
# A wrapper class that extends Mixlib::Log
class Log
extend Mixlib::Log
end
end
| ruby | MIT | f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917 | 2026-01-04T17:45:15.670612Z | false |
ranjib/etcd-ruby | https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/lib/etcd/keys.rb | lib/etcd/keys.rb | # Encoding: utf-8
require 'json'
require 'etcd/response'
require 'etcd/log'
module Etcd
# Keys module provides the basic key value operations against
# etcd /keys namespace
module Keys
# return etcd endpoint that is reserved for key/value store
def key_endpoint
version_prefix + '/keys'
end
# Retrives a key with its associated data, if key is not present it will
# return with message "Key Not Found"
#
# This method takes the following parameters as arguments
# * key - whose data is to be retrieved
def get(key, opts = {})
response = api_execute(key_endpoint + key, :get, params: opts)
Response.from_http_response(response)
end
# Create or update a new key
#
# This method takes the following parameters as arguments
# * key - whose value to be set
# * value - value to be set for specified key
# * ttl - shelf life of a key (in seconds) (optional)
def set(key, opts = nil)
fail ArgumentError, 'Second argument must be a hash' unless opts.is_a?(Hash)
path = key_endpoint + key
payload = {}
[:ttl, :value, :dir, :prevExist, :prevValue, :prevIndex].each do |k|
payload[k] = opts[k] if opts.key?(k)
end
response = api_execute(path, :put, params: payload)
Response.from_http_response(response)
end
# Deletes a key (and its content)
#
# This method takes the following parameters as arguments
# * key - key to be deleted
def delete(key, opts = {})
response = api_execute(key_endpoint + key, :delete, params: opts)
Response.from_http_response(response)
end
# Set a new value for key if previous value of key is matched
#
# This method takes the following parameters as arguments
# * key - whose value is going to change if previous value is matched
# * value - new value to be set for specified key
# * prevValue - value of a key to compare with existing value of key
# * ttl - shelf life of a key (in secsonds) (optional)
def compare_and_swap(key, opts = {})
fail ArgumentError, 'Second argument must be a hash' unless opts.is_a?(Hash)
fail ArgumentError, 'You must pass prevValue' unless opts.key?(:prevValue)
set(key, opts)
end
# Gives a notification when specified key changes
#
# This method takes the following parameters as arguments
# @ key - key to be watched
# @options [Hash] additional options for watching a key
# @options [Fixnum] :index watch the specified key from given index
# @options [Fixnum] :timeout specify http timeout
def watch(key, opts = {})
params = { wait: true }
fail ArgumentError, 'Second argument must be a hash' unless opts.is_a?(Hash)
timeout = opts[:timeout] || @read_timeout
index = opts[:waitIndex] || opts[:index]
params[:waitIndex] = index unless index.nil?
params[:consistent] = opts[:consistent] if opts.key?(:consistent)
params[:recursive] = opts[:recursive] if opts.key?(:recursive)
response = api_execute(
key_endpoint + key,
:get,
timeout: timeout,
params: params
)
Response.from_http_response(response)
end
def create_in_order(dir, opts = {})
path = key_endpoint + dir
fail ArgumentError, 'Second argument must be a hash' unless opts.is_a?(Hash)
payload = {}
[:ttl, :value].each do |k|
payload[k] = opts[k] if opts.key?(k)
end
response = api_execute(path, :post, params: payload)
Response.from_http_response(response)
end
def exists?(key)
Etcd::Log.debug("Checking if key:' #{key}' exists")
get(key)
true
rescue KeyNotFound => e
Etcd::Log.debug("Key does not exist #{e}")
false
end
def create(key, opts = {})
set(key, opts.merge(prevExist: false))
end
def update(key, opts = {})
set(key, opts.merge(prevExist: true))
end
def eternal_watch(key, index = nil)
loop do
response = watch(key, index)
yield response
end
end
alias_method :key?, :exists?
alias_method :exist?, :exists?
alias_method :has_key?, :exists?
alias_method :test_and_set, :compare_and_swap
end
end
| ruby | MIT | f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917 | 2026-01-04T17:45:15.670612Z | false |
ranjib/etcd-ruby | https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/lib/etcd/node.rb | lib/etcd/node.rb | # Encoding: utf-8
module Etcd
# This class represents an etcd node
class Node
include Comparable
attr_reader :created_index, :modified_index, :expiration, :ttl, :key, :value, :dir
alias_method :createdIndex, :created_index
alias_method :modifiedIndex, :modified_index
# rubocop:disable MethodLength
def initialize(opts = {})
@created_index = opts['createdIndex']
@modified_index = opts['modifiedIndex']
@ttl = opts['ttl']
@key = opts['key']
@value = opts['value']
@expiration = opts['expiration']
@dir = opts['dir']
if opts['dir'] && opts['nodes']
opts['nodes'].each do |data|
children << Node.new(data)
end
end
end
def <=>(other)
key <=> other.key
end
def children
if directory?
@children ||= []
else
fail 'This is not a directory, cant have children'
end
end
def directory?
! @dir.nil?
end
end
end
| ruby | MIT | f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917 | 2026-01-04T17:45:15.670612Z | false |
ranjib/etcd-ruby | https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/lib/etcd/response.rb | lib/etcd/response.rb | # Encoding: utf-8
require 'etcd/node'
require 'json'
require 'forwardable'
module Etcd
# manage http responses
class Response
extend Forwardable
attr_reader :action, :node, :etcd_index, :raft_index, :raft_term
def_delegators :@node, :key, :value, :directory?, :children
def initialize(opts, headers = {})
@action = opts['action']
@node = Node.new(opts['node'])
@etcd_index = headers[:etcd_index]
@raft_index = headers[:raft_index]
@raft_term = headers[:raft_term]
end
def self.from_http_response(response)
data = JSON.parse(response.body)
headers = {}
headers[:etcd_index] = response['X-Etcd-Index'].to_i
headers[:raft_index] = response['X-Raft-Index'].to_i
headers[:raft_term] = response['X-Raft-Term'].to_i
Response.new(data, headers)
end
end
end
| ruby | MIT | f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917 | 2026-01-04T17:45:15.670612Z | false |
ranjib/etcd-ruby | https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/lib/etcd/stats.rb | lib/etcd/stats.rb | # Encoding: utf-8
require 'json'
module Etcd
# Support stats
module Stats
def stats_endpoint
version_prefix + '/stats'
end
def stats(type)
case type
when :leader
JSON.parse(api_execute(stats_endpoint + '/leader', :get).body)
when :store
JSON.parse(api_execute(stats_endpoint + '/store', :get).body)
when :self
JSON.parse(api_execute(stats_endpoint + '/self', :get).body)
else
fail ArgumentError, "Invalid stats type '#{type}'"
end
end
end
end
| ruby | MIT | f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917 | 2026-01-04T17:45:15.670612Z | false |
ranjib/etcd-ruby | https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/lib/etcd/client.rb | lib/etcd/client.rb | # Encoding: utf-8
require 'openssl'
require 'net/http'
require 'net/https'
require 'json'
require 'etcd/log'
require 'etcd/stats'
require 'etcd/keys'
require 'etcd/exceptions'
module Etcd
##
# This is the central ruby class for Etcd. It provides methods for all
# etcd api calls. It also provides few additional methods beyond the core
# etcd api, like Etcd::Client#lock and Etcd::Client#eternal_watch, they
# are defined in separate modules and included in this class
class Client
extend Forwardable
HTTP_REDIRECT = ->(r) { r.is_a? Net::HTTPRedirection }
HTTP_SUCCESS = ->(r) { r.is_a? Net::HTTPSuccess }
HTTP_CLIENT_ERROR = ->(r) { r.is_a? Net::HTTPClientError }
include Stats
include Keys
Config = Struct.new(
:use_ssl,
:verify_mode,
:read_timeout,
:ssl_key,
:ca_file,
:user_name,
:password,
:ssl_cert
)
def_delegators :@config, :use_ssl, :verify_mode, :read_timeout
def_delegators :@config, :user_name, :password
attr_reader :host, :port, :http, :config
##
# Creates an Etcd::Client object. It accepts a hash +opts+ as argument
#
# @param [Hash] opts The options for new Etcd::Client object
# @opts [String] :host IP address of the etcd server (default 127.0.0.1)
# @opts [Fixnum] :port Port number of the etcd server (default 4001)
# @opts [Fixnum] :read_timeout set HTTP read timeouts (default 60)
# rubocop:disable CyclomaticComplexity
def initialize(opts = {})
@host = opts[:host] || '127.0.0.1'
@port = opts[:port] || 4001
@config = Config.new
@config.read_timeout = opts[:read_timeout] || 60
@config.use_ssl = opts[:use_ssl] || false
@config.verify_mode = opts.key?(:verify_mode) ? opts[:verify_mode] : OpenSSL::SSL::VERIFY_PEER
@config.user_name = opts[:user_name] || nil
@config.password = opts[:password] || nil
@config.ca_file = opts.key?(:ca_file) ? opts[:ca_file] : nil
# Provide a OpenSSL X509 cert here and not the path. See README
@config.ssl_cert = opts.key?(:ssl_cert) ? opts[:ssl_cert] : nil
# Provide the key (content) and not just the filename here.
@config.ssl_key = opts.key?(:ssl_key) ? opts[:ssl_key] : nil
yield @config if block_given?
end
# rubocop:enable CyclomaticComplexity
# Returns the etcd api version that will be used for across API methods
def version_prefix
'/v2'
end
# Returns the etcd daemon version
def version
api_execute('/version', :get).body
end
# Get the current leader
def leader
api_execute(version_prefix + '/stats/leader', :get).body.strip
end
# This method sends api request to etcd server.
#
# This method has following parameters as argument
# * path - etcd server path (etcd server end point)
# * method - the request method used
# * options - any additional parameters used by request method (optional)
# rubocop:disable MethodLength, CyclomaticComplexity
def api_execute(path, method, options = {})
params = options[:params]
case method
when :get
req = build_http_request(Net::HTTP::Get, path, params)
when :post
req = build_http_request(Net::HTTP::Post, path, nil, params)
when :put
req = build_http_request(Net::HTTP::Put, path, nil, params)
when :delete
req = build_http_request(Net::HTTP::Delete, path, params)
else
fail "Unknown http action: #{method}"
end
http = Net::HTTP.new(host, port)
http.read_timeout = options[:timeout] || read_timeout
setup_https(http)
req.basic_auth(user_name, password) if [user_name, password].all?
Log.debug("Invoking: '#{req.class}' against '#{path}")
res = http.request(req)
Log.debug("Response code: #{res.code}")
Log.debug("Response body: #{res.body}")
process_http_request(res)
end
def setup_https(http)
http.use_ssl = use_ssl
http.verify_mode = verify_mode
if config.ssl_cert
Log.debug('Setting up ssl cert')
http.cert = config.ssl_cert
end
if config.ssl_key
Log.debug('Setting up ssl key')
http.key = config.ssl_key
end
if config.ca_file
Log.debug('Setting up ssl ca file to :' + config.ca_file)
http.ca_file = config.ca_file
end
end
# need to have original request to process the response when it redirects
def process_http_request(res)
case res
when HTTP_SUCCESS
Log.debug('Http success')
res
when HTTP_CLIENT_ERROR
fail Error.from_http_response(res)
else
Log.debug('Http error')
Log.debug(res.body)
res.error!
end
end
# rubocop:enable MethodLength
def build_http_request(klass, path, params = nil, body = nil)
path += '?' + URI.encode_www_form(params) unless params.nil?
req = klass.new(path)
req.body = URI.encode_www_form(body) unless body.nil?
Etcd::Log.debug("Built #{klass} path:'#{path}' body:'#{req.body}'")
req
end
end
end
| ruby | MIT | f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917 | 2026-01-04T17:45:15.670612Z | false |
nickryand/vagrant-multi-putty | https://github.com/nickryand/vagrant-multi-putty/blob/4e4e7e7f8449545df687702d671f29caaee39cd2/lib/vagrant-multi-putty.rb | lib/vagrant-multi-putty.rb | require 'vagrant-multi-putty/command'
require 'vagrant-multi-putty/config'
require 'vagrant-multi-putty/plugin'
require 'vagrant-multi-putty/version'
| ruby | MIT | 4e4e7e7f8449545df687702d671f29caaee39cd2 | 2026-01-04T17:45:16.965191Z | false |
nickryand/vagrant-multi-putty | https://github.com/nickryand/vagrant-multi-putty/blob/4e4e7e7f8449545df687702d671f29caaee39cd2/lib/vagrant-multi-putty/command.rb | lib/vagrant-multi-putty/command.rb | # Pieces of this plugin were taken from the bundled vagrant ssh plugin.
require 'rubygems'
require 'openssl'
require 'optparse'
require 'putty/key'
using PuTTY::Key
module VagrantMultiPutty
class Command < Vagrant.plugin(2, :command)
def execute
# config_global is deprecated from v1.5
if Gem::Version.new(::Vagrant::VERSION) >= Gem::Version.new('1.5')
@config = @env.vagrantfile.config
else
@config = @env.config_global
end
options = {:modal => @config.putty.modal,
:plain_auth => false }
opts = OptionParser.new do |opts|
opts.banner = "Usage: vagrant putty [vm-name...] [-- extra putty args]"
opts.on("-p", "--plain", "Plain auth mode which will require the user to provide a password.") do |p|
options[:plain_auth] = p
end
opts.on("-m", "--modal", "Block until all spawned putty processes have exited") do |m|
options[:modal] = m
end
opts.separator ""
end
argv = parse_options(opts)
return -1 if !argv
# This is borrowed from the ssh base command that ships with vagrant.
# It is used to parse out arguments meant for the putty program.
putty_args = ARGV.drop_while { |i| i != "--" }
putty_args = putty_args[1..-1] if !putty_args.empty?
@logger.debug("Putty args: #{putty_args}")
# argv needs to be purged of the extra putty arguments. The remaining arguments
# (if any) will be the VM names to log into.
argv = argv - putty_args
# Since putty is a program with a GUI window, we can perform a spawn and
# detach the process from vagrant.
with_target_vms(argv) do |vm|
@logger.info("Launching putty session to: #{vm.name}")
putty_connect(vm, putty_args, options)
end
if options[:modal]
Process.waitall
@config.putty.after_modal_hook.call
end
return 0
end
def putty_connect(vm, args, options={})
# This isn't called by vagrant automatically.
vm.config.putty.finalize!
ssh_info = vm.ssh_info
# If ssh_info is nil, the machine is not ready for ssh.
raise Vagrant::Errors::SSHNotReady if ssh_info.nil?
ssh_options = []
# Load a saved putty session if provided. Putty (v0.63 at least) appears
# to have a weird bug where a hostname specified on the command line will
# not override the hostname in a session unless the hostname comes after
# the -load option. This doesn't appear to affect any other command line
# options aside from hostname.
ssh_options += ["-load", vm.config.putty.session] if
vm.config.putty.session
# Load options from machine ssh_info.
ssh_options += [ssh_info[:host]]
# config.putty.username overrides the machines ssh_info username.
ssh_options += ["-l", vm.config.putty.username || ssh_info[:username]]
ssh_options += ["-P", ssh_info[:port].to_s]
ssh_options += ["-X"] if ssh_info[:forward_x11]
ssh_options += ["-A"] if ssh_info[:forward_agent]
# Putty only allows one ssh key to be passed with the -i option
# so we default to choosing the first default key if it is not
# explicitly set.
private_key = vm.config.putty.private_key_path ||
get_putty_key_file(ssh_info[:private_key_path][0])
@logger.debug("Putty Private Keys: #{private_key.to_s}")
ssh_options += ["-i", private_key] unless
options[:plain_auth] || private_key == :agent
# Set Connection type to -ssh, in cases other protocol
# stored in Default Settings of Putty.
if vm.config.putty.ssh_options
if vm.config.putty.ssh_options.class == Array
ssh_options += vm.config.putty.ssh_options
else
ssh_options += [vm.config.putty.ssh_options]
end
end
# Add in additional args from the command line.
ssh_options.concat(args) if !args.nil?
# Spawn putty and detach it so we can move on.
@logger.debug("Putty cmd line options: #{ssh_options.to_s}")
pid = spawn(@config.putty.ssh_client, *ssh_options)
@logger.debug("Putty Child Pid: #{pid}")
Process.detach(pid)
end
private
def get_putty_key_file(ssh_key_path)
"#{ssh_key_path}.ppk".tap do |ppk_path|
if !File.exist?(ppk_path) || File.mtime(ssh_key_path) > File.mtime(ppk_path)
ssh_key = OpenSSL::PKey.read(File.read(ssh_key_path, mode: 'rb'))
ppk = ssh_key.to_ppk
ppk.comment = "Converted by vagrant-multi-putty at #{Time.now}"
ppk.save(ppk_path)
end
end
end
end
end
| ruby | MIT | 4e4e7e7f8449545df687702d671f29caaee39cd2 | 2026-01-04T17:45:16.965191Z | false |
nickryand/vagrant-multi-putty | https://github.com/nickryand/vagrant-multi-putty/blob/4e4e7e7f8449545df687702d671f29caaee39cd2/lib/vagrant-multi-putty/version.rb | lib/vagrant-multi-putty/version.rb | module VagrantMultiPutty
VERSION = "1.6.0"
end
| ruby | MIT | 4e4e7e7f8449545df687702d671f29caaee39cd2 | 2026-01-04T17:45:16.965191Z | false |
nickryand/vagrant-multi-putty | https://github.com/nickryand/vagrant-multi-putty/blob/4e4e7e7f8449545df687702d671f29caaee39cd2/lib/vagrant-multi-putty/plugin.rb | lib/vagrant-multi-putty/plugin.rb | require 'vagrant'
module VagrantMultiPutty
class Plugin < Vagrant.plugin("2")
name "vagrant-multi-putty"
description <<-DESC
Vagrant-multi-putty allows you to ssh into your virtual machines using the putty
program (or other compatible ssh clients like kitty). This plugin also supports
opening putty sessions into multi-vm environments.
DESC
command "putty" do
require_relative "command"
Command
end
config "putty" do
require_relative "config"
PuttyConfig
end
end
end
| ruby | MIT | 4e4e7e7f8449545df687702d671f29caaee39cd2 | 2026-01-04T17:45:16.965191Z | false |
nickryand/vagrant-multi-putty | https://github.com/nickryand/vagrant-multi-putty/blob/4e4e7e7f8449545df687702d671f29caaee39cd2/lib/vagrant-multi-putty/config.rb | lib/vagrant-multi-putty/config.rb | module VagrantMultiPutty
class PuttyConfig < Vagrant.plugin(2, :config)
attr_accessor :username
attr_accessor :private_key_path
attr_accessor :after_modal_hook
attr_accessor :modal
attr_accessor :session
attr_accessor :ssh_client
attr_accessor :ssh_options
def after_modal &proc
@after_modal_hook = proc
end
def initialize
@username = UNSET_VALUE
@private_key_path = UNSET_VALUE
@after_modal_hook = UNSET_VALUE
@modal = UNSET_VALUE
@session = UNSET_VALUE
@ssh_client = UNSET_VALUE
@ssh_options = UNSET_VALUE
end
def finalize!
@username = nil if @username == UNSET_VALUE
@private_key_path = nil if @private_key_path == UNSET_VALUE
@after_modal_hook = Proc.new{ } if @after_modal_hook == UNSET_VALUE
@modal = false if @modal == UNSET_VALUE
@session = nil if @session == UNSET_VALUE
@ssh_client = "putty" if @ssh_client == UNSET_VALUE
@ssh_options = "-ssh" if @ssh_options == UNSET_VALUE
end
def validate(machine)
{}
end
end
end
| ruby | MIT | 4e4e7e7f8449545df687702d671f29caaee39cd2 | 2026-01-04T17:45:16.965191Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/activestorage_aliyun_test.rb | test/activestorage_aliyun_test.rb | # frozen_string_literal: true
require "test_helper"
module ActiveStorageAliyun
class Test < ActiveSupport::TestCase
FIXTURE_KEY = SecureRandom.base58(24)
FIXTURE_DATA = "\211PNG\r\n\032\n\000\000\000\rIHDR\000\000\000\020\000\000\000\020\001\003\000\000\000%=m\"\000\000\000\006PLTE\000\000\000\377\377\377\245\331\237\335\000\000\0003IDATx\234c\370\377\237\341\377_\206\377\237\031\016\2603\334?\314p\1772\303\315\315\f7\215\031\356\024\203\320\275\317\f\367\201R\314\f\017\300\350\377\177\000Q\206\027(\316]\233P\000\000\000\000IEND\256B`\202".dup.force_encoding(Encoding::BINARY)
ALIYUN_CONFIG = {
aliyun: {
service: "Aliyun",
access_key_id: ENV["ALIYUN_ACCESS_KEY_ID"],
access_key_secret: ENV["ALIYUN_ACCESS_KEY_SECRET"],
bucket: "carrierwave-aliyun-test",
endpoint: "https://oss-cn-beijing.aliyuncs.com",
path: "activestorage-aliyun-test",
public: true
}
}.freeze
ALIYUN_PRIVATE_CONFIG = {
aliyun: {
service: "Aliyun",
access_key_id: ENV["ALIYUN_ACCESS_KEY_ID"],
access_key_secret: ENV["ALIYUN_ACCESS_KEY_SECRET"],
bucket: "carrierwave-aliyun-test",
endpoint: "https://oss-cn-beijing.aliyuncs.com",
path: "/activestorage-aliyun-test",
public: false
}
}.freeze
def content_disposition_with(type, filename)
@service.send(:content_disposition_with, type: type, filename: ActiveStorage::Filename.wrap(filename))
end
def fixure_url_for(path)
filename_key = File.join("activestorage-aliyun-test", path)
host = ALIYUN_CONFIG[:aliyun][:endpoint].sub("://", "://#{ALIYUN_CONFIG[:aliyun][:bucket]}.")
"#{host}/#{filename_key}"
end
def download_url_for(path, disposition:, filename: nil, content_type: nil, params: {})
host_url = fixure_url_for(path)
params["response-content-type"] = content_type if content_type
params["response-content-disposition"] = content_disposition_with(disposition, filename) if filename
"#{host_url}?#{params.to_query}"
end
setup do
@service = ActiveStorage::Service.configure(:aliyun, ALIYUN_CONFIG)
@private_service = ActiveStorage::Service.configure(:aliyun, ALIYUN_PRIVATE_CONFIG)
@service.upload(FIXTURE_KEY, StringIO.new(FIXTURE_DATA))
end
teardown do
@service.delete FIXTURE_KEY
end
def mock_service_with_path(path)
ActiveStorage::Service.configure(:aliyun, aliyun: {service: "Aliyun", path: path})
end
test "path_for" do
service = mock_service_with_path("/")
assert_equal "foo/bar", service.send(:path_for, "foo/bar")
service = mock_service_with_path("")
assert_equal "foo/bar", service.send(:path_for, "/foo/bar")
service = mock_service_with_path("/hello/world")
assert_equal "hello/world/foo/bar", service.send(:path_for, "/foo/bar")
service = mock_service_with_path("hello//world")
assert_equal "hello/world/foo/bar", service.send(:path_for, "foo/bar")
end
test "get url for public mode" do
url = @service.url(FIXTURE_KEY)
assert_equal fixure_url_for(FIXTURE_KEY), url
res = download_file(url)
assert_equal "200", res.code
assert_equal FIXTURE_DATA, res.body
url = @service.url(FIXTURE_KEY, params: {"x-oss-process": "image/resize,h_100,w_100"})
assert_equal "#{fixure_url_for(FIXTURE_KEY)}?x-oss-process=image%2Fresize%2Ch_100%2Cw_100", url
res = download_file(url)
assert_equal "200", res.code
assert_equal "image/png", res["Content-Type"]
end
test "get private mode url" do
url = @private_service.url(FIXTURE_KEY, expires_in: 500, content_type: "image/png", disposition: :inline,
filename: "foo.jpg")
assert_equal true, url.include?("Signature=")
assert_equal true, url.include?("OSSAccessKeyId=")
assert_equal true, url.include?("response-content-disposition=inline")
assert_equal true, url.include?("response-content-type=image%2Fpng")
res = download_file(url)
assert_equal "200", res.code
assert_equal %(inline; filename="foo.jpg"; filename*=UTF-8''foo.jpg), res["Content-Disposition"]
assert_equal FIXTURE_DATA, res.body
url = @private_service.url(FIXTURE_KEY, expires_in: 500, content_type: "image/png", disposition: :inline,
params: {"x-oss-process" => "image/resize,h_100,w_100"})
assert_equal true, url.include?("x-oss-process=")
assert_equal true, url.include?("Signature=")
assert_equal true, url.include?("OSSAccessKeyId=")
assert_equal true, url.include?("response-content-type=image%2Fpng")
assert_equal false, url.include?("response-content-disposition=")
res = download_file(url)
assert_equal "200", res.code
end
test "host" do
config = ALIYUN_CONFIG.deep_dup
config[:aliyun][:host] = "https://foo.bar"
host_service = ActiveStorage::Service.configure(:aliyun, config)
assert_equal "https://carrierwave-aliyun-test.foo.bar/activestorage-aliyun-test/#{FIXTURE_KEY}", host_service.url(FIXTURE_KEY)
end
test "get url with oss image thumb" do
url = @service.url(FIXTURE_KEY, params: {"x-oss-process" => "image/resize,h_100,w_100"})
assert_equal "#{fixure_url_for(FIXTURE_KEY)}?x-oss-process=image%2Fresize%2Ch_100%2Cw_100", url
res = download_file(url)
assert_equal "200", res.code
end
test "get url with string :filename" do
filename = "Test 中文 [100].zip"
url = @private_service.url(FIXTURE_KEY, content_type: "image/jpeg", disposition: :attachment, filename: filename)
res = download_file(url)
assert_equal "200", res.code
assert_equal "image/jpeg", res["Content-Type"]
expected_disposition = "attachment; filename=\"Test %3F%3F %5B100%5D.zip\"; filename*=UTF-8''Test%20%E4%B8%AD%E6%96%87%20%5B100%5D.zip"
assert_equal expected_disposition, res["Content-Disposition"]
end
test "get url with attachment type disposition" do
filename = ActiveStorage::Filename.new("Test 中文 [100].zip")
url = @private_service.url(FIXTURE_KEY, expires_in: 500, content_type: "image/jpeg", disposition: :attachment,
filename: filename)
res = download_file(url)
assert_equal "200", res.code
assert_equal "image/jpeg", res["Content-Type"]
expected_disposition = "attachment; filename=\"Test %3F%3F %5B100%5D.zip\"; filename*=UTF-8''Test%20%E4%B8%AD%E6%96%87%20%5B100%5D.zip"
assert_equal expected_disposition, res["Content-Disposition"]
end
test "get url with empty content-type" do
filename = ActiveStorage::Filename.new("Test 中文 [100].zip")
url = @service.url(FIXTURE_KEY, expires_in: 500, content_type: "", disposition: :attachment, filename: filename)
assert_no_match "response-content-type", url
end
test "uploading with integrity" do
key = SecureRandom.base58(24)
data = "Something else entirely!"
@service.upload(key, StringIO.new(data), checksum: Digest::MD5.base64digest(data))
assert_equal data, @service.download(key)
ensure
@service.delete key
end
test "downloading" do
assert_equal FIXTURE_DATA, @private_service.download(FIXTURE_KEY)
assert_equal FIXTURE_DATA, @service.download(FIXTURE_KEY)
end
test "downloading in chunks" do
chunks = []
@service.download(FIXTURE_KEY) do |chunk|
chunks << chunk
end
assert_equal [FIXTURE_DATA], chunks
end
test "downloading chunk" do
chunk = @service.download_chunk(FIXTURE_KEY, 0..8)
assert_equal 9, chunk.length
assert_equal FIXTURE_DATA[0..8], chunk
# exclude end
chunk = @service.download_chunk(FIXTURE_KEY, 0...8)
assert_equal 8, chunk.length
assert_equal FIXTURE_DATA[0...8], chunk
chunk = @service.download_chunk(FIXTURE_KEY, 10...15)
assert_equal 5, chunk.length
assert_equal FIXTURE_DATA[10..14], chunk
end
test "existing" do
assert @service.exist?(FIXTURE_KEY)
assert_not @service.exist?("#{FIXTURE_KEY}nonsense")
end
test "deleting" do
@service.delete FIXTURE_KEY
assert_not @service.exist?(FIXTURE_KEY)
end
test "deleting nonexistent key" do
assert_nothing_raised do
@service.delete SecureRandom.base58(24)
end
end
test "deleting by prefix" do
prefix = SecureRandom.hex
begin
@service.upload("#{prefix}/a/a", StringIO.new(FIXTURE_DATA))
@service.upload("#{prefix}/a/b", StringIO.new(FIXTURE_DATA))
@service.upload("#{prefix}/b/a", StringIO.new(FIXTURE_DATA))
@service.delete_prefixed("#{prefix}/a/")
assert_not @service.exist?("#{prefix}/a/a")
assert_not @service.exist?("#{prefix}/a/b")
assert @service.exist?("#{prefix}/b/a")
ensure
@service.delete("#{prefix}/a/a")
@service.delete("#{prefix}/a/b")
@service.delete("#{prefix}/b/a")
end
end
test "headers_for_direct_upload" do
key = "test-file"
data = "Something else entirely!"
checksum = Digest::MD5.base64digest(data)
content_type = "text/plain"
date = "Fri, 02 Feb 2018 06:45:25 GMT"
travel_to Time.parse(date) do
headers = @service.headers_for_direct_upload(key, expires_in: 5.minutes, content_type: content_type,
content_length: data.size, checksum: checksum)
assert_equal date, headers["x-oss-date"]
assert_equal "text/plain", headers["Content-Type"]
assert_equal checksum, headers["Content-MD5"]
assert headers["Authorization"].start_with?("OSS #{ENV["ALIYUN_ACCESS_KEY_ID"]}:")
end
end
test "direct upload" do
key = SecureRandom.base58(24)
data = "Something else entirely!"
checksum = Digest::MD5.base64digest(data)
url = @service.url_for_direct_upload(key, expires_in: 5.minutes, content_type: "text/plain",
content_length: data.size, checksum: checksum)
assert_equal fixure_url_for(key), url
begin
headers = @service.headers_for_direct_upload(key, expires_in: 5.minutes, content_type: "text/plain",
content_length: data.size, checksum: checksum)
uri = URI.parse url
request = Net::HTTP::Put.new uri.request_uri
request.body = data
headers.each_key do |field|
request.add_field field, headers[field]
end
Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
http.request request
end
assert_equal data, @service.download(key)
ensure
@service.delete key
end
end
end
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/model_test.rb | test/model_test.rb | # frozen_string_literal: true
require "test_helper"
module ActiveStorageAliyun
class ModelTest < ActionDispatch::IntegrationTest
test "service_name" do
u = User.new(avatar: fixture_file_upload("foo.jpg"))
assert_equal "aliyun", u.avatar.blob.service_name
u = User.new(files: [fixture_file_upload("foo.jpg")])
assert_equal "aliyun", u.files.first.blob.service_name
end
end
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/test_helper.rb | test/test_helper.rb | # frozen_string_literal: true
# Configure Rails Environment
ENV["RAILS_ENV"] = "test"
require_relative "../test/dummy/config/environment"
require "rails"
require "minitest/autorun"
require "rails/test_help"
require "active_support/core_ext/securerandom"
require "activestorage-aliyun"
ENV["BACKTRACE"] = "1"
ENV["RUBYOPT"] = "-W0"
# Load fixtures from the engine
if ActiveSupport::TestCase.respond_to?(:fixture_path=)
ActiveSupport::TestCase.fixture_path = File.expand_path("fixtures", __dir__)
ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path
ActiveSupport::TestCase.file_fixture_path = "#{ActiveSupport::TestCase.fixture_path}/files"
ActiveSupport::TestCase.fixtures :all
end
module ActiveSupport
class TestCase
def download_file(url)
Net::HTTP.get_response(URI.parse(url))
end
end
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/app/jobs/application_job.rb | test/dummy/app/jobs/application_job.rb | class ApplicationJob < ActiveJob::Base
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/app/helpers/users_helper.rb | test/dummy/app/helpers/users_helper.rb | module UsersHelper
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/app/helpers/application_helper.rb | test/dummy/app/helpers/application_helper.rb | module ApplicationHelper
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/app/controllers/users_controller.rb | test/dummy/app/controllers/users_controller.rb | class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
# GET /users
def index
@users = User.all
end
# GET /users/1
def show
end
# GET /users/new
def new
@user = User.new
end
# GET /users/1/edit
def edit
end
# POST /users
def create
@user = User.new(user_params)
if @user.save
redirect_to @user, notice: "User was successfully created."
else
render :new
end
end
# PATCH/PUT /users/1
def update
if @user.update(user_params)
redirect_to @user, notice: "User was successfully updated."
else
render :edit
end
end
# DELETE /users/1
def destroy
@user.destroy
redirect_to users_url, notice: "User was successfully destroyed."
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def user_params
params.require(:user).permit(:name, :avatar, files: [])
end
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/app/controllers/application_controller.rb | test/dummy/app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/app/models/application_record.rb | test/dummy/app/models/application_record.rb | class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/app/models/user.rb | test/dummy/app/models/user.rb | class User < ApplicationRecord
has_one_attached :avatar, service: :aliyun
has_many_attached :files, service: :aliyun
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/app/mailers/application_mailer.rb | test/dummy/app/mailers/application_mailer.rb | class ApplicationMailer < ActionMailer::Base
default from: "from@example.com"
layout "mailer"
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/app/channels/application_cable/channel.rb | test/dummy/app/channels/application_cable/channel.rb | module ApplicationCable
class Channel < ActionCable::Channel::Base
end
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/app/channels/application_cable/connection.rb | test/dummy/app/channels/application_cable/connection.rb | module ApplicationCable
class Connection < ActionCable::Connection::Base
end
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/db/schema.rb | test/dummy/db/schema.rb | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `bin/rails
# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2021_01_26_105837) do
create_table "active_storage_attachments", force: :cascade do |t|
t.string "name", null: false
t.string "record_type", null: false
t.integer "record_id", null: false
t.integer "blob_id", null: false
t.datetime "created_at", null: false
t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true
end
create_table "active_storage_blobs", force: :cascade do |t|
t.string "key", null: false
t.string "filename", null: false
t.string "content_type"
t.text "metadata"
t.integer "byte_size", null: false
t.string "checksum", null: false
t.datetime "created_at", null: false
t.string "service_name", null: false
t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true
end
create_table "active_storage_variant_records", force: :cascade do |t|
t.bigint "blob_id", null: false
t.string "variation_digest", null: false
t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true
end
create_table "users", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id"
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/db/migrate/20210126105836_add_service_name_to_active_storage_blobs.active_storage.rb | test/dummy/db/migrate/20210126105836_add_service_name_to_active_storage_blobs.active_storage.rb | # This migration comes from active_storage (originally 20190112182829)
class AddServiceNameToActiveStorageBlobs < ActiveRecord::Migration[6.0]
def up
unless column_exists?(:active_storage_blobs, :service_name)
add_column :active_storage_blobs, :service_name, :string
if configured_service = ActiveStorage::Blob.service.name
ActiveStorage::Blob.unscoped.update_all(service_name: configured_service)
end
change_column :active_storage_blobs, :service_name, :string, null: false
end
end
def down
remove_column :active_storage_blobs, :service_name
end
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/db/migrate/20210126105837_create_active_storage_variant_records.active_storage.rb | test/dummy/db/migrate/20210126105837_create_active_storage_variant_records.active_storage.rb | # This migration comes from active_storage (originally 20191206030411)
class CreateActiveStorageVariantRecords < ActiveRecord::Migration[6.0]
def change
create_table :active_storage_variant_records do |t|
t.belongs_to :blob, null: false, index: false
t.string :variation_digest, null: false
t.index %i[blob_id variation_digest], name: "index_active_storage_variant_records_uniqueness", unique: true
t.foreign_key :active_storage_blobs, column: :blob_id
end
end
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/db/migrate/20180201031134_create_users.rb | test/dummy/db/migrate/20180201031134_create_users.rb | class CreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
t.string :name
t.timestamps
end
end
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/db/migrate/20180201031103_create_active_storage_tables.active_storage.rb | test/dummy/db/migrate/20180201031103_create_active_storage_tables.active_storage.rb | # This migration comes from active_storage (originally 20170806125915)
class CreateActiveStorageTables < ActiveRecord::Migration[5.2]
def change
create_table :active_storage_blobs do |t|
t.string :key, null: false
t.string :filename, null: false
t.string :content_type
t.text :metadata
t.bigint :byte_size, null: false
t.string :checksum, null: false
t.datetime :created_at, null: false
t.index [:key], unique: true
end
create_table :active_storage_attachments do |t|
t.string :name, null: false
t.references :record, null: false, polymorphic: true, index: false
t.references :blob, null: false
t.datetime :created_at, null: false
t.index [:record_type, :record_id, :name, :blob_id], name: "index_active_storage_attachments_uniqueness", unique: true
end
end
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/application.rb | test/dummy/config/application.rb | require_relative "boot"
require "rails/all"
Bundler.require(*Rails.groups)
require "activestorage-aliyun"
module Dummy
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0
# Settings in config/environments/* take precedence over those specified here.
# 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 | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/environment.rb | test/dummy/config/environment.rb | # Load the Rails application.
require_relative "application"
# Initialize the Rails application.
Rails.application.initialize!
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/puma.rb | test/dummy/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.
#
threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
threads threads_count, 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 number of `workers` to boot in clustered mode.
# Workers are forked webserver 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 | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/routes.rb | test/dummy/config/routes.rb | Rails.application.routes.draw do
resources :users
root to: "users#index"
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/spring.rb | test/dummy/config/spring.rb | %w[
.ruby-version
.rbenv-vars
tmp/restart.txt
tmp/caching-dev.txt
].each { |path| Spring.watch(path) }
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/boot.rb | test/dummy/config/boot.rb | # Set up gems listed in the Gemfile.
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../../Gemfile", __dir__)
require "bundler/setup" if File.exist?(ENV["BUNDLE_GEMFILE"])
$LOAD_PATH.unshift File.expand_path("../../../lib", __dir__)
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/initializers/content_security_policy.rb | test/dummy/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
# 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?
# # 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 | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/initializers/filter_parameter_logging.rb | test/dummy/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 += [
:passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn
]
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/initializers/application_controller_renderer.rb | test/dummy/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 | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/initializers/wrap_parameters.rb | test/dummy/config/initializers/wrap_parameters.rb | # Be sure to restart your server when you modify this file.
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json]
end
# To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do
# self.include_root_in_json = true
# end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/initializers/inflections.rb | test/dummy/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 | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/initializers/cookies_serializer.rb | test/dummy/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 | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/initializers/permissions_policy.rb | test/dummy/config/initializers/permissions_policy.rb | # Define an application-wide HTTP permissions policy. For further
# information see https://developers.google.com/web/updates/2018/06/feature-policy
#
# Rails.application.config.permissions_policy do |f|
# f.camera :none
# f.gyroscope :none
# f.microphone :none
# f.usb :none
# f.fullscreen :self
# f.payment :self, "https://secure.example.com"
# end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/initializers/assets.rb | test/dummy/config/initializers/assets.rb | # Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = "1.0"
# Add additional assets to the asset load path.
# Rails.application.config.assets.paths << Emoji.images_path
# Add Yarn node_modules folder to the asset load path.
Rails.application.config.assets.paths << Rails.root.join("node_modules")
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in the app/assets
# folder are already added.
# Rails.application.config.assets.precompile += %w( admin.js admin.css )
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/initializers/backtrace_silencers.rb | test/dummy/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| /my_noisy_library/.match?(line) }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code
# by setting BACKTRACE=1 before calling your invocation, like "BACKTRACE=1 ./bin/rails runner 'MyClass.perform'".
Rails.backtrace_cleaner.remove_silencers! if ENV["BACKTRACE"]
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/initializers/mime_types.rb | test/dummy/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 | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/initializers/new_framework_defaults_6_1.rb | test/dummy/config/initializers/new_framework_defaults_6_1.rb | # Be sure to restart your server when you modify this file.
#
# This file contains migration options to ease your Rails 6.1 upgrade.
#
# Once upgraded flip defaults one by one to migrate to the new default.
#
# Read the Guide for Upgrading Ruby on Rails for more info on each option.
# Support for inversing belongs_to -> has_many Active Record associations.
# Rails.application.config.active_record.has_many_inversing = true
# Track Active Storage variants in the database.
# Rails.application.config.active_storage.track_variants = true
# Apply random variation to the delay when retrying failed jobs.
# Rails.application.config.active_job.retry_jitter = 0.15
# Stop executing `after_enqueue`/`after_perform` callbacks if
# `before_enqueue`/`before_perform` respectively halts with `throw :abort`.
# Rails.application.config.active_job.skip_after_callbacks_if_terminated = true
# Specify cookies SameSite protection level: either :none, :lax, or :strict.
#
# This change is not backwards compatible with earlier Rails versions.
# It's best enabled when your entire app is migrated and stable on 6.1.
# Rails.application.config.action_dispatch.cookies_same_site_protection = :lax
# Generate CSRF tokens that are encoded in URL-safe Base64.
#
# This change is not backwards compatible with earlier Rails versions.
# It's best enabled when your entire app is migrated and stable on 6.1.
# Rails.application.config.action_controller.urlsafe_csrf_tokens = true
# Specify whether `ActiveSupport::TimeZone.utc_to_local` returns a time with an
# UTC offset or a UTC time.
# ActiveSupport.utc_to_local_returns_utc_offset_times = true
# Change the default HTTP status code to `308` when redirecting non-GET/HEAD
# requests to HTTPS in `ActionDispatch::SSL` middleware.
# Rails.application.config.action_dispatch.ssl_default_redirect_status = 308
# Use new connection handling API. For most applications this won't have any
# effect. For applications using multiple databases, this new API provides
# support for granular connection swapping.
# Rails.application.config.active_record.legacy_connection_handling = false
# Make `form_with` generate non-remote forms by default.
# Rails.application.config.action_view.form_with_generates_remote_forms = false
# Set the default queue name for the analysis job to the queue adapter default.
# Rails.application.config.active_storage.queues.analysis = nil
# Set the default queue name for the purge job to the queue adapter default.
# Rails.application.config.active_storage.queues.purge = nil
# Set the default queue name for the incineration job to the queue adapter default.
# Rails.application.config.action_mailbox.queues.incineration = nil
# Set the default queue name for the routing job to the queue adapter default.
# Rails.application.config.action_mailbox.queues.routing = nil
# Set the default queue name for the mail deliver job to the queue adapter default.
# Rails.application.config.action_mailer.deliver_later_queue_name = nil
# Generate a `Link` header that gives a hint to modern browsers about
# preloading assets when using `javascript_include_tag` and `stylesheet_link_tag`.
# Rails.application.config.action_view.preload_links_header = true
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/environments/test.rb | test/dummy/config/environments/test.rb | require "active_support/core_ext/integer/time"
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure public file server for tests with Cache-Control for performance.
config.public_file_server.enabled = true
config.public_file_server.headers = {
"Cache-Control" => "public, max-age=#{1.hour.to_i}"
}
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.cache_store = :null_store
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Store uploaded files on the local file system in a temporary directory.
config.active_storage.service = :local
config.action_mailer.perform_caching = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raise exceptions for disallowed deprecations.
config.active_support.disallowed_deprecation = :raise
# Tell Active Support which deprecation messages to disallow.
config.active_support.disallowed_deprecation_warnings = []
# Raises error for missing translations.
# config.i18n.raise_on_missing_translations = true
# Annotate rendered view with file names.
# config.action_view.annotate_rendered_view_with_filenames = true
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/environments/development.rb | test/dummy/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
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join("tmp", "caching-dev.txt").exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
"Cache-Control" => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options)
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# 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 | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/test/dummy/config/environments/production.rb | test/dummy/config/environments/production.rb | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV["RAILS_SERVE_STATIC_FILES"].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options)
config.active_storage.service = :local
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [:request_id]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "dummy_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/lib/activestorage-aliyun.rb | lib/activestorage-aliyun.rb | # frozen_string_literal: true
# require "active_storage_aliyun/railtie"
module ActiveStorageAliyun
# Your code goes here...
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/lib/active_storage/service/aliyun_service.rb | lib/active_storage/service/aliyun_service.rb | # frozen_string_literal: true
require "aliyun/oss"
module ActiveStorage
class Service::AliyunService < Service
def initialize(**config)
Aliyun::Common::Logging.set_log_file("/dev/null")
@config = config
@public = @config.fetch(:public, false)
# Compatible with mode config
if @config.fetch(:mode, nil) == "public"
ActiveSupport::Deprecation.warn("mode has deprecated, and will remove in 1.1.0, use public: true instead.")
@public = true
end
end
CHUNK_SIZE = 1024 * 1024
def upload(key, io, checksum: nil, content_type: nil, disposition: nil, filename: nil, custom_metadata: {}, **)
instrument :upload, key: key, checksum: checksum do
content_type ||= Marcel::MimeType.for(io)
bucket.put_object(path_for(key), content_type: content_type, metas: custom_metadata) do |stream|
stream << io.read(CHUNK_SIZE) until io.eof?
end
end
end
def download(key, &block)
if block
instrument :streaming_download, key: key do
bucket.get_object(path_for(key), &block)
end
else
instrument :download, key: key do
chunk_buff = []
bucket.get_object(path_for(key)) do |chunk|
chunk_buff << chunk
end
chunk_buff.join
end
end
end
def download_chunk(key, range)
instrument :download_chunk, key: key, range: range do
chunk_buff = []
range_end = range.exclude_end? ? range.end : range.end + 1
bucket.get_object(path_for(key), range: [range.begin, range_end]) do |chunk|
chunk_buff << chunk
end
chunk_buff.join
end
end
def delete(key)
instrument :delete, key: key do
bucket.delete_object(path_for(key))
end
end
def delete_prefixed(prefix)
instrument :delete_prefixed, prefix: prefix do
files = bucket.list_objects(prefix: path_for(prefix))
return if files.blank?
keys = files.map(&:key)
return if keys.blank?
bucket.batch_delete_objects(keys, quiet: true)
end
end
def exist?(key)
instrument :exist, key: key do |_payload|
bucket.object_exists?(path_for(key))
end
end
# You must setup CORS on OSS control panel to allow JavaScript request from your site domain.
# https://www.alibabacloud.com/help/zh/doc-detail/31988.htm
# https://help.aliyun.com/document_detail/31925.html
# Source: *.your.host.com
# Allowed Methods: POST, PUT, HEAD
# Allowed Headers: *
def url_for_direct_upload(key, expires_in:, content_type:, content_length:, checksum:, custom_metadata: {})
instrument :url, key: key do |payload|
generated_url = bucket.object_url(path_for(key), false)
payload[:url] = generated_url
generated_url
end
end
# Headers for Direct Upload
# https://help.aliyun.com/document_detail/31951.html
# headers["Date"] is required use x-oss-date instead
def headers_for_direct_upload(key, content_type:, checksum:, custom_metadata: {}, **)
date = Time.now.httpdate
{
"Content-Type" => content_type,
"Content-MD5" => checksum,
"Authorization" => authorization(key, content_type, checksum, date),
"x-oss-date" => date,
**custom_metadata_headers(custom_metadata)
}
end
def custom_metadata_headers(metadata)
metadata.transform_keys { |key| "x-oss-meta-#{key}" }
end
# Remove this in Rails 6.1, compatiable with Rails 6.0.0
def url(key, **options)
instrument :url, key: key do |payload|
generated_url =
if public?
public_url(key, **options)
else
private_url(key, **options)
end
payload[:url] = generated_url
generated_url
end
end
private
attr_reader :config
def private_url(key, expires_in: 60, filename: nil, content_type: nil, disposition: nil, params: {}, **)
filekey = path_for(key)
params["response-content-type"] = content_type unless content_type.blank?
if filename
filename = ActiveStorage::Filename.wrap(filename)
params["response-content-disposition"] = content_disposition_with(type: disposition, filename: filename)
end
object_url(filekey, sign: true, expires_in: expires_in, params: params)
end
def public_url(key, params: {}, **)
object_url(path_for(key), sign: false, params: params)
end
# Remove this in Rails 6.1, compatiable with Rails 6.0.0
def public?
@public == true
end
def path_for(key)
root_path = config.fetch(:path, nil)
full_path = if root_path.blank? || root_path == "/"
key
else
File.join(root_path, key)
end
full_path.gsub(%r{^/}, "").squeeze("/")
end
def object_url(key, sign: false, expires_in: 60, params: {})
url = host_bucket.object_url(key, false)
unless sign
return url if params.blank?
return "#{url}?#{params.to_query}"
end
resource = "/#{host_bucket.name}/#{key}"
expires = Time.now.to_i + expires_in
query = {
"Expires" => expires,
"OSSAccessKeyId" => config.fetch(:access_key_id)
}
query.merge!(params)
resource += "?" + params.map { |k, v| "#{k}=#{v}" }.sort.join("&") if params.present?
string_to_sign = ["GET", "", "", expires, resource].join("\n")
query["Signature"] = host_bucket.sign(string_to_sign)
[url, query.to_query].join("?")
end
def bucket
return @bucket if defined? @bucket
@bucket = client.get_bucket(config.fetch(:bucket))
@bucket
end
def host_bucket
return @host_bucket if defined? @host_bucket
host_bucket_client = host ? host_client : client
@host_bucket = host_bucket_client.get_bucket(config.fetch(:bucket))
@host_bucket
end
def authorization(key, content_type, checksum, date)
filename = File.expand_path("/#{bucket.name}/#{path_for(key)}")
addition_headers = "x-oss-date:#{date}"
sign = ["PUT", checksum, content_type, date, addition_headers, filename].join("\n")
signature = bucket.sign(sign)
"OSS #{config.fetch(:access_key_id)}:#{signature}"
end
def endpoint
config.fetch(:endpoint, "https://oss-cn-hangzhou.aliyuncs.com")
end
def host
config.fetch(:host, nil)
end
def client
@client ||= Aliyun::OSS::Client.new(
endpoint: endpoint,
access_key_id: config.fetch(:access_key_id),
access_key_secret: config.fetch(:access_key_secret),
cname: config.fetch(:cname, false)
)
end
def host_client
@host_client ||= Aliyun::OSS::Client.new(
endpoint: host,
access_key_id: config.fetch(:access_key_id),
access_key_secret: config.fetch(:access_key_secret),
cname: config.fetch(:cname, false)
)
end
end
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/lib/active_storage_aliyun/version.rb | lib/active_storage_aliyun/version.rb | # frozen_string_literal: true
module ActiveStorageAliyun
VERSION = "1.2.0"
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
huacnlee/activestorage-aliyun | https://github.com/huacnlee/activestorage-aliyun/blob/913697c234924765cbd771687e6550f9fab1cfb8/lib/active_storage_aliyun/railtie.rb | lib/active_storage_aliyun/railtie.rb | # frozen_string_literal: true
module ActiveStorageAliyun
class Railtie < ::Rails::Railtie
end
end
| ruby | MIT | 913697c234924765cbd771687e6550f9fab1cfb8 | 2026-01-04T17:45:18.412428Z | false |
ruby-av/paperclip-av-transcoder | https://github.com/ruby-av/paperclip-av-transcoder/blob/76679abf0e4cbcc8ff1f7d879a2f1425e10661b5/spec/schema.rb | spec/schema.rb | ActiveRecord::Schema.define version: 0 do
create_table "documents", force: true do |t|
t.string :owner
t.string :video_file_name
t.string :video_content_type
t.integer :video_updated_at
t.integer :video_file_size
t.string :image_file_name
t.string :image_content_type
t.integer :image_updated_at
t.integer :image_file_size
end
end | ruby | MIT | 76679abf0e4cbcc8ff1f7d879a2f1425e10661b5 | 2026-01-04T17:45:18.794313Z | false |
ruby-av/paperclip-av-transcoder | https://github.com/ruby-av/paperclip-av-transcoder/blob/76679abf0e4cbcc8ff1f7d879a2f1425e10661b5/spec/spec_helper.rb | spec/spec_helper.rb | ENV["RAILS_ENV"] = "test"
require 'coveralls'
Coveralls.wear!
require 'rubygems'
require 'rspec'
require 'bundler/setup'
require 'paperclip'
require 'paperclip/railtie'
# Prepare activerecord
require "active_record"
require 'paperclip/av/transcoder'
Bundler.require(:default)
# Connect to sqlite
ActiveRecord::Base.establish_connection("adapter" => "sqlite3", "database" => ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)
load(File.join(File.dirname(__FILE__), 'schema.rb'))
Paperclip::Railtie.insert
RSpec.configure do |config|
config.run_all_when_everything_filtered = true
config.filter_run focus: true
end
class Document < ActiveRecord::Base
has_attached_file :video,
storage: :filesystem,
path: "./spec/tmp/:id.:extension",
url: "/spec/tmp/:id.:extension",
whiny: true,
styles: {
small: {
format: 'ogv',
convert_options: {
output: {
ab: '256k',
ar: 44100,
ac: 2
}
}
},
thumb: {
format: 'jpg',
time: 0
}
},
processors: [:transcoder]
has_attached_file :image,
storage: :filesystem,
path: "./spec/tmp/:id.:extension",
url: "/spec/tmp/:id.:extension",
whiny: true,
styles: {
small: "100x100"
},
processors: [:transcoder, :thumbnail]
do_not_validate_attachment_file_type :video
do_not_validate_attachment_file_type :image
end | ruby | MIT | 76679abf0e4cbcc8ff1f7d879a2f1425e10661b5 | 2026-01-04T17:45:18.794313Z | false |
ruby-av/paperclip-av-transcoder | https://github.com/ruby-av/paperclip-av-transcoder/blob/76679abf0e4cbcc8ff1f7d879a2f1425e10661b5/spec/transcoder/transcoder_spec.rb | spec/transcoder/transcoder_spec.rb | require 'spec_helper'
describe Paperclip::Transcoder do
let(:supported) { File.new(Dir.pwd + '/spec/support/assets/sample.mp4') }
let(:unsupported) { File.new(File.expand_path('spec/support/assets/image.png')) }
let(:destination) { Pathname.new("#{Dir.tmpdir}/transcoder/") }
describe "supported formats" do
let(:subject) { Paperclip::Transcoder.new(supported) }
let(:document) { Document.create(video: Rack::Test::UploadedFile.new(supported, 'video/mp4')) }
describe ".transcode" do
it { expect(File.exists?(document.video.path(:small))).to eq true }
it { expect(File.exists?(document.video.path(:thumb))).to eq true }
end
end
describe "unsupported formats" do
let(:subject) { Paperclip::Transcoder.new(unsupported) }
let(:document) { Document.create(image: Rack::Test::UploadedFile.new(unsupported, 'image/png')) }
describe ".transcode" do
it { expect(File.exists?(document.image.path(:small))).to eq true }
end
end
end | ruby | MIT | 76679abf0e4cbcc8ff1f7d879a2f1425e10661b5 | 2026-01-04T17:45:18.794313Z | false |
ruby-av/paperclip-av-transcoder | https://github.com/ruby-av/paperclip-av-transcoder/blob/76679abf0e4cbcc8ff1f7d879a2f1425e10661b5/lib/paperclip/paperclip_processors/transcoder.rb | lib/paperclip/paperclip_processors/transcoder.rb | module Paperclip
class Transcoder < Processor
attr_accessor :geometry, :format, :whiny, :convert_options
# Creates a Video object set to work on the +file+ given. It
# will attempt to transcode the video into one defined by +target_geometry+
# which is a "WxH"-style string. +format+ should be specified.
# Video transcoding will raise no errors unless
# +whiny+ is true (which it is, by default. If +convert_options+ is
# set, the options will be appended to the convert command upon video transcoding.
def initialize file, options = {}, attachment = nil
@file = file
@current_format = File.extname(@file.path)
@basename = File.basename(@file.path, @current_format)
@cli = ::Av.cli
@meta = ::Av.cli.identify(@file.path)
@whiny = options[:whiny].nil? ? true : options[:whiny]
@convert_options = set_convert_options(options)
@format = options[:format]
@geometry = options[:geometry]
unless @geometry.nil?
modifier = @geometry[0]
@geometry[0] = '' if ['#', '<', '>'].include? modifier
@width, @height = @geometry.split('x')
@keep_aspect = @width[0] == '!' || @height[0] == '!'
@pad_only = @keep_aspect && modifier == '#'
@enlarge_only = @keep_aspect && modifier == '<'
@shrink_only = @keep_aspect && modifier == '>'
end
@time = options[:time].nil? ? 3 : options[:time]
@auto_rotate = options[:auto_rotate].nil? ? false : options[:auto_rotate]
@pad_color = options[:pad_color].nil? ? "black" : options[:pad_color]
@convert_options[:output][:s] = format_geometry(@geometry) if @geometry.present?
attachment.instance_write(:meta, @meta) if attachment
end
# Performs the transcoding of the +file+ into a thumbnail/video. Returns the Tempfile
# that contains the new image/video.
def make
::Av.logger = Paperclip.logger
@cli.add_source @file
dst = Tempfile.new([@basename, @format ? ".#{@format}" : ''])
dst.binmode
if @meta
log "Transcoding supported file #{@file.path}"
@cli.add_source(@file.path)
@cli.add_destination(dst.path)
@cli.reset_input_filters
if output_is_image?
@time = @time.call(@meta, @options) if @time.respond_to?(:call)
@cli.filter_seek @time
@cli.filter_rotate @meta[:rotate] if @auto_rotate && !@meta[:rotate].nil?
end
if @convert_options.present?
if @convert_options[:input]
@convert_options[:input].each do |h|
@cli.add_input_param h
end
end
if @convert_options[:output]
@convert_options[:output].each do |h|
@cli.add_output_param h
end
end
end
begin
@cli.run
log "Successfully transcoded #{@basename} to #{dst}"
rescue Cocaine::ExitStatusError => e
raise Paperclip::Error, "error while transcoding #{@basename}: #{e}" if @whiny
end
else
log "Unsupported file #{@file.path}"
# If the file is not supported, just return it
dst << @file.read
dst.close
end
dst
end
def log message
Paperclip.log "[transcoder] #{message}"
end
def set_convert_options options
return options[:convert_options] if options[:convert_options].present?
options[:convert_options] = {output: {}}
return options[:convert_options]
end
def format_geometry geometry
return unless geometry.present?
return geometry.gsub(/[#!<>)]/, '')
end
def output_is_image?
!!@format.to_s.match(/jpe?g|png|gif$/)
end
end
class Attachment
def meta
instance_read(:meta)
end
end
end
| ruby | MIT | 76679abf0e4cbcc8ff1f7d879a2f1425e10661b5 | 2026-01-04T17:45:18.794313Z | false |
ruby-av/paperclip-av-transcoder | https://github.com/ruby-av/paperclip-av-transcoder/blob/76679abf0e4cbcc8ff1f7d879a2f1425e10661b5/lib/paperclip/av/transcoder.rb | lib/paperclip/av/transcoder.rb | require "paperclip/av/transcoder/version"
require "av"
require File.join(File.expand_path(File.dirname(__FILE__)), "../paperclip_processors/transcoder") | ruby | MIT | 76679abf0e4cbcc8ff1f7d879a2f1425e10661b5 | 2026-01-04T17:45:18.794313Z | false |
ruby-av/paperclip-av-transcoder | https://github.com/ruby-av/paperclip-av-transcoder/blob/76679abf0e4cbcc8ff1f7d879a2f1425e10661b5/lib/paperclip/av/transcoder/version.rb | lib/paperclip/av/transcoder/version.rb | module Paperclip
module Av
module Transcoder
VERSION = "0.6.4"
end
end
end
| ruby | MIT | 76679abf0e4cbcc8ff1f7d879a2f1425e10661b5 | 2026-01-04T17:45:18.794313Z | false |
jkeen/tracking_number_data | https://github.com/jkeen/tracking_number_data/blob/802d8a55e506b65bb5c820ed4e6d259a29f3911e/utils/gen_dpd_service_codes.rb | utils/gen_dpd_service_codes.rb | require 'json'
path = File.expand_path(File.join(__dir__, 'dpd-service-codes.txt'))
file = File.read(path)
processed = file.lines.collect do |line|
items = line.split(' ')
data = {}
data[:code] = items.shift
data[:service] = items.shift
data[:description] = items.shift
data
end
puts JSON.generate(processed) | ruby | MIT | 802d8a55e506b65bb5c820ed4e6d259a29f3911e | 2026-01-04T17:45:13.109005Z | false |
jkeen/tracking_number_data | https://github.com/jkeen/tracking_number_data/blob/802d8a55e506b65bb5c820ed4e6d259a29f3911e/utils/gen_dpd_country_codes.rb | utils/gen_dpd_country_codes.rb | require 'json'
path = File.expand_path(File.join(__dir__, 'dpd-country-codes.txt'))
file = File.read(path)
processed = file.lines.collect do |line|
items = line.split(' ')
data = {}
data[:code] = items.pop
data[:country_code] = items.pop
data[:country_short_code] = items.pop
data[:country] = items.join(' ')
data
end
puts JSON.generate(processed) | ruby | MIT | 802d8a55e506b65bb5c820ed4e6d259a29f3911e | 2026-01-04T17:45:13.109005Z | false |
jkeen/tracking_number_data | https://github.com/jkeen/tracking_number_data/blob/802d8a55e506b65bb5c820ed4e6d259a29f3911e/spec/implementation_spec.rb | spec/implementation_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'tracking_number'
def load_courier_data
TrackingNumber::Loader.load_tracking_number_data(File.expand_path(File.join(__dir__, '../couriers/')))
end
load_courier_data.each do |data|
klass = data[:class]
courier_name = data[:name]
courier_code = data[:courier_code].to_sym
tracking_info = data[:info]
match_groups = [tracking_info[:regex]].flatten.join.scan(/<(\w+)>/).flatten
describe tracking_info[:name] do
context "valid number" do
tracking_info[:test_numbers][:valid].each do |valid_number|
context valid_number do
subject { valid_number }
let(:tracking_number) { klass.new(valid_number) }
it 'is found in search' do
matches = TrackingNumber.search(subject, match: :all)
results = matches.collect(&:class).collect(&:to_s)
expect(results.include?(klass.to_s)).to(eq(true))
end
if tracking_info[:validation][:checksum]
it 'fails on check digit changes' do
should_fail_on_check_digit_changes(valid_number)
end
end
it 'is found in search regardless of spacing' do
should_detect_number_variants(valid_number, klass, tracking_info)
end
it 'validates' do
expect(tracking_number.carrier).to(eq(courier_code))
expect(tracking_number.valid?).to(eq(true))
end
it "returns #{courier_code} for #courier_code" do
tracking_number = klass.new(valid_number)
expect(tracking_number.courier_code).to(eq(courier_code))
end
it "returns correct courier name" do
if tracking_number.matching_additional['Courier']
expect(tracking_number.courier_name).to(eq(tracking_number.matching_additional['Courier'][:courier]))
else
expect(tracking_number.courier_name).to(eq(courier_name))
end
end
it 'does not error when calling #service_type' do
service_type = tracking_number.service_type
expect((service_type.is_a?(String) or service_type.nil?)).to(be_truthy)
end
it 'does not error when calling #destination' do
expect((tracking_number.destination_zip.is_a?(String) or tracking_number.destination_zip.nil?)).to(be_truthy)
end
it 'does not error when calling #shipper' do
expect((tracking_number.shipper_id.is_a?(String) or tracking_number.shipper_id.nil?)).to(be_truthy)
end
it 'does not error when calling #package_type' do
expect((tracking_number.package_type.is_a?(String) or tracking_number.package_type.nil?)).to(be_truthy)
end
it 'does not error when calling #decode' do
decode = tracking_number.decode
expect(decode.is_a?(Hash)).to(eq(true))
end
end
end
end
context "invalid number" do
tracking_info[:test_numbers][:invalid].each do |invalid_number|
context invalid_number do
let(:tracking_number) { klass.new(invalid_number) }
it "does not validate" do
t = klass.new(invalid_number)
expect((!t.valid?)).to(be_truthy)
end
it "returns empty hash for #decode" do
t = klass.new(invalid_number)
decode = t.decode
expect(decode.is_a?(Hash)).to(eq(true))
end
end
end
end
end
end
| ruby | MIT | 802d8a55e506b65bb5c820ed4e6d259a29f3911e | 2026-01-04T17:45:13.109005Z | false |
jkeen/tracking_number_data | https://github.com/jkeen/tracking_number_data/blob/802d8a55e506b65bb5c820ed4e6d259a29f3911e/spec/format_spec.rb | spec/format_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'active_support'
require 'json'
require 'active_support/core_ext/hash'
require 'active_support/core_ext/string'
def courier_files
Dir.glob(File.expand_path(File.join(__dir__, '../couriers/*.json')))
end
def parsed_json_file(file)
JSON.parse(File.read(file)).deep_symbolize_keys!
end
def tracking_data
@tracking_data ||= begin
data = {}
courier_files.each do |file|
file_name = file.split('/').last
json = parsed_json_file(file)
json[:tracking_numbers].each do |info|
data[info[:id]] = info
end
end
data
end
end
courier_files.each do |file|
file_name = file.split('/').last
data = parsed_json_file(file)
describe file_name do
subject { file }
it 'has a file name without spaces' do
expect(file_name).to(match(/[a-z0-9]+\.json/))
end
it 'reads as valid and parseable json' do
expect(data).to(be_truthy)
end
it 'has a human readable name' do
expect(data[:name]).to_not match(/_/), 'should not have underscores'
end
it 'has a valid courier_code' do
expect(data[:courier_code]).to_not match(/\s/), 'should not have underscores'
expect(data[:courier_code]).to match(/^([a-z])([a-z][0-9])*/)
expect(!data[:courier_code].empty?).to(be_truthy)
end
end
data[:tracking_numbers].each do |info|
context info[:name] do
subject { info }
let(:pattern) { [subject[:regex]].flatten.join('') }
it 'includes a validation block, even if empty' do
expect(subject.keys.include?(:validation)).to(eq(true))
end
it 'includes a regex key as a string or an array of strings' do
expect(subject[:regex]).to(be_truthy)
expect((subject[:regex].is_a?(String) or subject[:regex].is_a?(Array))).to(be_truthy)
expect(subject[:regex].all? { |r| r.is_a?(String) }).to(be_truthy) if subject[:regex].is_a?(Array)
end
it 'has a pattern that compiles as regex' do
expect(Regexp.new(pattern)).to(be_truthy)
end
it 'has a pattern that can match spaces are double backslashed' do
expect(pattern).to(match(/\\s\*/))
end
it 'includes a <SerialNumber> character group' do
expect(pattern.include?('?<SerialNumber>')).to(eq(true))
end
it 'specifies validiation if a <CheckDigit> group is present' do
expect(info[:validation][:checksum][:name]).to(be_truthy) if pattern.include?('?<CheckDigit>')
end
it 'only includes character groups with agreed upon keys' do
regex = Regexp.new(pattern)
valid_keys = %w[SerialNumber CheckDigit ServiceType CountryCode DestinationZip PackageId
ShipperId SSID ShippingContainerType ApplicationIdentifier RoutingApplicationId SCNC GSN RoutingNumber OriginId]
regex.names.each { |name| expect(valid_keys.include?(name)).to(eq(true)) }
end
it 'if checksum is provided, it is never empty' do
expect((subject[:validation][:checksum].nil? or subject[:validation][:checksum][:name])).to(be_truthy)
end
it 'includes valid test numbers' do
uniques = subject[:test_numbers][:valid].uniq.size
expect((uniques > 1)).to(be_truthy)
end
it 'includes invalid test numbers' do
uniques = subject[:test_numbers][:invalid].uniq.size
expect((uniques > 0)).to(be_truthy)
end
it 'matches included valid numbers with pattern' do
regex = Regexp.new(pattern)
subject[:test_numbers][:valid].each do |valid|
expect(regex.match(valid)).to(be_truthy)
end
end
it 'matches included valid numbers with specified checksum algorithm' do
subject[:test_numbers][:valid].each do |valid|
if checksum_info = subject[:validation][:checksum]
expect_valid_checksum(valid, info)
end
end
end
it 'does not validate invalid numbers' do
regex = Regexp.new(pattern)
subject[:test_numbers][:invalid].each do |invalid|
passes_pattern_test = regex.match(invalid).present?
has_checksum = subject[:validation][:checksum]
has_additional_check = info[:validation][:additional]
results = []
results << passes_pattern_test
if has_checksum && passes_pattern_test
results << validate_with_checksum(invalid, info)
end
results << false if has_additional_check
expect((results.any? { |r| !r })).to(be_truthy)
end
end
it 'should include valid additional section' do
expect(info[:additional].is_a?(Array)).to(eq(true)) if info.keys.include?(:additional)
end
it 'should have an included regex group in each additional section' do
if info.keys.include?(:additional)
info[:additional].each do |section|
regex = Regexp.new(pattern)
expect(regex.names.include?(section[:regex_group_name])).to(eq(true))
end
end
end
it 'should have `matches` or `matches_regex` key in each lookup value' do
if info.keys.include?(:additional)
info[:additional].each do |section|
section[:lookup].each do |lookup|
expect((lookup[:matches] or lookup[:matches_regex])).to(be_truthy)
end
end
end
end
it 'should have a two way reference if the partner block is included' do
if info.keys.include?(:partners)
info[:partners].each do |partner|
expect(partner[:partner_id]).to(be_truthy)
expect(partner[:partner_type]).to(be_truthy)
partner_data = tracking_data[partner[:partner_id]]
expect(partner_data&.keys&.include?(:partners)).to(eq(true))
expect(partner_data[:partners]&.map { |p| p[:partner_id] }).to(include(info[:id]), "expected to find #{info[:id]} in #{partner_data[:partners]&.map { |p| p[:partner_id] }}")
end
end
end
end
end
end
| ruby | MIT | 802d8a55e506b65bb5c820ed4e6d259a29f3911e | 2026-01-04T17:45:13.109005Z | false |
jkeen/tracking_number_data | https://github.com/jkeen/tracking_number_data/blob/802d8a55e506b65bb5c820ed4e6d259a29f3911e/spec/collision_spec.rb | spec/collision_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'tracking_number'
def load_courier_data
TrackingNumber::Loader.load_tracking_number_data(File.expand_path(File.join(__dir__, '../couriers/')))
end
# Ideally each tracking numbers definition would only return one match, and that's usually the case
# when tracking numbers contain check digits, but some numbers like Amazon Logictics and Lasership don't
# do that, which increases the risk of false positives. These tests keep an eye on that.
describe do
load_courier_data.each do |data|
klass = data[:class]
courier_name = data[:name]
courier_code = data[:courier_code].to_sym
tracking_info = data[:info]
describe tracking_info[:name] do
valid_numbers = tracking_info[:test_numbers][:valid].flatten.compact
match_counts = valid_numbers.collect { |number| TrackingNumber.detect_all(number).size }.group_by { |count| count }.collect { |count, matches| [count, matches.size] }.to_h
if match_counts[1] == valid_numbers.size
it "matches one type of number" do
expect(true).to be_truthy
end
else
valid_numbers.each do |number|
detections = TrackingNumber.detect_all(number)
if detections.size > 1
xit "TODO: #{number} returned #{detections.collect { |a| a.class.to_s }.join(', ')} and it would be better if it didn't"
end
end
end
end
end
end
| ruby | MIT | 802d8a55e506b65bb5c820ed4e6d259a29f3911e | 2026-01-04T17:45:13.109005Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.