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 |
|---|---|---|---|---|---|---|---|---|
dobtco/filterer | https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/lib/generators/filterer/templates/filter.rb | lib/generators/filterer/templates/filter.rb | class <%= class_name %> < Filterer::Base
end
| ruby | MIT | 47b16e84651da4769d2932076c087d88fd9de167 | 2026-01-04T17:58:11.153161Z | false |
dobtco/filterer | https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/lib/filterer/active_record.rb | lib/filterer/active_record.rb | module Filterer
module ActiveRecord
extend ActiveSupport::Concern
class_methods do
def filter(params = {}, opts = {})
delegate_to_filterer(:filter, params, opts)
end
def chain(params = {}, opts = {})
delegate_to_filterer(:chain, params, opts)
end
private
def delegate_to_filterer(method, params, opts)
filterer_class(opts[:filterer_class]).
send(method, params, { starting_query: all }.merge(opts))
end
def filterer_class(override)
if override
override.constantize
else
const_get("#{name}Filterer")
end
rescue
fail "Looked for #{name}Filterer and couldn't find one!"
end
end
end
end
ActiveRecord::Base.send(:include, Filterer::ActiveRecord)
| ruby | MIT | 47b16e84651da4769d2932076c087d88fd9de167 | 2026-01-04T17:58:11.153161Z | false |
dobtco/filterer | https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/lib/filterer/version.rb | lib/filterer/version.rb | module Filterer
VERSION = '2.0.0'
end
| ruby | MIT | 47b16e84651da4769d2932076c087d88fd9de167 | 2026-01-04T17:58:11.153161Z | false |
dobtco/filterer | https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/lib/filterer/base.rb | lib/filterer/base.rb | module Filterer
class Base
attr_accessor :results,
:meta,
:sort,
:params,
:opts
class_attribute :sort_options
self.sort_options = []
class_attribute :per_page
self.per_page = 20
class_attribute :allow_per_page_override
self.allow_per_page_override = false
class_attribute :per_page_max
self.per_page_max = 1000
class << self
# Macro for adding sort options
def sort_option(key, string_or_proc = nil, opts = {})
if string_or_proc.is_a?(Hash)
opts, string_or_proc = string_or_proc.clone, nil
end
if !string_or_proc
if key.is_a?(String)
string_or_proc = key
else
raise 'Please provide a query string or a proc.'
end
end
if key.is_a?(Regexp) && opts[:default]
raise "Default sort option can't have a Regexp key."
end
if string_or_proc.is_a?(Proc) && opts[:tiebreaker]
raise "Tiebreaker can't be a proc."
end
self.sort_options += [{
key: key,
string_or_proc: string_or_proc,
opts: opts
}]
end
# Public API
# @return [ActiveRecord::Association]
def filter(params = {}, opts = {})
new(params, opts).results
end
# @return [ActiveRecord::Association]
def filter_without_pagination(params = {}, opts = {})
new(params, opts.merge(
skip_pagination: true
)).results
end
# @return [ActiveRecord::Association]
def chain(params = {}, opts = {})
new(params, opts.merge(
skip_ordering: true,
skip_pagination: true
)).results
end
end
def initialize(params = {}, opts = {})
self.opts = opts
self.params = defaults.merge(parse_strong_parameters(params)).
with_indifferent_access
self.results = opts[:starting_query] || starting_query
self.results = apply_default_filters || results
add_params_to_query
self.results = ordered_results unless opts[:skip_ordering]
paginate_results unless opts[:skip_pagination]
extend_active_record_relation
end
def defaults
{}
end
def starting_query
raise 'You must override this method!'
end
def direction
params[:direction].try(:downcase) == 'desc' ? 'desc' : 'asc'
end
# @return [String] the key for the applied sort option.
def sort
@sort ||= begin
if params[:sort] && find_sort_option_from_param(params[:sort])
params[:sort]
else
default_sort_option[:key]
end
end
end
private
def paginate_results
if per_page && paginator
send("paginate_results_with_#{paginator}")
end
end
def paginator
if defined?(Kaminari)
:kaminari
elsif defined?(WillPaginate)
:will_paginate
end
end
def paginate_results_with_kaminari
self.results = results.page(current_page).per(per_page)
end
def paginate_results_with_will_paginate
self.results = results.paginate(page: current_page, per_page: per_page)
end
def apply_default_filters
results
end
def add_params_to_query
present_params.each do |k, v|
method_name = "param_#{k}"
if respond_to?(method_name)
self.results = send(method_name, v) || results
end
end
end
def present_params
params.select do |_k, v|
v.present?
end
end
def ordered_results
if sort_option && sort_option[:string_or_proc].is_a?(String)
order_by_sort_option(sort_option)
elsif sort_option && sort_option[:string_or_proc].is_a?(Proc)
order_by_sort_proc
else
order_by_sort_option(default_sort_option)
end
end
def per_page
if self.class.allow_per_page_override && params[:per_page].present?
[params[:per_page].to_i, per_page_max].min
else
self.class.per_page
end
end
def current_page
[params[:page].to_i, 1].max
end
def sort_option
@sort_option ||= find_sort_option_from_param(sort)
end
# @param x [String]
# @return [Hash] sort_option
def find_sort_option_from_param(x)
self.class.sort_options.detect do |sort_option|
if sort_option[:key].is_a?(Regexp)
x.match(sort_option[:key])
else # String
x == sort_option[:key]
end
end
end
def order_by_sort_proc
if (sort_string = sort_proc_to_string(sort_option))
order_by_sort_option(sort_option.merge(
string_or_proc: sort_string
))
else
order_by_sort_option(filterer_default_sort_option)
end
end
def order_by_sort_option(opt)
results.order %{
#{opt[:string_or_proc]}
#{direction}
#{opt[:opts][:nulls_last] ? 'NULLS LAST' : ''}
#{tiebreaker_sort_string ? ', ' + tiebreaker_sort_string : ''}
}.squish
end
def sort_proc_to_string(opt)
sort_key = opt[:key]
matches = sort_key.is_a?(Regexp) && params[:sort].match(sort_key)
instance_exec matches, &opt[:string_or_proc]
end
def default_sort_option
self.class.sort_options.detect do |sort_option|
sort_option[:opts][:default]
end || filterer_default_sort_option
end
def filterer_default_sort_option
{
key: 'default',
string_or_proc: "#{results.model.table_name}.id",
opts: {}
}
end
def tiebreaker_sort_string
self.class.sort_options.detect do |sort_option|
sort_option[:opts][:tiebreaker]
end.try(:[], :string_or_proc)
end
def extend_active_record_relation
results.instance_variable_set(:@filterer, self)
results.extending! do
def filterer
@filterer
end
end
end
def parse_strong_parameters(params)
params.try(:to_unsafe_h) || params
end
end
end
| ruby | MIT | 47b16e84651da4769d2932076c087d88fd9de167 | 2026-01-04T17:58:11.153161Z | false |
dobtco/filterer | https://github.com/dobtco/filterer/blob/47b16e84651da4769d2932076c087d88fd9de167/lib/filterer/engine.rb | lib/filterer/engine.rb | module Filterer
class Engine < ::Rails::Engine
isolate_namespace Filterer
ActiveSupport.on_load(:active_record) do
require 'filterer/active_record'
end
end
end
| ruby | MIT | 47b16e84651da4769d2932076c087d88fd9de167 | 2026-01-04T17:58:11.153161Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/res/scaffold/simple/main.rb | res/scaffold/simple/main.rb | require 'goby'
include Goby
require_relative 'map/farm.rb'
# Set this to true in order to use BGM.
Music::set_playback(false)
# By default, we've included no music files.
# The Music module also includes a function
# to change the music-playing program.
# Clear the terminal.
system("clear")
# Allow the player to load an existing game.
if File.exists?("player.yaml")
print "Load the saved file?: "
input = player_input
if input.is_positive?
player = load_game("player.yaml")
end
end
# No load? Create a new player.
if player.nil?
# A Location specifies the Map and (y,x) coordinates of a Player.
home = Location.new(Farm.new, C[1, 1])
# Use the Player constructor to set the
# location, stats, gold, inventory, and more.
player = Player.new(location: home)
end
run_driver(player)
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/res/scaffold/simple/farm.rb | res/scaffold/simple/farm.rb | # This is an example of how to create a Map. You can
# define the name, where to respawn, and the 2D display of
# the Map - each point is referred to as a Tile.
class Farm < Map
def initialize
super(name: "Farm")
# Define the main tiles on this map.
grass = Tile.new(description: "You are standing on some grass.")
# Fill the map with "grass."
@tiles = Array.new(9) { Array.new(5) { grass.clone } }
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/spec_helper.rb | spec/spec_helper.rb | # This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# The `.rspec` file also contains a few flags that are not defaults but that
# users commonly want.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
require 'coveralls'
Coveralls.wear!
require 'goby'
# Set variable to know when testing.
# Also has boolean value true.
ENV['TEST'] = 'rspec'
# Credit for "discovering" (?) RSpec input:
# https://gist.github.com/nu7hatch/631329
module Helpers
# Replace standard input with faked one StringIO.
def __stdin(*args)
begin
$stdin = StringIO.new
$stdin.puts(args.shift) until args.empty?
$stdin.rewind
yield
ensure
$stdin = STDIN
end
end
end
RSpec.configure do |config|
include Goby
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# Suppress output & error by redirecting to text files.
original_stderr = $stderr
original_stdout = $stdout
config.before(:all) do
# Redirect stderr and stdout to /dev/null
$stderr = File.open(File::NULL, "w")
$stdout = File.open(File::NULL, "w")
end
config.after(:all) do
$stderr = original_stderr
$stdout = original_stdout
end
# Allow RSpec tests to access this module.
config.include(Helpers)
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = true
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = 'doc'
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/music_spec.rb | spec/goby/music_spec.rb | require 'goby'
RSpec.describe Music do
include Music
before(:all) do
_relativePATH = File.expand_path File.dirname(__FILE__)
@music = _relativePATH + "/bach.mid"
end
# If you do not have BGM support and would like to run the
# test suite locally, replace 'it' with 'xit'.
it "should play and stop the music" do
set_playback(true)
set_program("timidity")
play_music(@music)
sleep(0.01)
stop_music
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/world_command_spec.rb | spec/goby/world_command_spec.rb | require 'goby'
RSpec.describe do
include WorldCommand
let!(:map) { Map.new(tiles: [ [ Tile.new,
Tile.new(events: [NPC.new]),
Tile.new(events: [Event.new(visible: false)]) ],
[ Tile.new(events: [Shop.new, NPC.new]),
Tile.new(events: [Event.new(visible: false), Shop.new, NPC.new]) ] ] ) }
let!(:player) { Player.new(stats: { max_hp: 10, hp: 3 },
inventory: [ C[Food.new(name: "Banana", recovers: 5), 1],
C[Food.new(name: "Onion", disposable: false), 1],
C[Item.new(name: "Big Book of Stuff"), 1],
C[Helmet.new, 1] ],
location: Location.new(map, C[0, 0])) }
context "display default commands" do
it "should print the default commands" do
expect { display_default_commands }.to output(
WorldCommand::DEFAULT_COMMANDS).to_stdout
end
end
context "display special commands" do
it "should print nothing when no special commands are available" do
expect { display_special_commands(player) }.to_not output.to_stdout
end
it "should print nothing when the only event is non-visible" do
player.move_right
player.move_right
expect { display_special_commands(player) }.to_not output.to_stdout
end
it "should print one commmand for one event" do
player.move_right
expect { display_special_commands(player) }.to output(
WorldCommand::SPECIAL_COMMANDS_HEADER + "talk\n\n").to_stdout
end
it "should print two 'separated' commands for two events" do
player.move_down
expect { display_special_commands(player) }.to output(
WorldCommand::SPECIAL_COMMANDS_HEADER + "shop, talk\n\n").to_stdout
end
it "should ignore the non-visible event" do
player.move_down
player.move_right
expect { display_special_commands(player) }.to output(
WorldCommand::SPECIAL_COMMANDS_HEADER + "shop, talk\n\n").to_stdout
end
end
context "help" do
it "should print only the default commands when no special commands are available" do
expect { help(player) }.to output(WorldCommand::DEFAULT_COMMANDS).to_stdout
end
it "should print the default commands and the special commands" do
player.move_right
expect { help(player) }.to output(
WorldCommand::DEFAULT_COMMANDS + WorldCommand::SPECIAL_COMMANDS_HEADER +
"talk\n\n").to_stdout
end
end
# TODO: tests for describe_tile
context "describe tile" do
end
# TODO: test the input of all possible commands.
# TODO: test use/drop/equip/unequip multi-word items.
context "interpret command" do
context "lowercase" do
it "should correctly move the player around" do
interpret_command("s", player)
expect(player.location.coords).to eq C[1, 0]
interpret_command("d", player)
expect(player.location.coords).to eq C[1, 1]
interpret_command("w", player)
expect(player.location.coords).to eq C[0, 1]
interpret_command("a", player)
expect(player.location.coords).to eq C[0, 0]
end
it "should display the help text" do
expect { interpret_command("help", player) }.to output(
WorldCommand::DEFAULT_COMMANDS).to_stdout
end
it "should print the map" do
interpret_command("map", player)
# TODO: expect the map output.
end
it "should print the inventory" do
interpret_command("inv", player)
# TODO: expect the inventory output.
end
it "should print the status" do
interpret_command("status", player)
# TODO: expect the status output.
end
it "should save the game" do
# Rename the original file.
random_string = "n483oR38Avdis3"
File.rename("player.yaml", random_string) if File.exists?("player.yaml")
interpret_command("save", player)
expect(File.exists?("player.yaml")).to be true
File.delete("player.yaml")
# Return the original data to the file.
File.rename(random_string, "player.yaml") if File.exists?(random_string)
end
it "should drop a disposable item" do
interpret_command("drop banana", player)
expect(player.has_item("Banana")).to be_nil
end
it "should drop the item composed of multiple words" do
interpret_command("drop big book of stuff", player)
expect(player.has_item("Big Book of Stuff")).to be_nil
end
it "should not drop a non-disposable item" do
interpret_command("drop onion", player)
expect(player.has_item("Onion")).to eq 1
end
it "should print error text for dropping nonexistent item" do
expect { interpret_command("drop orange", player) }.to output(
WorldCommand::NO_ITEM_DROP_ERROR).to_stdout
end
it "should not output anything on quit" do
expect { interpret_command("quit", @player) }.to_not output.to_stdout
end
it "should equip and unequip the specified item" do
interpret_command("equip helmet", player)
expect(player.has_item("Helmet")).to be_nil
expect(player.outfit[:helmet]).to eq Helmet.new
interpret_command("unequip helmet", player)
expect(player.has_item("Helmet")).not_to be_nil
expect(player.outfit[:helmet]).to be_nil
end
it "should use the specified item" do
interpret_command("use banana", player)
expect(player.has_item("Banana")).to be_nil
expect(player.stats[:hp]).to eq 8
end
it "should print error text for using nonexistent item" do
expect { interpret_command("use apple", player) }.to output(
Entity::NO_SUCH_ITEM_ERROR).to_stdout
end
it "should run the event on the tile" do
player.move_right
expect { interpret_command("talk\n", player) }.to output(
"NPC: Hello!\n\n").to_stdout
end
end
context "case-insensitive" do
it "should correctly move the player around" do
interpret_command("S", player)
expect(player.location.coords).to eq C[1, 0]
interpret_command("D", player)
expect(player.location.coords).to eq C[1, 1]
interpret_command("W", player)
expect(player.location.coords).to eq C[0, 1]
interpret_command("A", player)
expect(player.location.coords).to eq C[0, 0]
end
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/driver_spec.rb | spec/goby/driver_spec.rb | require 'goby'
RSpec.describe do
let(:player) { Player.new }
# Success for each of these tests mean
# that run_driver exits without error.
context "run driver" do
it "should exit on 'quit'" do
__stdin("quit\n") { run_driver(player) }
end
it "should accept various commands in a looping fashion" do
__stdin("w\ne\ns\nn\nquit\n") { run_driver(player) }
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/extension_spec.rb | spec/goby/extension_spec.rb | require 'goby'
RSpec.describe Array do
context "nonempty?" do
it "returns true when the array contains elements" do
expect([1].nonempty?).to be true
expect(["Hello"].nonempty?).to be true
expect([false, false].nonempty?).to be true
end
it "returns false when the array contains no elements" do
expect([].nonempty?).to be false
expect(Array.new.nonempty?).to be false
end
end
end
RSpec.describe Integer do
context "is positive?" do
it "returns true for an integer value that is greater than zero" do
expect(0.positive?).to be false
expect(1.positive?).to be true
expect(-1.positive?).to be false
end
end
context "is nonpositive?" do
it "returns true for an integer value less than or equal to zero" do
expect(0.nonpositive?).to be true
expect(1.nonpositive?).to be false
expect(-1.nonpositive?).to be true
end
end
context "is negative?" do
it "returns true for an integer value less than zero" do
expect(0.negative?).to be false
expect(1.negative?).to be false
expect(-1.negative?).to be true
end
end
context "is nonnegative?" do
it "returns true for an integer value greater than or equal to zero" do
expect(0.nonnegative?).to be true
expect(1.nonnegative?).to be true
expect(-1.nonnegative?).to be false
end
end
end
RSpec.describe String do
context "is positive?" do
it "returns true for a positive string" do
expect("y".is_positive?).to be true
expect("yes".is_positive?).to be true
expect("yeah".is_positive?).to be true
expect("ok".is_positive?).to be true
end
it "returns false for a non-positive string" do
expect("maybe".is_positive?).to be false
expect("whatever".is_positive?).to be false
expect("no".is_positive?).to be false
expect("nah".is_positive?).to be false
end
end
context "is negative?" do
it "returns true for a negative string" do
expect("n".is_negative?).to be true
expect("no".is_negative?).to be true
expect("nah".is_negative?).to be true
expect("nope".is_negative?).to be true
end
it "returns false for a non-negative string" do
expect("maybe".is_negative?).to be false
expect("whatever".is_negative?).to be false
expect("sure".is_negative?).to be false
expect("okey dokey".is_negative?).to be false
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/scaffold_spec.rb | spec/goby/scaffold_spec.rb | require 'goby'
require 'fileutils'
RSpec.describe Scaffold do
context "simple" do
it "should create the appropriate directories & files" do
project = "goby-project"
Scaffold::simple project
# Ensure all of the directories exist.
expect(Dir.exists? "#{project}").to be true
[ '', 'battle', 'entity',
'event', 'item', 'map' ].each do |dir|
expect(Dir.exist? "#{project}/src/#{dir}").to be true
end
# Ensure all of the files exist.
[ '.gitignore', 'src/main.rb', 'src/map/farm.rb' ].each do |file|
expect(File.exist? "#{project}/#{file}").to be true
end
# Clean up the scaffolding.
FileUtils.remove_dir project
end
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/util_spec.rb | spec/goby/util_spec.rb | require 'goby'
RSpec.describe do
context "couple" do
it "should correctly initialize the couple" do
couple = C["Apple", 1]
expect(couple.first).to eq "Apple"
expect(couple.second).to eq 1
end
it "should equate two objects based on both 'first' and 'second'" do
couple1 = C["Apple", 1]
couple2 = C["Apple", 1]
expect(couple1).to eq couple2
end
it "should not equate two objects with a different 'first'" do
couple1 = C["Apple", 1]
couple2 = C["Banana", 1]
expect(couple1).to_not eq couple2
end
it "should not equate two objects with a different 'second'" do
couple1 = C["Apple", 1]
couple2 = C["Apple", 2]
expect(couple1).to_not eq couple2
end
it "should not equate two objects with both different 'first' and 'second'" do
couple1 = C["Apple", 1]
couple2 = C["Banana", 2]
expect(couple1).to_not eq couple2
end
end
context "location" do
it "should correctly initialize the location" do
map = Map.new(name: "Test Map")
location = Location.new(map, C[0, 0])
expect(location.map.name).to eq "Test Map"
expect(location.coords).to eq C[0, 0]
end
end
context "player input" do
before (:each) { Readline::HISTORY.pop until Readline::HISTORY.size <= 0 }
it "should return the same string as given (without newline)" do
__stdin("kick\n") do
input = player_input
expect(input).to eq "kick"
end
end
it "should correctly add distinct commands to the history" do
__stdin("kick\n") { player_input }
__stdin("use\n") { player_input }
__stdin("inv\n") { player_input }
expect(Readline::HISTORY.size).to eq 3
expect(Readline::HISTORY[-1]).to eq "inv"
end
it "should not add repeated commands to the history" do
__stdin("kick\n") { player_input }
__stdin("kick\n") { player_input }
__stdin("inv\n") { player_input }
__stdin("kick\n") { player_input }
expect(Readline::HISTORY.size).to eq 3
expect(Readline::HISTORY[0]).to eq "kick"
expect(Readline::HISTORY[1]).to eq "inv"
end
it "should not add single-character commands to the history" do
__stdin("w\n") { player_input }
__stdin("a\n") { player_input }
__stdin("s\n") { player_input }
__stdin("d\n") { player_input }
expect(Readline::HISTORY.size).to eq 0
end
end
context "type" do
it "should print the given message" do
expect { type("HELLO") }.to output("HELLO").to_stdout
end
end
context "save game" do
it "should create the appropriate file" do
player = Player.new
save_game(player, "test.yaml")
expect(File.file?("test.yaml")).to eq true
File.delete("test.yaml")
end
end
context "load game" do
it "should load the player's information" do
player1 = Player.new(name: "Nicholas",
stats: { max_hp: 5, hp: 3 })
save_game(player1, "test.yaml")
player2 = load_game("test.yaml")
expect(player2.name).to eq "Nicholas"
expect(player2.stats[:max_hp]).to eq 5
expect(player2.stats[:hp]).to eq 3
File.delete("test.yaml")
end
it "should return nil if no such file exists" do
player = load_game("test.yaml")
expect(player).to be_nil
end
end
context "increasing player_input versatility" do
context "handling lowercase functionality" do
it "should maintain case of input if lowercase is marked as false" do
inputs = ["KicK\n", "uSe\n", "INV\n"]
Readline::HISTORY.pop until Readline::HISTORY.size <= 0
inputs.each do |i|
__stdin(i) { player_input lowercase: false }
end
expect(Readline::HISTORY.size).to eq 3
i = 0
expect(Readline::HISTORY.all? do |input|
input == inputs[i]
i += 1
end).to eq true
end
it "returns lowercase input as default" do
inputs = ["KicK\n", "uSe\n", "INV\n"]
Readline::HISTORY.pop until Readline::HISTORY.size <= 0
inputs.each do |i|
__stdin(i) { player_input }
end
expect(Readline::HISTORY.size).to eq 3
i = 0
expect(Readline::HISTORY.all? do |input|
input == inputs[i].downcase
i += 1
end).to eq true
end
end
context "output is determined by given params" do
it "prints an empty string and extra space by default" do
expect{ __stdin('test') {player_input} }.to output("\n").to_stdout
end
it "prints the correct prompt when given an argument" do
expect{ __stdin('test') {player_input prompt: '> '} }.to output("> \n").to_stdout
end
it "does not print the newline if doublespace is marked as false" do
expect{ __stdin('test') {player_input doublespace: false} }.to output('').to_stdout
end
it "prints custom prompt and doesn't print the newline if doublespace is marked as false" do
expect{ __stdin('test') {player_input doublespace: false, prompt: 'testing: '} }.to output("testing: ").to_stdout
end
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/entity/player_spec.rb | spec/goby/entity/player_spec.rb | require 'goby'
RSpec.describe Player do
# Constructs a map in the shape of a plus sign.
let!(:map) { Map.new(tiles: [[Tile.new(passable: false), Tile.new, Tile.new(passable: false)],
[Tile.new, Tile.new, Tile.new(monsters: [Monster.new(battle_commands: [Attack.new(success_rate: 0)])])],
[Tile.new(passable: false), Tile.new, Tile.new(passable: false)]]) }
let!(:center) { C[1, 1] }
let!(:passable) { Tile::DEFAULT_PASSABLE }
let!(:impassable) { Tile::DEFAULT_IMPASSABLE }
let!(:dude) { Player.new(stats: {attack: 10, agility: 10000, map_hp: 2000}, gold: 10,
battle_commands: [Attack.new(strength: 20), Escape.new, Use.new],
location: Location.new(map, center)) }
let!(:slime) { Monster.new(battle_commands: [Attack.new(success_rate: 0)],
gold: 5000, treasures: [C[Item.new, 1]]) }
let!(:newb) { Player.new(battle_commands: [Attack.new(success_rate: 0)],
gold: 50, location: Location.new(map, center),
respawn_location: Location.new(map, C[2, 1])) }
let!(:dragon) { Monster.new(stats: {attack: 50, agility: 10000},
battle_commands: [Attack.new(strength: 50)]) }
let!(:chest_map) { Map.new(name: "Chest Map",
tiles: [[Tile.new(events: [Chest.new(gold: 5)]), Tile.new(events: [Chest.new(gold: 5)])]]) }
context "constructor" do
it "has the correct default parameters" do
player = Player.new
expect(player.name).to eq "Player"
expect(player.stats[:max_hp]).to eq 1
expect(player.stats[:hp]).to eq 1
expect(player.stats[:attack]).to eq 1
expect(player.stats[:defense]).to eq 1
expect(player.stats[:agility]).to eq 1
expect(player.inventory).to eq Array.new
expect(player.gold).to eq 0
expect(player.outfit).to eq Hash.new
expect(player.battle_commands).to eq Array.new
expect(player.location.map).to eq Player::DEFAULT_MAP
expect(player.location.coords).to eq Player::DEFAULT_COORDS
expect(player.respawn_location.map).to eq Player::DEFAULT_MAP
expect(player.respawn_location.coords).to eq Player::DEFAULT_COORDS
end
it "correctly assigns custom parameters" do
hero = Player.new(name: "Hero",
stats: {max_hp: 50,
hp: 35,
attack: 12,
defense: 4,
agility: 9},
inventory: [C[Item.new, 1]],
gold: 10,
outfit: {weapon: Weapon.new(
attack: Attack.new,
stat_change: {attack: 3, defense: 1}),
helmet: Helmet.new(
stat_change: {attack: 1, defense: 5})},
battle_commands: [
BattleCommand.new(name: "Yell"),
BattleCommand.new(name: "Run")
],
location: Location.new(map, C[1, 1]),
respawn_location: Location.new(map, C[1, 2]))
expect(hero.name).to eq "Hero"
expect(hero.stats[:max_hp]).to eq 50
expect(hero.stats[:hp]).to eq 35
expect(hero.stats[:attack]).to eq 16
expect(hero.stats[:defense]).to eq 10
expect(hero.stats[:agility]).to eq 9
expect(hero.inventory).to eq [C[Item.new, 1]]
expect(hero.gold).to eq 10
expect(hero.outfit[:weapon]).to eq Weapon.new
expect(hero.outfit[:helmet]).to eq Helmet.new
expect(hero.battle_commands).to eq [
Attack.new,
BattleCommand.new(name: "Run"),
BattleCommand.new(name: "Yell")
]
expect(hero.location.map).to eq map
expect(hero.location.coords).to eq C[1, 1]
expect(hero.respawn_location.map).to eq map
expect(hero.respawn_location.coords).to eq C[1, 2]
end
it "sets respawn to start location for no respawn_location" do
player = Player.new(location: Location.new(map, C[1, 1]))
expect(player.respawn_location.map).to eq map
expect(player.respawn_location.coords).to eq C[1, 1]
end
context "places the player in the default map & location" do
it "receives the nil map" do
player = Player.new(location: Location.new(nil, C[2, 4]))
expect(player.location.map).to eq Player::DEFAULT_MAP
expect(player.location.coords).to eq Player::DEFAULT_COORDS
end
it "receives nil coordinates" do
player = Player.new(location: Location.new(Map.new, nil))
expect(player.location.map).to eq Player::DEFAULT_MAP
expect(player.location.coords).to eq Player::DEFAULT_COORDS
end
it "receives an out-of-bounds location" do
player = Player.new(location: Location.new(Map.new, C[0, 1]))
expect(player.location.map).to eq Player::DEFAULT_MAP
expect(player.location.coords).to eq Player::DEFAULT_COORDS
end
it "receives an impassable location" do
player = Player.new(location: Location.new(
Map.new(tiles: [[Tile.new(passable: false)]]), C[0, 0]))
expect(player.location.map).to eq Player::DEFAULT_MAP
expect(player.location.coords).to eq Player::DEFAULT_COORDS
end
end
end
context "choose attack" do
it "should choose the correct attack based on the input" do
charge = BattleCommand.new(name: "Charge")
zap = BattleCommand.new(name: "Zap")
player = Player.new(battle_commands: [charge, zap])
# RSpec input example. Also see spec_helper.rb for __stdin method.
__stdin("kick\n", "zap\n") do
expect(player.choose_attack.name).to eq "Zap"
end
end
end
context "choose item and on whom" do
let!(:banana) { Item.new(name: "Banana") }
let!(:axe) { Item.new(name: "Axe") }
let!(:entity) { Player.new(inventory: [C[banana, 1],
C[axe, 3]]) }
let!(:enemy) { Entity.new(name: "Enemy") }
it "should return correct values based on the input" do
# RSpec input example. Also see spec_helper.rb for __stdin method.
__stdin("goulash\n", "axe\n", "bill\n", "enemy\n") do
pair = entity.choose_item_and_on_whom(enemy)
expect(pair.first.name).to eq "Axe"
expect(pair.second.name).to eq "Enemy"
end
end
context "should return nil on appropriate input" do
it "for item" do
# RSpec input example. Also see spec_helper.rb for __stdin method.
__stdin("goulash\n", "pass\n") do
pair = entity.choose_item_and_on_whom(enemy)
expect(pair).to be_nil
end
end
it "for whom" do
# RSpec input example. Also see spec_helper.rb for __stdin method.
__stdin("banana\n", "bill\n", "pass\n") do
pair = entity.choose_item_and_on_whom(enemy)
expect(pair).to be_nil
end
end
end
end
context "move to" do
it "correctly moves the player to a passable tile" do
dude.move_to(Location.new(dude.location.map, C[2, 1]))
expect(dude.location.map).to eq map
expect(dude.location.coords).to eq C[2, 1]
end
it "prevents the player from moving on an impassable tile" do
dude.move_to(Location.new(dude.location.map, C[2, 2]))
expect(dude.location.map).to eq map
expect(dude.location.coords).to eq center
end
it "prevents the player from moving on a nonexistent tile" do
dude.move_to(Location.new(dude.location.map, C[3, 3]))
expect(dude.location.map).to eq map
expect(dude.location.coords).to eq center
end
it "saves the information from previous maps" do
dude.move_to(Location.new(chest_map, C[0, 0]))
interpret_command("open", dude)
expect(dude.gold).to eq 15
dude.move_to(Location.new(Map.new, C[0, 0]))
dude.move_to(Location.new(Map.new(name: "Chest Map"), C[0, 0]))
interpret_command("open", dude)
expect(dude.gold).to eq 15
dude.move_right
interpret_command("open", dude)
expect(dude.gold).to eq 20
end
end
context "move up" do
it "correctly moves the player to a passable tile" do
dude.move_up
expect(dude.location.map).to eq map
expect(dude.location.coords).to eq C[0, 1]
end
it "prevents the player from moving on a nonexistent tile" do
dude.move_up; dude.move_up
expect(dude.location.map).to eq map
expect(dude.location.coords).to eq C[0, 1]
end
end
context "move right" do
it "correctly moves the player to a passable tile" do
20.times do
__stdin("Attack\n", "\n") do
dude.move_right
expect(dude.location.map).to eq map
expect(dude.location.coords).to eq C[1, 2]
dude.move_left
expect(dude.location.map).to eq map
expect(dude.location.coords).to eq C[1, 1]
end
end
end
it "prevents the player from moving on a nonexistent tile" do
__stdin("Attack\n", "\n") do
dude.move_right; dude.move_right
expect(dude.location.map).to eq map
expect(dude.location.coords).to eq C[1, 2]
end
end
end
context "move down" do
it "correctly moves the player to a passable tile" do
dude.move_down
expect(dude.location.map).to eq map
expect(dude.location.coords).to eq C[2, 1]
end
it "prevents the player from moving on a nonexistent tile" do
dude.move_down; dude.move_down
expect(dude.location.map).to eq map
expect(dude.location.coords).to eq C[2, 1]
end
end
context "move left" do
it "correctly moves the player to a passable tile" do
dude.move_left
expect(dude.location.map).to eq map
expect(dude.location.coords).to eq C[1, 0]
end
it "prevents the player from moving on a nonexistent tile" do
dude.move_left; dude.move_left
expect(dude.location.map).to eq map
expect(dude.location.coords).to eq C[1, 0]
end
end
context "update map" do
let!(:line_map) { Map.new(tiles: [[Tile.new, Tile.new, Tile.new, Tile.new]]) }
let!(:player) { Player.new(location: Location.new(line_map, C[0, 0])) }
it "uses default argument to update tiles" do
player.update_map
expect(line_map.tiles[0][3].seen).to eq false
end
it "uses given argument to update tiles" do
player.update_map(Location.new(player.location.map, C[0, 2]))
expect(line_map.tiles[0][3].seen).to eq true
end
end
context "print map" do
it "should display as appropriate" do
edge_row = "#{impassable} #{passable} #{impassable} \n"
middle_row = "#{passable} ¶ #{passable} \n"
expect { dude.print_map }.to output(
" Map\n\n"\
" #{edge_row}"\
" #{middle_row}"\
" #{edge_row}"\
"\n"\
" ¶ - #{dude.name}'s\n"\
" location\n\n"
).to_stdout
end
end
context "print minimap" do
it "should display as appropriate" do
edge_row = "#{impassable} #{passable} #{impassable} \n"
middle_row = "#{passable} ¶ #{passable} \n"
expect { dude.print_minimap }.to output(
"\n"\
" #{edge_row}"\
" #{middle_row}"\
" #{edge_row}"\
" \n"
).to_stdout
end
end
context "print tile" do
it "should display the marker on the player's location" do
expect { dude.print_tile(dude.location.coords) }.to output("¶ ").to_stdout
end
it "should display the graphic of the tile elsewhere" do
expect { dude.print_tile(C[0, 0]) }.to output(
"#{impassable} "
).to_stdout
expect { dude.print_tile(C[0, 1]) }.to output(
"#{passable} "
).to_stdout
end
end
# Fighter specific specs
context "fighter" do
it "should be a fighter" do
expect(dude.class.included_modules.include?(Fighter)).to be true
end
end
context "battle" do
it "should allow the player to win in this example" do
__stdin("attack\n", "\n") do
dude.battle(slime)
end
expect(dude.inventory.size).to eq 1
end
it "should allow the player to escape in this example" do
# Could theoretically fail, but with very low probability.
__stdin("escape\nescape\nescape\n") do
dude.battle(slime)
expect(dude.gold).to eq 10
end
end
it "should allow the monster to win in this example" do
__stdin("attack\n") do
newb.battle(dragon)
end
# Newb should die and go to respawn location.
expect(newb.gold).to eq 25
expect(newb.location.coords).to eq C[2, 1]
end
it "should allow the stronger player to win as the attacker" do
__stdin("attack\nattack\n", "\n") do
dude.battle(newb)
end
# Weaker Player should die and go to respawn location.
expect(newb.gold).to eq 25
expect(newb.location.coords).to eq C[2, 1]
# Stronger Player should get weaker Players gold
expect(dude.gold).to eq (35)
end
it "should allow the stronger player to win as the defender" do
__stdin("attack\nattack\n", "\n") do
newb.battle(dude)
end
# Weaker Player should die and go to respawn location.
expect(newb.gold).to eq 25
expect(newb.location.coords).to eq C[2, 1]
# Stronger Player should get weaker Players gold
expect(dude.gold).to eq (35)
end
end
context "die" do
it "moves the player back to his/her respawn location" do
newb.move_left
expect(newb.location.coords).to eq C[1, 0]
newb.die
expect(newb.location.map).to eq map
expect(newb.location.coords).to eq C[2, 1]
end
it "recovers the player's HP to max" do
newb.set_stats(hp: 0)
newb.die
expect(newb.stats[:hp]).to eq newb.stats[:max_hp]
end
end
context "sample gold" do
it "reduces the player's gold by half" do
dude.set_gold(10)
dude.sample_gold
expect(dude.gold).to eq 5
end
it "returns the amount of gold the player has lost" do
dude.set_gold(10)
expect(dude.sample_gold).to eq 5
end
end
context "sample treasures" do
it "returns nil to indicate the player has lost no treasures" do
expect(dude.sample_treasures).to be_nil
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/entity/fighter_spec.rb | spec/goby/entity/fighter_spec.rb | require 'goby'
RSpec.describe Fighter do
let!(:empty_fighter) { Class.new { extend Fighter } }
let(:fighter_class) {
Class.new(Entity) do
include Fighter
def initialize(name: "Fighter", stats: {}, inventory: [], gold: 0, battle_commands: [], outfit: {})
super(name: name, stats: stats, inventory: inventory, gold: gold, outfit: outfit)
add_battle_commands(battle_commands)
end
end
}
let(:fighter) { fighter_class.new }
context "fighter" do
it "is a fighter" do
expect(fighter.class.included_modules.include?(Fighter)).to be true
end
end
context "placeholder methods" do
it "forces :die to be implemented" do
expect { empty_fighter.die }.to raise_error(NotImplementedError, 'A Fighter must know how to die.')
end
it "forces :handle_victory to be implemented" do
expect { empty_fighter.handle_victory(fighter) }.to raise_error(NotImplementedError, 'A Fighter must know how to handle victory.')
end
it "forces :sample_treasures to be implemented" do
expect { empty_fighter.sample_treasures }.to raise_error(NotImplementedError, 'A Fighter must know whether it returns treasure or not after losing a battle.')
end
it "forces :sample_gold to be implemented" do
expect { empty_fighter.sample_gold }.to raise_error(NotImplementedError, 'A Fighter must return some gold after losing a battle.')
end
end
context "add battle command" do
it "properly adds the command in a trivial case" do
fighter.add_battle_command(BattleCommand.new)
expect(fighter.battle_commands.length).to eq 1
expect(fighter.battle_commands).to eq [BattleCommand.new]
end
it "maintains the sorted invariant for a more complex case" do
fighter.add_battle_command(BattleCommand.new(name: "Kick"))
fighter.add_battle_command(BattleCommand.new(name: "Chop"))
fighter.add_battle_command(BattleCommand.new(name: "Grab"))
expect(fighter.battle_commands.length).to eq 3
expect(fighter.battle_commands).to eq [
BattleCommand.new(name: "Chop"),
BattleCommand.new(name: "Grab"),
BattleCommand.new(name: "Kick")]
end
end
context "battle" do
it "raises an error when starting a battle against a non-Fighter Entity" do
expect {empty_fighter.battle(Class.new)}.to raise_error(Fighter::UnfightableException,
"You can't start a battle with an Entity of type Class as it doesn't implement the Fighter module")
end
end
context "choose attack" do
it "randomly selects one of the available commands" do
kick = BattleCommand.new(name: "Kick")
zap = BattleCommand.new(name: "Zap")
entity = fighter_class.new(battle_commands: [kick, zap])
attack = entity.choose_attack
expect(attack.name).to eq("Kick").or(eq("Zap"))
end
end
context "choose item and on whom" do
it "randomly selects both item and on whom" do
banana = Item.new(name: "Banana")
axe = Item.new(name: "Axe")
entity = fighter_class.new(inventory: [C[banana, 1],
C[axe, 3]])
enemy = fighter_class.new(name: "Enemy")
pair = entity.choose_item_and_on_whom(enemy)
expect(pair.first.name).to eq("Banana").or(eq("Axe"))
expect(pair.second.name).to eq("Fighter").or(eq("Enemy"))
end
end
context "equip item" do
it "correctly equips the weapon and alters the stats of a Fighter Entity" do
entity = fighter_class.new(inventory: [C[
Weapon.new(stat_change: {attack: 3},
attack: Attack.new), 1]])
entity.equip_item("Weapon")
expect(entity.outfit[:weapon]).to eq Weapon.new
expect(entity.stats[:attack]).to eq 4
expect(entity.battle_commands).to eq [Attack.new]
end
it "correctly switches the equipped items and alters status of a Fighter Entity as appropriate" do
entity = fighter_class.new(inventory: [C[
Weapon.new(name: "Hammer",
stat_change: {attack: 3,
defense: 2,
agility: 4},
attack: Attack.new(name: "Bash")), 1],
C[
Weapon.new(name: "Knife",
stat_change: {attack: 5,
defense: 3,
agility: 7},
attack: Attack.new(name: "Stab")), 1]])
entity.equip_item("Hammer")
stats = entity.stats
expect(stats[:attack]).to eq 4
expect(stats[:defense]).to eq 3
expect(stats[:agility]).to eq 5
expect(entity.outfit[:weapon].name).to eq "Hammer"
expect(entity.battle_commands).to eq [Attack.new(name: "Bash")]
expect(entity.inventory.length).to eq 1
expect(entity.inventory[0].first.name).to eq "Knife"
entity.equip_item("Knife")
stats = entity.stats
expect(stats[:attack]).to eq 6
expect(stats[:defense]).to eq 4
expect(stats[:agility]).to eq 8
expect(entity.outfit[:weapon].name).to eq "Knife"
expect(entity.battle_commands).to eq [Attack.new(name: "Stab")]
expect(entity.inventory.length).to eq 1
expect(entity.inventory[0].first.name).to eq "Hammer"
end
end
context "has battle command" do
it "correctly indicates an absent command for an object argument" do
entity = fighter_class.new(battle_commands: [
BattleCommand.new(name: "Kick"),
BattleCommand.new(name: "Poke")])
index = entity.has_battle_command(BattleCommand.new(name: "Chop"))
expect(index).to be_nil
end
it "correctly indicates a present command for an object argument" do
entity = fighter_class.new(battle_commands: [
BattleCommand.new(name: "Kick"),
BattleCommand.new(name: "Poke")])
index = entity.has_battle_command(BattleCommand.new(name: "Poke"))
expect(index).to eq 1
end
it "correctly indicates an absent command for a string argument" do
entity = fighter_class.new(battle_commands: [
BattleCommand.new(name: "Kick"),
BattleCommand.new(name: "Poke")])
index = entity.has_battle_command("Chop")
expect(index).to be_nil
end
it "correctly indicates a present command for a string argument" do
entity = fighter_class.new(battle_commands: [
BattleCommand.new(name: "Kick"),
BattleCommand.new(name: "Poke")])
index = entity.has_battle_command("Poke")
expect(index).to eq 1
end
end
context "print battle commands" do
it "should print only the default header when there are no battle commands" do
expect { fighter.print_battle_commands }.to output("Battle Commands:\n\n").to_stdout
end
it "should print the custom header when one is passed" do
expect { fighter.print_battle_commands("Choose an attack:") }.to output("Choose an attack:\n\n").to_stdout
end
it "should print each battle command in a list" do
kick = Attack.new(name: "Kick")
entity = fighter_class.new(battle_commands: [kick, Use.new, Escape.new])
expect { entity.print_battle_commands }.to output(
"Battle Commands:\n❊ Escape\n❊ Kick\n❊ Use\n\n"
).to_stdout
end
end
context "print status" do
it "prints all of the entity's information without battle commands" do
entity = fighter_class.new(stats: {max_hp: 50,
hp: 30,
attack: 5,
defense: 3,
agility: 4},
outfit: {helmet: Helmet.new,
legs: Legs.new,
shield: Shield.new,
torso: Torso.new,
weapon: Weapon.new})
expect { entity.print_status }.to output(
"Stats:\n* HP: 30/50\n* Attack: 5\n* Defense: 3\n* Agility: 4\n\n"\
"Equipment:\n* Weapon: Weapon\n* Shield: Shield\n* Helmet: Helmet\n"\
"* Torso: Torso\n* Legs: Legs\n\n"
).to_stdout
end
it "prints all of the entity's information including battle commands" do
entity = fighter_class.new(stats: {max_hp: 50,
hp: 30,
attack: 5,
defense: 3,
agility: 4},
outfit: {helmet: Helmet.new,
legs: Legs.new,
shield: Shield.new,
torso: Torso.new,
weapon: Weapon.new},
battle_commands: [Escape.new])
expect { entity.print_status }.to output(
"Stats:\n* HP: 30/50\n* Attack: 5\n* Defense: 3\n* Agility: 4\n\n"\
"Equipment:\n* Weapon: Weapon\n* Shield: Shield\n* Helmet: Helmet\n"\
"* Torso: Torso\n* Legs: Legs\n\nBattle Commands:\n❊ Escape\n\n"
).to_stdout
end
end
context "remove battle command" do
it "has no effect when no such command is present" do
fighter.add_battle_command(Attack.new(name: "Kick"))
fighter.remove_battle_command(BattleCommand.new(name: "Poke"))
expect(fighter.battle_commands.length).to eq 1
end
it "correctly removes the command in the trivial case" do
fighter.add_battle_command(Attack.new(name: "Kick"))
fighter.remove_battle_command(Attack.new(name: "Kick"))
expect(fighter.battle_commands.length).to eq 0
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/entity/monster_spec.rb | spec/goby/entity/monster_spec.rb | require 'goby'
RSpec.describe Monster do
let(:slime_item) { Item.new }
let(:wolf) {
Monster.new(name: "Wolf",
stats: { max_hp: 20,
hp: 15,
attack: 2,
defense: 2,
agility: 4 },
inventory: [C[Item.new, 1]],
gold: 10,
outfit: { weapon: Weapon.new(
attack: Attack.new,
stat_change: {attack: 3, defense: 1}
),
helmet: Helmet.new(
stat_change: {attack: 1, defense: 5}
)
},
battle_commands: [
Attack.new(name: "Scratch"),
Attack.new(name: "Kick")
])
}
let!(:dude) { Player.new(stats: { attack: 10, agility: 10000 },
battle_commands: [Attack.new(strength: 20), Escape.new, Use.new])}
let!(:slime) { Monster.new(battle_commands: [Attack.new(success_rate: 0)],
gold: 5000, treasures: [C[slime_item, 1]]) }
let(:newb) { Player.new(battle_commands: [Attack.new(success_rate: 0)],
gold: 50, respawn_location: Location.new(Map.new, C[0, 0])) }
context "constructor" do
it "has the correct default parameters" do
monster = Monster.new
expect(monster.name).to eq "Monster"
expect(monster.stats[:max_hp]).to eq 1
expect(monster.stats[:hp]).to eq 1
expect(monster.stats[:attack]). to eq 1
expect(monster.stats[:defense]).to eq 1
expect(monster.stats[:agility]).to eq 1
expect(monster.inventory).to eq Array.new
expect(monster.gold).to eq 0
expect(monster.outfit).to eq Hash.new
expect(monster.battle_commands).to eq Array.new
expect(monster.treasures).to eq Array.new
end
it "correctly assigns custom parameters" do
clown = Monster.new(name: "Clown",
stats: { max_hp: 20,
hp: 15,
attack: 2,
defense: 2,
agility: 4 },
inventory: [C[Item.new, 1]],
gold: 10,
outfit: { weapon: Weapon.new(
attack: Attack.new,
stat_change: {attack: 3, defense: 1}
),
helmet: Helmet.new(
stat_change: {attack: 1, defense: 5}
)
},
battle_commands: [
Attack.new(name: "Scratch"),
Attack.new(name: "Kick")
],
treasures: [C[Item.new, 1],
C[nil, 3]])
expect(clown.name).to eq "Clown"
expect(clown.stats[:max_hp]).to eq 20
expect(clown.stats[:hp]).to eq 15
expect(clown.stats[:attack]).to eq 6
expect(clown.stats[:defense]).to eq 8
expect(clown.stats[:agility]).to eq 4
expect(clown.inventory).to eq [C[Item.new, 1]]
expect(clown.gold).to eq 10
expect(clown.outfit[:weapon]).to eq Weapon.new
expect(clown.outfit[:helmet]).to eq Helmet.new
expect(clown.battle_commands).to eq [
Attack.new,
Attack.new(name: "Kick"),
Attack.new(name: "Scratch")
]
expect(clown.treasures).to eq [C[Item.new, 1],
C[nil, 3]]
expect(clown.total_treasures).to eq 4
end
end
context "clone" do
let(:monster) { Monster.new(inventory: [C[Item.new, 1]]) }
let!(:clone) { monster.clone }
it "should leave the original's inventory the same" do
clone.use_item("Item", clone)
expect(monster.inventory.size).to eq 1
expect(clone.inventory.size).to be_zero
end
it "should leave the clone's inventory the same" do
monster.use_item("Item", monster)
expect(monster.inventory.size).to be_zero
expect(clone.inventory.size).to eq 1
end
end
# Fighter specific specs
context "fighter" do
it "should be a fighter" do
expect(wolf.class.included_modules.include?(Fighter)).to be true
end
end
context "battle" do
it "should allow the monster to win in this example" do
__stdin("attack\n") do
wolf.battle(newb)
end
# The amount of gold the Monster had + that returned by the Player
expect(newb.gold).to eq 25
end
it "should allow the player to win in this example" do
__stdin("attack\n", "\n") do
slime.battle(dude)
end
expect(dude.inventory.size).to eq 1
end
it "should allow the stronger monster to win as the attacker" do
wolf.battle(slime)
expect(wolf.inventory.size).to eq 1
end
it "should allow the stronger monster to win as the defender" do
slime.battle(wolf)
expect(wolf.inventory.size).to eq 1
end
end
context "die" do
it "does nothing" do
expect(wolf.die).to be_nil
end
end
context "sample gold" do
it "returns a random amount of gold" do
gold_sample = wolf.sample_gold
expect(gold_sample).to be >= 0
expect(gold_sample).to be <= 10
end
end
context "sample treasures" do
it "returns the treasure when there is only one" do
expect(slime.sample_treasures).to eq slime_item
end
it "returns nothing if there are no treasures" do
expect(wolf.sample_treasures).to be_nil
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/entity/entity_spec.rb | spec/goby/entity/entity_spec.rb | require 'goby'
RSpec.describe Entity do
let(:entity) { Entity.new }
context "constructor" do
it "has the correct default parameters" do
expect(entity.name).to eq "Entity"
stats = entity.stats
expect(stats[:max_hp]).to eq 1
expect(stats[:hp]).to eq 1
expect(stats[:attack]). to eq 1
expect(stats[:defense]).to eq 1
expect(stats[:agility]).to eq 1
expect(entity.inventory).to eq Array.new
expect(entity.gold).to eq 0
expect(entity.outfit).to eq Hash.new
end
it "correctly assigns custom parameters" do
hero = Entity.new(name: "Hero",
stats: { max_hp: 50,
hp: 35,
attack: 12,
defense: 4,
agility: 9 },
inventory: [C[Item.new, 1]],
gold: 10,
outfit: { shield: Shield.new(
stat_change: {attack: 3, defense: 1, agility: 4}
),
helmet: Helmet.new(
stat_change: {attack: 1, defense: 5}
) })
expect(hero.name).to eq "Hero"
stats = hero.stats
expect(stats[:max_hp]).to eq 50
expect(stats[:hp]).to eq 35
# Attack & defense increase due to the equipped items.
expect(stats[:attack]).to eq 16
expect(stats[:defense]).to eq 10
expect(stats[:agility]).to eq 13
expect(hero.inventory).to eq [C[Item.new, 1]]
expect(hero.gold).to eq 10
expect(hero.outfit[:shield]).to eq Shield.new
expect(hero.outfit[:helmet]).to eq Helmet.new
end
it "assigns default keyword arguments as appropriate" do
entity = Entity.new(stats: { max_hp: 7,
defense: 9 },
gold: 3)
expect(entity.name).to eq "Entity"
stats = entity.stats
expect(stats[:max_hp]).to eq 7
expect(stats[:hp]).to eq 7
expect(stats[:attack]).to eq 1
expect(stats[:defense]).to eq 9
expect(stats[:agility]).to eq 1
expect(entity.inventory).to eq []
expect(entity.gold).to eq 3
end
end
context "add gold" do
it "properly adds the appropriate amount of gold" do
entity.add_gold(30)
expect(entity.gold).to eq 30
end
it "prevents gold < 0" do
entity.add_gold(-30)
expect(entity.gold).to be_zero
end
end
context "add item" do
it "properly adds an item in a trivial case" do
entity.add_item(Item.new)
expect(entity.inventory.length).to eq 1
expect(entity.inventory[0].first).to eq Item.new
expect(entity.inventory[0].second).to eq 1
end
it "properly adds the same item to the same slot" do
entity.add_item(Item.new, 2)
expect(entity.inventory[0].second).to eq 2
entity.add_item(Item.new, 4)
expect(entity.inventory[0].second).to eq 6
expect(entity.inventory.length).to eq 1
end
it "handles multiple items being added in succession" do
entity.add_item(Item.new, 3)
entity.add_item(Item.new(name: "Apple"), 2)
entity.add_item(Item.new(name: "Orange"), 4)
entity.add_item(Item.new(name: "Apple"), 3)
expect(entity.inventory.length).to eq 3
expect(entity.inventory[0].first).to eq Item.new
expect(entity.inventory[0].second).to eq 3
expect(entity.inventory[1].first).to eq Item.new(name: "Apple")
expect(entity.inventory[1].second).to eq 5
expect(entity.inventory[2].first).to eq Item.new(name: "Orange")
expect(entity.inventory[2].second).to eq 4
end
end
context "add rewards" do
it "should give the player the appropriate amount of gold" do
entity.add_loot(5, nil)
expect(entity.gold).to eq 5
expect(entity.inventory.size).to be_zero
end
it "should give the player the appropriate treasure item" do
entity.add_loot(0, [Item.new])
expect(entity.gold).to be_zero
expect(entity.inventory).to eq [C[Item.new, 1]]
end
it "should give the player both the gold and all the treasures" do
entity.add_loot(5, [Item.new, Helmet.new, Food.new])
expect(entity.gold).to eq 5
expect(entity.inventory.size).to eq 3
expect(entity.inventory[0].first).to eq Item.new
expect(entity.inventory[1].first).to eq Helmet.new
expect(entity.inventory[2].first).to eq Food.new
end
it "should not give the player the nil treasure" do
entity.add_loot(0, [Food.new, nil])
expect(entity.inventory.size).to eq 1
expect(entity.inventory[0].first).to eq Food.new
end
it "should not output anything for no rewards" do
expect { entity.add_loot(0, nil) }.to output(
"Loot: nothing!\n\n"
).to_stdout
end
it "should not output anything for empty treasures" do
expect { entity.add_loot(0, []) }.to output(
"Loot: nothing!\n\n"
).to_stdout
end
it "should not output anything for only nil treasures" do
expect { entity.add_loot(0, [nil, nil] )}.to output(
"Loot: nothing!\n\n"
).to_stdout
end
it "should output only the gold" do
expect { entity.add_loot(3, nil) }.to output(
"Loot: \n* 3 gold\n\n"
).to_stdout
end
it "should output only the treasures" do
expect { entity.add_loot(0, [Item.new, Food.new]) }.to output(
"Loot: \n* Item\n* Food\n\n"
).to_stdout
end
it "should output both of the rewards" do
expect { entity.add_loot(5, [Item.new]) }.to output(
"Loot: \n* 5 gold\n* Item\n\n"
).to_stdout
end
it "should output all of the rewards" do
expect { entity.add_loot(7, [Item.new, Helmet.new, Food.new]) }.to output(
"Loot: \n* 7 gold\n* Item\n* Helmet\n* Food\n\n"
).to_stdout
end
it "should not output the nil treasure" do
expect { entity.add_loot(0, [Item.new, nil, Food.new]) }.to output(
"Loot: \n* Item\n* Food\n\n"
).to_stdout
end
end
context "clear inventory" do
it "has no effect on an empty inventory" do
entity.clear_inventory
expect(entity.inventory.size).to be_zero
end
it "removes all items from a non-empty inventory" do
entity = Entity.new(inventory: [C[Item.new, 4],
C[Item.new(name: "Apple"), 3],
C[Item.new(name: "Orange"), 7]])
entity.clear_inventory
expect(entity.inventory.size).to be_zero
end
end
context "equip item" do
it "correctly equips the helmet and alters the stats" do
entity = Entity.new(inventory: [C[
Helmet.new(stat_change: { defense: 3 } ), 1]])
entity.equip_item("Helmet")
expect(entity.outfit[:helmet]).to eq Helmet.new
expect(entity.stats[:defense]).to eq 4
end
it "correctly equips the shield and alters the stats" do
entity = Entity.new(inventory: [C[
Shield.new(stat_change: { defense: 3,
agility: 2 } ), 1]])
entity.equip_item("Shield")
expect(entity.outfit[:shield]).to eq Shield.new
expect(entity.stats[:defense]).to eq 4
expect(entity.stats[:agility]).to eq 3
end
it "correctly equips the legs and alters the stats" do
entity = Entity.new(inventory: [C[
Legs.new(stat_change: { defense: 3 } ), 1]])
entity.equip_item("Legs")
expect(entity.outfit[:legs]).to eq Legs.new
expect(entity.stats[:defense]).to eq 4
end
it "correctly equips the torso and alters the stats" do
entity = Entity.new(inventory: [C[
Torso.new(stat_change: { defense: 3 } ), 1]])
entity.equip_item("Torso")
expect(entity.outfit[:torso]).to eq Torso.new
expect(entity.stats[:defense]).to eq 4
end
it "does not equip anything for an absent item" do
entity.equip_item("Weapon")
expect(entity.outfit).to be_empty
end
it "only removes one of the equipped item from the inventory" do
entity = Entity.new(inventory: [C[
Helmet.new(stat_change: { defense: 3 } ), 2]])
entity.equip_item("Helmet")
expect(entity.inventory.length).to eq 1
expect(entity.inventory[0].first).to eq Helmet.new
expect(entity.inventory[0].second).to eq 1
end
it "correctly switches the equipped items and alters status as appropriate" do
entity = Entity.new(inventory: [C[
Helmet.new(name: "Builder",
stat_change: { attack: 3,
defense: 2,
agility: 4 }), 1],
C[
Helmet.new(name: "Viking",
stat_change: { attack: 5,
defense: 3,
agility: 7 }), 1]])
entity.equip_item("Builder")
stats = entity.stats
expect(stats[:attack]).to eq 4
expect(stats[:defense]).to eq 3
expect(stats[:agility]).to eq 5
expect(entity.outfit[:helmet].name).to eq "Builder"
expect(entity.inventory.length).to eq 1
expect(entity.inventory[0].first.name).to eq "Viking"
entity.equip_item("Viking")
stats = entity.stats
expect(stats[:attack]).to eq 6
expect(stats[:defense]).to eq 4
expect(stats[:agility]).to eq 8
expect(entity.outfit[:helmet].name).to eq "Viking"
expect(entity.inventory.length).to eq 1
expect(entity.inventory[0].first.name).to eq "Builder"
end
it "prints an error message for an unequippable item" do
entity = Entity.new(inventory: [C[Item.new, 1]])
expect { entity.equip_item("Item") }.to output(
"Item cannot be equipped!\n\n"
).to_stdout
end
end
context "has item" do
it "correctly indicates an absent item for an object argument" do
entity.add_item(Item.new(name: "Apple"))
entity.add_item(Item.new(name: "Orange"))
index = entity.has_item(Item.new(name: "Banana"))
expect(index).to be_nil
end
it "correctly indicates a present item for an object argument" do
entity.add_item(Item.new(name: "Apple"))
entity.add_item(Item.new(name: "Orange"))
index = entity.has_item(Item.new(name: "Apple"))
expect(index).to eq 0
end
it "correctly indicates an absent item for a string argument" do
entity.add_item(Item.new(name: "Apple"))
entity.add_item(Item.new(name: "Orange"))
index = entity.has_item("Banana")
expect(index).to be_nil
end
it "correctly indicates a present item for a string argument" do
entity.add_item(Item.new(name: "Apple"))
entity.add_item(Item.new(name: "Orange"))
index = entity.has_item("Orange")
expect(index).to eq 1
end
end
context "print inventory" do
it "should print the inventory is empty when it is" do
expect { entity.print_inventory }.to output(
"Current gold in pouch: 0.\n\nEntity's inventory is empty!\n\n"
).to_stdout
end
it "should print the complete inventory when not empty" do
apple = Item.new(name: "Apple")
banana = Item.new(name: "Banana")
entity = Entity.new(gold: 33, inventory: [
C[apple, 1], C[banana, 2]] )
expect { entity.print_inventory }.to output(
"Current gold in pouch: 33.\n\nEntity's inventory:\n"\
"* Apple (1)\n* Banana (2)\n\n"
).to_stdout
end
end
context "print status" do
it "prints all of the entity's information" do
entity = Entity.new(stats: { max_hp: 50,
hp: 30,
attack: 5,
defense: 3,
agility: 4 },
outfit: { helmet: Helmet.new,
legs: Legs.new,
shield: Shield.new,
torso: Torso.new,
weapon: Weapon.new })
expect { entity.print_status }.to output(
"Stats:\n* HP: 30/50\n* Attack: 5\n* Defense: 3\n* Agility: 4\n\n"\
"Equipment:\n* Weapon: Weapon\n* Shield: Shield\n* Helmet: Helmet\n"\
"* Torso: Torso\n* Legs: Legs\n\n"
).to_stdout
end
it "prints the appropriate info for the default Entity" do
expect { entity.print_status }.to output(
"Stats:\n* HP: 1/1\n* Attack: 1\n* Defense: 1\n* Agility: 1\n\n"\
"Equipment:\n* Weapon: none\n* Shield: none\n* Helmet: none\n"\
"* Torso: none\n* Legs: none\n\n"
).to_stdout
end
end
context "remove gold" do
it "should remove the given amount of gold" do
entity = Entity.new(gold: 50)
entity.remove_gold(20)
expect(entity.gold).to eq 30
end
it "should prevent gold < 0" do
entity = Entity.new(gold: 5)
entity.remove_gold(10)
expect(entity.gold).to be_zero
end
end
context "remove item" do
it "has no effect when no such item is present" do
entity.add_item(Item.new(name: "Apple"))
entity.remove_item(Item.new(name: "Banana"))
expect(entity.inventory.length).to eq 1
end
it "correctly removes the item in the trivial case" do
entity.add_item(Item.new(name: "Apple"))
entity.remove_item(Item.new(name: "Apple"))
expect(entity.inventory.length).to eq 0
end
it "correctly removes multiple of the same item" do
entity.add_item(Item.new(name: "Apple"), 4)
entity.remove_item(Item.new(name: "Apple"), 3)
expect(entity.inventory.length).to eq 1
expect(entity.inventory[0].first.name).to eq "Apple"
end
it "removes all of an item and leaves no gaps" do
entity.add_item(Item.new(name: "Apple"), 4)
entity.add_item(Item.new(name: "Banana"), 3)
entity.add_item(Item.new(name: "Orange"), 7)
entity.remove_item(Item.new(name: "Banana"), 6)
expect(entity.inventory.length).to eq 2
expect(entity.inventory[0].first.name).to eq "Apple"
expect(entity.inventory[1].first.name).to eq "Orange"
end
end
context "set gold" do
it "should set the gold to the given amount" do
entity = Entity.new(gold: 10)
entity.set_gold(15)
expect(entity.gold).to eq 15
end
it "should prevent gold < 0" do
entity = Entity.new(gold: 5)
entity.set_gold(-10)
expect(entity.gold).to be_zero
end
end
context "unequip item" do
it "correctly unequips an equipped item" do
entity = Entity.new(outfit: { helmet: Helmet.new(stat_change: {agility: 4})})
entity.unequip_item("Helmet")
expect(entity.outfit).to be_empty
expect(entity.inventory.length).to eq 1
expect(entity.inventory[0].first).to eq Helmet.new
expect(entity.inventory[0].second).to eq 1
expect(entity.stats[:agility]).to eq 1
end
it "does not result in error when unequipping the same item twice" do
entity = Entity.new(inventory: [C[
Helmet.new(stat_change: { defense: 3 } ), 2]])
entity.equip_item("Helmet")
entity.unequip_item("Helmet")
expect(entity.inventory.length).to eq 1
expect(entity.inventory[0].first).to eq Helmet.new
expect(entity.inventory[0].second).to eq 2
entity.unequip_item("Helmet")
expect(entity.inventory.length).to eq 1
expect(entity.inventory[0].first).to eq Helmet.new
expect(entity.inventory[0].second).to eq 2
end
end
context "use item" do
it "correctly uses a present item for an object argument" do
entity = Entity.new(stats: { max_hp: 20, hp: 10 },
inventory: [C[Food.new(recovers: 5), 3]])
entity.use_item(Food.new, entity)
expect(entity.stats[:hp]).to eq 15
expect(entity.inventory[0].first).to eq Food.new
expect(entity.inventory[0].second).to eq 2
end
it "correctly uses a present item for a string argument" do
entity = Entity.new(stats: { max_hp: 20, hp: 10 },
inventory: [C[Food.new(recovers: 5), 3]])
entity.use_item("Food", entity)
expect(entity.stats[:hp]).to eq 15
expect(entity.inventory[0].first).to eq Food.new
expect(entity.inventory[0].second).to eq 2
end
end
context "equality operator" do
it "returns true for the trivial case" do
entity1 = Entity.new
entity2 = Entity.new
expect(entity1).to eq entity2
end
it "returns false for Entities with different names" do
bob = Entity.new(name: "Bob")
marge = Entity.new(name: "Marge")
expect(bob).not_to eq marge
end
end
context "set stats" do
it "changes an entities stats" do
entity = Entity.new(stats: { max_hp: 2, hp: 1, attack: 1, defense: 1, agility: 1 })
entity.set_stats({ max_hp: 3, hp: 3, attack: 2, defense: 3, agility: 4 })
stats = entity.stats
expect(stats[:max_hp]).to eq 3
expect(stats[:hp]).to eq 3
expect(stats[:attack]).to eq 2
expect(stats[:defense]).to eq 3
expect(stats[:agility]).to eq 4
end
it "only changes specified stats" do
entity = Entity.new(stats: { max_hp: 4, hp: 2, attack: 1, defense: 4, agility: 4 })
entity.set_stats({ max_hp: 3, attack: 2 })
stats = entity.stats
expect(stats[:max_hp]).to eq 3
expect(stats[:hp]).to eq 2
expect(stats[:attack]).to eq 2
expect(stats[:defense]).to eq 4
expect(stats[:agility]).to eq 4
end
it "sets hp to max_hp if hp is passed in as nil" do
entity.set_stats({ max_hp: 2, hp: nil })
stats = entity.stats
expect(stats[:max_hp]).to eq 2
expect(stats[:hp]).to eq 2
end
it "hp cannot be more than max hp" do
entity.set_stats({ max_hp: 2, hp: 3 })
stats = entity.stats
expect(stats[:max_hp]).to eq 2
expect(stats[:hp]).to eq 2
end
it "non hp values cannot go below 1" do
entity = Entity.new(stats: { max_hp: 2, attack: 3, defense: 2, agility: 3 })
entity.set_stats({ max_hp: 0, attack: 0, defense: 0, agility: 0 })
stats = entity.stats
expect(stats[:max_hp]).to eq 1
expect(stats[:attack]).to eq 1
expect(stats[:defense]).to eq 1
expect(stats[:agility]).to eq 1
end
it "hp cannot go below 0" do
entity = Entity.new(stats: {hp: 3})
entity.set_stats({hp: -1})
stats = entity.stats
expect(stats[:hp]).to eq 0
end
it "raises error if non-numeric passed in" do
entity = Entity.new(stats: { attack: 11 })
expect{ entity.set_stats({ attack: "foo" }) }.to raise_error
expect(entity.stats[:attack]).to eq 11
end
it "only allows stats to be changed by calling set_stats" do
entity = Entity.new(stats: { attack: 11 })
expect do
entity.stats = {attack: 9}
end.to raise_exception
expect do
entity.stats[:attack] = 9
end.to raise_exception
expect(entity.stats[:attack]).to eq 11
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/event/chest_spec.rb | spec/goby/event/chest_spec.rb | require 'goby'
RSpec.describe Chest do
let!(:player) { Player.new }
let!(:chest) { Chest.new }
let!(:gold_chest) { Chest.new(gold: 100) }
let!(:treasure_chest) { Chest.new(treasures: [Item.new, Food.new, Helmet.new]) }
let!(:giant_chest) { Chest.new(gold: 100, treasures: [Item.new, Food.new, Helmet.new]) }
context "constructor" do
it "has the correct default parameters" do
expect(chest.mode).to be_zero
expect(chest.visible).to be true
expect(chest.gold).to be_zero
expect(chest.treasures).to be_empty
end
it "correctly assigns custom parameters" do
chest = Chest.new(mode: 5, visible: false, gold: 3, treasures: [Item.new])
expect(chest.mode).to eq 5
expect(chest.visible).to be false
expect(chest.gold).to be 3
expect(chest.treasures[0]).to eq Item.new
end
end
context "run" do
it "should no longer be visible after the first open" do
chest.run(player)
expect(chest.visible).to be false
end
it "correctly gives the player nothing for no gold, no treasure" do
chest.run(player)
expect(player.gold).to be_zero
expect(player.inventory).to be_empty
end
it "correctly gives the player only gold when no treasure" do
gold_chest.run(player)
expect(player.gold).to be 100
expect(player.inventory).to be_empty
end
it "correctly gives the player only treasure when no gold" do
treasure_chest.run(player)
expect(player.gold).to be_zero
expect(player.inventory.size).to be 3
end
it "correctly gives the player both gold and treasure when both" do
giant_chest.run(player)
expect(player.gold).to be 100
expect(player.inventory.size).to be 3
end
it "outputs that there is no loot for no gold, no treasure" do
expect { chest.run(player) }.to output(
"You open the treasure chest...\n\nLoot: nothing!\n\n"
).to_stdout
end
it "outputs that there is only gold when no treasure" do
expect { gold_chest.run(player) }.to output(
"You open the treasure chest...\n\nLoot: \n* 100 gold\n\n"
).to_stdout
end
it "outputs that there is only treasure when no gold" do
expect { treasure_chest.run(player) }.to output(
"You open the treasure chest...\n\n"\
"Loot: \n* Item\n* Food\n* Helmet\n\n"
).to_stdout
end
it "outputs that there is both treasure and gold when both" do
expect { giant_chest.run(player) }.to output(
"You open the treasure chest...\n\n"\
"Loot: \n* 100 gold\n* Item\n* Food\n* Helmet\n\n"
).to_stdout
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/event/shop_spec.rb | spec/goby/event/shop_spec.rb | require 'goby'
RSpec.describe Shop do
let!(:shop) { Shop.new }
let!(:tools) { [Item.new(name: "Basket", price: 5),
Item.new(name: "Knife", price: 10),
Item.new(name: "Fork", price: 12),
Item.new(name: "Screwdriver", price: 7)] }
let!(:tool_shop) { Shop.new(name: "Tool Shop",
mode: 1,
visible: false,
items: tools) }
let!(:apple) { Item.new(name: "Apple", price: 2) }
let!(:banana) { Item.new(name: "Banana", disposable: false) }
# player1 doesn't have any gold.
let!(:player1) { Player.new(inventory: [C[apple, 3],
C[banana, 1]] ) }
# player2 has nothing in the inventory.
let!(:player2) { Player.new(gold: 50) }
context "constructor" do
it "has the correct default parameters" do
expect(shop.name).to eq "Shop"
expect(shop.command).to eq "shop"
expect(shop.mode).to eq 0
expect(shop.visible).to eq true
expect(shop.items).to eq Array.new
end
it "correctly assigns custom parameters" do
expect(tool_shop.name).to eq "Tool Shop"
expect(tool_shop.command).to eq "shop"
expect(tool_shop.mode).to eq 1
expect(tool_shop.visible).to eq false
expect(tool_shop.items).to eq tools
end
end
context "buy" do
it "should print an error message when the shop has nothing to sell" do
expect { shop.buy(player2) }.to output(Shop::NO_ITEMS_MESSAGE).to_stdout
end
it "should return if the player doesn't want to buy anything" do
__stdin("none\n") do
tool_shop.buy(player2)
expect(player2.inventory.empty?).to be true
end
end
it "should return if the player specifies a non-existent item" do
__stdin("pencil\n") do
tool_shop.buy(player2)
expect(player2.inventory.empty?).to be true
end
end
it "should prevent the player from buying more than (s)he has in gold" do
__stdin("fork\n5\n") do
tool_shop.buy(player2)
expect(player2.inventory.empty?).to be true
end
end
it "should prevent the player from buying a non-positive amount" do
__stdin("fork\n0\n") do
tool_shop.buy(player2)
expect(player2.inventory.empty?).to be true
end
end
it "should sell the item to the player for a sensible purchase" do
__stdin("fork\n2\n") do
tool_shop.buy(player2)
expect(player2.inventory.empty?).to be false
expect(player2.gold).to be 26
expect(player2.has_item("Fork")).to eq 0
end
end
end
context "has item" do
it "returns nil when no such item is available" do
expect(shop.has_item("Basket")).to be_nil
end
it "returns the index of the item when available" do
expect(tool_shop.has_item("Basket")).to be_zero
expect(tool_shop.has_item("Knife")).to eq 1
expect(tool_shop.has_item("Fork")).to eq 2
expect(tool_shop.has_item("Screwdriver")).to eq 3
end
end
context "print gold and greeting" do
it "prints the appropriate output" do
__stdin("exit\n") do
expect { shop.print_gold_and_greeting(player2) }.to output(
"Current gold in your pouch: 50.\n"\
"Would you like to buy, sell, or exit?: \n"\
).to_stdout
end
end
it "returns the input (w/o newline)" do
__stdin("buy\n") do
expect(shop.print_gold_and_greeting(player2)).to eq "buy"
end
end
end
context "print items" do
it "should print a helpful message when there's nothing to sell" do
expect { shop.print_items }.to output(Shop::NO_ITEMS_MESSAGE).to_stdout
end
it "should print the formatted list when there are items to sell" do
expect { tool_shop.print_items }.to output(
"#{Shop::WARES_MESSAGE}"\
"Basket (5 gold)\n"\
"Knife (10 gold)\n"\
"Fork (12 gold)\n"\
"Screwdriver (7 gold)\n\n"
).to_stdout
end
end
context "run" do
it "should allow the player to buy an item" do
__stdin("buy\nknife\n3\nexit\n") do
tool_shop.run(player2)
expect(player2.gold).to eq 20
expect(player2.inventory.size).to eq 1
end
end
it "should allow the player to sell an item" do
__stdin("sell\napple\n3\nexit\n") do
tool_shop.run(player1)
expect(player1.gold).to eq 3
expect(player1.inventory.size).to eq 1
end
end
it "should allow the player to leave immediately" do
__stdin("exit\n") do
tool_shop.run(player1)
expect(player1.gold).to be_zero
expect(player1.inventory.size).to eq 2
end
end
end
context "sell" do
it "should print an error message when the player has nothing to sell" do
expect { tool_shop.sell(player2) }.to output(Shop::NOTHING_TO_SELL).to_stdout
end
it "should return if the player doesn't want to sell anything" do
__stdin("none\n") do
tool_shop.sell(player1)
expect(player1.gold).to be_zero
end
end
it "should return if the player tries to sell a non-existent item" do
__stdin("object\n") do
tool_shop.sell(player1)
expect(player1.gold).to be_zero
end
end
it "should return if the player tries to sell a non-disposable item" do
__stdin("banana\n") do
tool_shop.sell(player1)
expect(player1.gold).to be_zero
end
end
it "should prevent the player from selling more than (s)he has" do
__stdin("apple\n4\n") do
tool_shop.sell(player1)
expect(player1.gold).to be_zero
end
end
it "should prevent the player from selling a non-positive amount" do
__stdin("apple\n0\n") do
tool_shop.sell(player1)
expect(player1.gold).to be_zero
end
end
it "should purchase the item for a sensible sale" do
__stdin("apple\n3\n") do
tool_shop.sell(player1)
expect(player1.gold).to be 3
expect(player1.inventory.size).to be 1
end
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/event/npc_spec.rb | spec/goby/event/npc_spec.rb | require 'goby'
RSpec.describe NPC do
let(:npc) { NPC.new }
let(:entity) { Entity.new }
context "constructor" do
it "has the correct default parameters" do
expect(npc.name).to eq "NPC"
expect(npc.command).to eq "talk"
expect(npc.mode).to eq 0
expect(npc.visible).to eq true
end
it "correctly assigns custom parameters" do
john = NPC.new(name: "John",
mode: 1,
visible: false)
expect(john.name).to eq "John"
expect(john.command).to eq "talk" # Always talk command.
expect(john.mode).to eq 1
expect(john.visible).to eq false
end
end
context "use" do
it "prints the default text for the default NPC" do
expect { npc.run(entity) }.to output("NPC: Hello!\n\n").to_stdout
end
end
context "say" do
subject(:npc) { NPC.new }
it "outputs the NPC's name and words argument" do
expect { npc.say("Welcome to Goby") }.to output("NPC: Welcome to Goby").to_stdout
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/event/event_spec.rb | spec/goby/event/event_spec.rb | require 'goby'
RSpec.describe Event do
let(:event) { Event.new }
let(:entity) { Entity.new }
context "constructor" do
it "has the correct default parameters" do
expect(event.command).to eq "event"
expect(event.mode).to eq 0
expect(event.visible).to eq true
end
it "correctly assigns custom parameters" do
box = Event.new(command: "open",
mode: 1,
visible: false)
expect(box.command).to eq "open"
expect(box.mode).to eq 1
expect(box.visible).to eq false
end
end
context "run" do
it "prints the default run text for a default event" do
entity = Entity.new
expect { event.run(entity) }.to output(Event::DEFAULT_RUN_TEXT).to_stdout
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/battle/battle_spec.rb | spec/goby/battle/battle_spec.rb | require 'goby'
RSpec.describe Goby::Battle do
let(:dummy_fighter_class) {
Class.new(Entity) do
include Fighter
def initialize(name: "Player", stats: {}, inventory: [], gold: 0, battle_commands: [], outfit: {})
super(name: name, stats: stats, inventory: inventory, gold: gold, outfit: outfit)
add_battle_commands(battle_commands)
end
end
}
context "constructor" do
it "takes two arguments" do
expect { Battle.new }.to raise_error(ArgumentError, "wrong number of arguments (given 0, expected 2)")
entity_1 = entity_2 = double
battle = Battle.new(entity_1, entity_2)
expect(battle).to be_a Battle
end
end
context "determine_winner" do
it "prompts both entities to choose an attack" do
entity_1 = spy('entity_1', stats: {hp: 1, agility: 1})
entity_2 = spy('entity_2', stats: {hp: 1, agility: 1})
Battle.new(entity_1, entity_2).determine_winner
expect(entity_1).to have_received(:choose_attack)
expect(entity_2).to have_received(:choose_attack)
end
it "returns the entity with positive hp" do
entity_1 = dummy_fighter_class.new(name: "Player",
stats: {max_hp: 20,
hp: 15,
attack: 2,
defense: 2,
agility: 4},
outfit: {weapon: Weapon.new(
attack: Attack.new,
stat_change: {attack: 3, defense: 1}
),
helmet: Helmet.new(
stat_change: {attack: 1, defense: 5}
)
},
battle_commands: [
Attack.new(name: "Scratch"),
Attack.new(name: "Kick")
])
entity_2 = dummy_fighter_class.new(name: "Clown",
stats: {max_hp: 20,
hp: 15,
attack: 2,
defense: 2,
agility: 4},
outfit: {weapon: Weapon.new(
attack: Attack.new,
stat_change: {attack: 3, defense: 1}
),
helmet: Helmet.new(
stat_change: {attack: 1, defense: 5}
)
},
battle_commands: [
Attack.new(name: "Scratch"),
Attack.new(name: "Kick")
])
battle = Battle.new(entity_1, entity_2)
winner = battle.determine_winner
expect([entity_1, entity_2].include?(winner)).to be true
loser = ([entity_1, entity_2] - [winner])[0]
expect(winner.stats[:hp]).to be > 0
expect(loser.stats[:hp]).to eql(0)
end
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/battle/escape_spec.rb | spec/goby/battle/escape_spec.rb | require 'goby'
RSpec.describe Goby::Escape do
let(:player) { Player.new }
let(:monster) { Monster.new }
let(:escape) { Escape.new }
context "constructor" do
it "has an appropriate default name" do
expect(escape.name).to eq "Escape"
end
end
context "run" do
# The purpose of this test is to run the code without error.
it "should return a usable result" do
# Exercise both branches of this function w/ high probability.
20.times do
escape.run(player, monster)
expect(player.escaped).to_not be nil
end
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/battle/use_spec.rb | spec/goby/battle/use_spec.rb | require 'goby'
RSpec.describe Use do
let(:use) { Use.new }
context "constructor" do
it "has an appropriate default name" do
expect(use.name).to eq "Use"
end
end
context "run" do
let(:player) { Player.new(stats: { max_hp: 10, hp: 3 },
battle_commands: [@use],
inventory: [C[Food.new(recovers: 5), 1]]) }
let(:monster) { Monster.new }
it "uses the specified item and remove it from the entity's inventory" do
# RSpec input example. Also see spec_helper.rb for __stdin method.
__stdin("food\n", "player\n") do
use.run(player, monster)
expect(player.stats[:hp]).to eq 8
expect(player.inventory.empty?).to be true
end
end
it "has no effect when the user chooses to pass" do
__stdin("pass\n") do
use.run(player, monster)
expect(player.inventory.empty?).to be false
end
end
end
context "fails?" do
let(:entity) { Entity.new }
it "returns true when the user's inventory is empty" do
expect(use.fails?(entity)).to be true
end
it "returns false when the user has at least one item" do
entity.add_item(Item.new)
expect(use.fails?(entity)).to be false
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/battle/battle_command_spec.rb | spec/goby/battle/battle_command_spec.rb | require 'goby'
RSpec.describe Goby::BattleCommand do
let(:cmd) { BattleCommand.new }
context "constructor" do
it "has the correct default parameters" do
expect(cmd.name).to eq "BattleCommand"
end
it "correctly assigns custom parameters" do
dance = BattleCommand.new(name: "Dance")
expect(dance.name).to eq "Dance"
end
end
context "run" do
it "prints the default message" do
user = Entity.new
enemy = Entity.new
# Rspec: expect output.
expect { cmd.run(user, enemy) }.to output(Goby::BattleCommand::NO_ACTION).to_stdout
end
end
context "fails?" do
it "returns false for the trivial case" do
entity = Entity.new
expect(cmd.fails?(entity)).to be false
end
end
context "equality operator" do
it "returns true for the seemingly trivial case" do
expect(cmd).to eq cmd
end
it "returns false for commands with different names" do
dance = BattleCommand.new(name: "Dance")
kick = BattleCommand.new(name: "Kick")
expect(dance).not_to eq kick
end
end
context "to_s" do
it "returns the name of the BattleCommand" do
expect(cmd.to_s).to eq cmd.name
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/battle/attack_spec.rb | spec/goby/battle/attack_spec.rb | require 'goby'
RSpec.describe Goby::Attack do
let!(:user) { Player.new(stats: { max_hp: 50, attack: 6, defense: 4 }) }
let!(:enemy) { Monster.new(stats: { max_hp: 30, attack: 3, defense: 2 }) }
let(:attack) { Attack.new(strength: 5) }
let(:cry) { Attack.new(name: "Cry", success_rate: 0) }
context "constructor" do
it "has the correct default parameters" do
attack = Attack.new
expect(attack.name).to eq "Attack"
expect(attack.strength).to eq 1
expect(attack.success_rate).to eq 100
end
it "correctly assigns all custom parameters" do
poke = Attack.new(name: "Poke",
strength: 12,
success_rate: 95)
expect(poke.name).to eq "Poke"
expect(poke.strength).to eq 12
expect(poke.success_rate).to eq 95
end
it "correctly assigns only one custom parameter" do
attack = Attack.new(success_rate: 77)
expect(attack.name).to eq "Attack"
expect(attack.strength).to eq 1
expect(attack.success_rate).to eq 77
end
end
context "equality operator" do
it "returns true for the seemingly trivial case" do
expect(Attack.new).to eq Attack.new
end
it "returns false for commands with different names" do
poke = Attack.new(name: "Poke")
kick = Attack.new(name: "Kick")
expect(poke).not_to eq kick
end
end
context "run" do
it "does the appropriate amount of damage for attack > defense" do
attack.run(user, enemy)
expect(enemy.stats[:hp]).to be_between(21, 24)
end
it "prevents the enemy's HP from falling below 0" do
user.set_stats(attack: 200)
attack.run(user, enemy)
expect(enemy.stats[:hp]).to be_zero
end
it "does the appropriate amount of damage for defense > attack" do
attack.run(enemy, user)
expect(user.stats[:hp]).to be_between(45, 46)
end
it "prints an appropriate message for a failed attack" do
expect { cry.run(user, enemy) }.to output(
"Player tries to use Cry, but it fails.\n\n"
).to_stdout
end
end
context "calculate damage" do
it "returns within the appropriate range for attack > defense" do
damage = attack.calculate_damage(user, enemy)
expect(damage).to be_between(6, 9)
end
it "returns within the appropriate range for defense > attack" do
damage = attack.calculate_damage(enemy, user)
expect(damage).to be_between(4, 5)
end
it "defaults to 0 when the defense is very high" do
enemy.set_stats(defense: 100)
damage = attack.calculate_damage(user, enemy)
expect(damage).to be_zero
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/item/weapon_spec.rb | spec/goby/item/weapon_spec.rb | require 'goby'
RSpec.describe Weapon do
let(:weapon) { Weapon.new }
let(:entity) { Entity.new.extend(Fighter) }
let(:dummy_fighter_class) { Class.new(Entity) {include Fighter} }
context "constructor" do
it "has the correct default parameters" do
expect(weapon.name).to eq "Weapon"
expect(weapon.price).to eq 0
expect(weapon.consumable).to eq false
expect(weapon.disposable).to eq true
expect(weapon.type).to eq :weapon
end
it "correctly assigns custom parameters" do
pencil = Weapon.new(name: "Pencil",
price: 20,
consumable: true,
disposable: false,
stat_change: {attack: 2, defense: 2})
expect(pencil.name).to eq "Pencil"
expect(pencil.price).to eq 20
expect(pencil.consumable).to eq true
expect(pencil.disposable).to eq false
expect(pencil.stat_change[:attack]).to eq 2
expect(pencil.stat_change[:defense]).to eq 2
# Cannot be overwritten.
expect(pencil.type).to eq :weapon
end
end
context "equip" do
it "correctly equips the weapon and alters the stats of a Fighter Entity" do
weapon = Weapon.new(stat_change: {attack: 3},
attack: Attack.new)
weapon.equip(entity)
expect(entity.outfit[:weapon]).to eq Weapon.new
expect(entity.stats[:attack]).to eq 4
expect(entity.battle_commands).to eq [Attack.new]
end
end
context "use" do
it "should print an appropriate message for how to equip" do
expect { weapon.use(entity, entity) }.to output(
"Type 'equip Weapon' to equip this item.\n\n"
).to_stdout
end
end
context "unequip" do
it "correctly unequips an equipped item from a Fighter Entity" do
weapon = Weapon.new(stat_change: {agility: 4},
attack: Attack.new)
entity = dummy_fighter_class.new(outfit: {weapon: weapon})
weapon.unequip(entity)
expect(entity.outfit).to be_empty
expect(entity.battle_commands).to be_empty
expect(entity.stats[:agility]).to eq 1
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/item/helmet_spec.rb | spec/goby/item/helmet_spec.rb | require 'goby'
RSpec.describe Helmet do
context "constructor" do
it "has the correct default parameters" do
helmet = Helmet.new
expect(helmet.name).to eq "Helmet"
expect(helmet.price).to eq 0
expect(helmet.consumable).to eq false
expect(helmet.disposable).to eq true
expect(helmet.type).to eq :helmet
end
it "correctly assigns custom parameters" do
big_hat = Helmet.new(name: "Big Hat",
price: 20,
consumable: true,
disposable: false,
stat_change: {attack: 2, defense: 2})
expect(big_hat.name).to eq "Big Hat"
expect(big_hat.price).to eq 20
expect(big_hat.consumable).to eq true
expect(big_hat.disposable).to eq false
expect(big_hat.stat_change[:attack]).to eq 2
expect(big_hat.stat_change[:defense]).to eq 2
# Cannot be overwritten.
expect(big_hat.type).to eq :helmet
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/item/food_spec.rb | spec/goby/item/food_spec.rb | require 'goby'
RSpec.describe Food do
let(:food) { Food.new }
let(:magic_banana) { Food.new(name: "Magic Banana", price: 5,
consumable: false, disposable: false,
recovers: 10) }
context "constructor" do
it "has the correct default parameters" do
expect(food.name).to eq "Food"
expect(food.price).to eq 0
expect(food.consumable).to eq true
expect(food.disposable).to eq true
expect(food.recovers).to eq 0
end
it "correctly assigns custom parameters" do
expect(magic_banana.name).to eq "Magic Banana"
expect(magic_banana.price).to eq 5
expect(magic_banana.consumable).to eq false
expect(magic_banana.disposable).to eq false
expect(magic_banana.recovers).to eq 10
end
end
context "use" do
it "heals the entity's HP in a trivial case" do
entity = Entity.new(stats: { hp: 5, max_hp: 20 })
magic_banana.use(entity, entity)
expect(entity.stats[:hp]).to eq 15
end
it "does not heal over the entity's max HP" do
entity = Entity.new(stats: { hp: 15, max_hp: 20 })
magic_banana.use(entity, entity)
expect(entity.stats[:hp]).to eq 20
end
end
it "heals another entity's HP as appropriate" do
bob = Entity.new(name: "Bob")
marge = Entity.new(name: "Marge",
stats: { hp: 5, max_hp: 20 })
magic_banana.use(bob, marge)
expect(marge.stats[:hp]).to eq 15
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/item/equippable_spec.rb | spec/goby/item/equippable_spec.rb | require 'goby'
RSpec.describe Equippable do
let(:equippable) { Class.new { extend Equippable } }
let(:entity) { Entity.new }
context "placeholder methods" do
it "forces :stat_change to be implemented" do
expect { equippable.stat_change }.to raise_error(NotImplementedError, 'An Equippable Item must implement a stat_change Hash')
end
it "forces :type to be implemented" do
expect { equippable.type }.to raise_error(NotImplementedError, 'An Equippable Item must have a type')
end
end
context "alter stats" do
before (:each) do
allow(equippable).to receive(:stat_change) { { attack: 2, defense: 3, agility: 4, max_hp: 2 } }
end
it "changes the entity's stats in the trivial case" do
equippable.alter_stats(entity, true)
expect(entity.stats[:attack]).to eq 3
expect(entity.stats[:defense]).to eq 4
expect(entity.stats[:agility]).to eq 5
expect(entity.stats[:max_hp]).to eq 3
expect(entity.stats[:hp]).to eq 1
equippable.alter_stats(entity, false)
expect(entity.stats[:attack]).to eq 1
expect(entity.stats[:defense]).to eq 1
expect(entity.stats[:agility]).to eq 1
expect(entity.stats[:max_hp]).to eq 1
expect(entity.stats[:hp]).to eq 1
end
it "does not lower stats below 1" do
equippable.alter_stats(entity, false)
expect(entity.stats[:attack]).to eq 1
expect(entity.stats[:defense]).to eq 1
expect(entity.stats[:agility]).to eq 1
expect(entity.stats[:max_hp]).to eq 1
expect(entity.stats[:hp]).to eq 1
end
it "automatically decreases hp to match max_hp" do
entity.set_stats({ max_hp: 3, hp: 2 })
equippable.alter_stats(entity, false)
expect(entity.stats[:max_hp]).to eq 1
expect(entity.stats[:hp]).to eq 1
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/item/torso_spec.rb | spec/goby/item/torso_spec.rb | require 'goby'
RSpec.describe Torso do
context "constructor" do
it "has the correct default parameters" do
torso = Torso.new
expect(torso.name).to eq "Torso"
expect(torso.price).to eq 0
expect(torso.consumable).to eq false
expect(torso.disposable).to eq true
expect(torso.type).to eq :torso
end
it "correctly assigns custom parameters" do
shirt = Torso.new(name: "Shirt",
price: 20,
consumable: true,
disposable: false,
stat_change: {attack: 2, defense: 2})
expect(shirt.name).to eq "Shirt"
expect(shirt.price).to eq 20
expect(shirt.consumable).to eq true
expect(shirt.disposable).to eq false
expect(shirt.stat_change[:attack]).to eq 2
expect(shirt.stat_change[:defense]).to eq 2
# Cannot be overwritten.
expect(shirt.type).to eq :torso
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/item/item_spec.rb | spec/goby/item/item_spec.rb | require 'goby'
RSpec.describe Item do
let(:item) { Item.new }
context "constructor" do
it "has the correct default parameters" do
expect(item.name).to eq "Item"
expect(item.price).to eq 0
expect(item.consumable).to eq true
expect(item.disposable).to eq true
end
it "correctly assigns some custom parameters" do
book = Item.new(name: "Book", disposable: false)
expect(book.name).to eq "Book"
expect(book.price).to eq 0
expect(book.consumable).to eq true
expect(book.disposable).to eq false
end
it "correctly assigns all custom parameters" do
hammer = Item.new(name: "Hammer",
price: 40,
consumable: false,
disposable: false)
expect(hammer.name).to eq "Hammer"
expect(hammer.price).to eq 40
expect(hammer.consumable).to eq false
expect(hammer.disposable).to eq false
end
end
context "use" do
it "prints the default string for the base item" do
user = Entity.new(name: "User") # who uses the item.
whom = Entity.new(name: "Whom") # on whom the item is used.
expect { item.use(user, whom) }.to output(Item::DEFAULT_USE_TEXT).to_stdout
end
end
context "equality operator" do
it "returns true for the seemingly trivial case" do
expect(item).to eq Item.new
end
it "returns true when the names are the only same parameter" do
item1 = Item.new(price: 30, consumable: true)
item2 = Item.new(price: 40, consumable: false)
expect(item1).to eq item2
end
it "returns false for items with different names" do
hammer = Item.new(name: "Hammer")
banana = Item.new(name: "Banana")
expect(hammer).not_to eq banana
end
end
context "to_s" do
it "returns the name of the Item" do
expect(item.to_s).to eq item.name
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/item/shield_spec.rb | spec/goby/item/shield_spec.rb | require 'goby'
RSpec.describe Shield do
context "constructor" do
it "has the correct default parameters" do
shield = Shield.new
expect(shield.name).to eq "Shield"
expect(shield.price).to eq 0
expect(shield.consumable).to eq false
expect(shield.disposable).to eq true
expect(shield.type).to eq :shield
end
it "correctly assigns custom parameters" do
buckler = Shield.new(name: "Buckler",
price: 20,
consumable: true,
disposable: false,
stat_change: {attack: 2, defense: 2})
expect(buckler.name).to eq "Buckler"
expect(buckler.price).to eq 20
expect(buckler.consumable).to eq true
expect(buckler.disposable).to eq false
expect(buckler.stat_change[:attack]).to eq 2
expect(buckler.stat_change[:defense]).to eq 2
# Cannot be overwritten.
expect(buckler.type).to eq :shield
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/item/legs_spec.rb | spec/goby/item/legs_spec.rb | require 'goby'
RSpec.describe Legs do
context "constructor" do
it "has the correct default parameters" do
legs = Legs.new
expect(legs.name).to eq "Legs"
expect(legs.price).to eq 0
expect(legs.consumable).to eq false
expect(legs.disposable).to eq true
expect(legs.type).to eq :legs
end
it "correctly assigns custom parameters" do
pants = Legs.new(name: "Pants",
price: 20,
consumable: true,
disposable: false,
stat_change: {attack: 2, defense: 2})
expect(pants.name).to eq "Pants"
expect(pants.price).to eq 20
expect(pants.consumable).to eq true
expect(pants.disposable).to eq false
expect(pants.stat_change[:attack]).to eq 2
expect(pants.stat_change[:defense]).to eq 2
# Cannot be overwritten.
expect(pants.type).to eq :legs
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/map/tile_spec.rb | spec/goby/map/tile_spec.rb | require 'goby'
RSpec.describe Tile do
context "constructor" do
it "has the correct default parameters" do
tile = Tile.new
expect(tile.passable).to eq true
expect(tile.seen).to eq false
expect(tile.description).to eq ""
expect(tile.events).to eq []
expect(tile.monsters).to eq []
expect(tile.graphic).to eq Tile::DEFAULT_PASSABLE
end
it "correctly assigns default graphic for non-passable tiles" do
tile = Tile.new(passable:false)
expect(tile.graphic).to eq Tile::DEFAULT_IMPASSABLE
end
it "correctly overrides the default passable graphic" do
tile = Tile.new(graphic: '$')
expect(tile.graphic).to eq '$'
end
it "correctly assigns custom parameters" do
pond = Tile.new(passable: false,
seen: true,
description: "Wet",
events: [Event.new],
monsters: [Monster.new],
graphic: '#')
expect(pond.passable).to eq false
expect(pond.seen).to eq true
expect(pond.description).to eq "Wet"
expect(pond.events).to eq [Event.new]
expect(pond.monsters).to eq [Monster.new]
expect(pond.graphic).to eq '#'
end
end
context "to s" do
it "should return two spaces when unseen" do
tile = Tile.new(seen: false, graphic: '$')
expect(tile.to_s).to eq " "
end
it "should return the graphic & one space when seen" do
tile = Tile.new(seen: true, graphic: '$')
expect(tile.to_s).to eq "$ "
end
end
context "clone" do
it "should make a deep copy of the tile" do
tile = Tile.new(description: "This is a test tile", events: [Event.new], monsters: [Monster.new])
new_tile = tile.clone
new_tile.events.pop
new_tile.monsters.pop
new_tile.description = "This is the deep-copied clone tile"
expect(tile.events.length).not_to eq(0)
expect(tile.monsters.length).not_to eq(0)
expect(tile.description).not_to eq(new_tile.description)
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/spec/goby/map/map_spec.rb | spec/goby/map/map_spec.rb | require 'goby'
RSpec.describe Map do
let(:lake) { Map.new(name: "Lake",
tiles: [ [ Tile.new, Tile.new(passable: false) ] ] ) }
context "constructor" do
it "has the correct default parameters" do
map = Map.new
expect(map.name).to eq "Map"
expect(map.tiles[0][0].passable).to be true
end
it "correctly assigns custom parameters" do
expect(lake.name).to eq "Lake"
expect(lake.tiles[0][0].passable).to be true
expect(lake.tiles[0][1].passable).to be false
end
end
context "to_s" do
it "should display a simple map" do
expect(lake.to_s).to eq("· ■ \n")
end
end
context "in bounds" do
it "returns true when the coordinates are within the map bounds" do
expect(lake.in_bounds(0,0)).to eq true
expect(lake.in_bounds(0,1)).to eq true
end
it "returns false when the coordinates are outside the map bounds" do
expect(lake.in_bounds(-1,0)).to eq false
expect(lake.in_bounds(0,-1)).to eq false
expect(lake.in_bounds(-1,-1)).to eq false
expect(lake.in_bounds(1,0)).to eq false
expect(lake.in_bounds(0,2)).to eq false
expect(lake.in_bounds(1,1)).to eq false
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby.rb | lib/goby.rb | # Import order matters.
require 'goby/scaffold'
require 'goby/extension'
require 'goby/util'
require 'goby/world_command'
require 'goby/music'
require 'goby/driver'
require 'goby/battle/battle'
require 'goby/battle/battle_command'
require 'goby/battle/attack'
require 'goby/battle/escape'
require 'goby/battle/use'
require 'goby/map/map'
require 'goby/map/tile'
require 'goby/entity/entity'
require 'goby/entity/fighter'
require 'goby/entity/monster'
require 'goby/entity/player'
require 'goby/event/event'
require 'goby/event/chest'
require 'goby/event/npc'
require 'goby/event/shop'
require 'goby/item/item'
require 'goby/item/food'
require 'goby/item/equippable'
require 'goby/item/helmet'
require 'goby/item/legs'
require 'goby/item/shield'
require 'goby/item/torso'
require 'goby/item/weapon'
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/scaffold.rb | lib/goby/scaffold.rb | module Goby
# Functions for scaffolding starter projects.
module Scaffold
# Simple starter project w/o testing.
#
# @param [String] project the project name.
def self.simple(project)
# TODO: detect existence of project folder.
# Make the directory structure.
Dir.mkdir project
dirs = [ '', 'battle', 'entity',
'event', 'item', 'map' ]
dirs.each do |dir|
Dir.mkdir "#{project}/src/#{dir}"
end
# Create the source files.
gem_location = %x[gem which goby].chomp "/lib/goby.rb\n"
files = { '.gitignore': '../gitignore',
'src/main.rb': 'main.rb',
'src/map/farm.rb': 'farm.rb' }
files.each do |dest, source|
File.open("#{project}/#{dest.to_s}", 'w') do |w|
w.write(File.read "#{gem_location}/res/scaffold/simple/#{source}")
end
end
end
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/driver.rb | lib/goby/driver.rb | require 'goby'
module Goby
include Music
include WorldCommand
# Runs the main game loop.
#
# @param [Player] player the player of the game.
def run_driver(player)
while (run_turn(player)); end
stop_music
end
private
# Clear the terminal and display the minimap.
#
# @param [Player] player the player of the game.
def clear_and_minimap(player)
system("clear") unless ENV["TEST"]
describe_tile(player)
end
# Runs a single command from the player on the world map.
#
# @param [Player] player the player of the game.
# @return [Bool] true iff the player does not want to quit.
def run_turn(player)
# Play music and re-display the minimap (when appropriate).
music = player.location.map.music
play_music(music) if music
if player.moved
clear_and_minimap(player)
player.moved = false
end
# Receive input and run the command.
input = player_input prompt: '> '
interpret_command(input, player)
return !input.eql?("quit")
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/world_command.rb | lib/goby/world_command.rb | module Goby
# Functions that handle commands on the "world map."
module WorldCommand
# String literal providing default commands.
DEFAULT_COMMANDS =
%{ Command Purpose
w (↑)
a (←) s (↓) d (→) Movement
help Show the help menu
map Print the map
inv Check inventory
status Show player status
use [item] Use the specified item
drop [item] Drop the specified item
equip [item] Equip the specified item
unequip [item] Unequip the specified item
save Save the game
quit Quit the game
}
# String literal for the special commands header.
SPECIAL_COMMANDS_HEADER = "* Special commands: "
# Message for when the player tries to drop a non-existent item.
NO_ITEM_DROP_ERROR = "You can't drop what you don't have!\n\n"
# Prints the commands that are available everywhere.
def display_default_commands
print DEFAULT_COMMANDS
end
# Prints the commands that are tile-specific.
#
# @param [Player] player the player who wants to see the special commands.
def display_special_commands(player)
events = player.location.map.tiles[player.location.coords.first][player.location.coords.second].events
if events.nonempty? && events.any? { |event| event.visible }
print SPECIAL_COMMANDS_HEADER + (events.reduce([]) do |commands, event|
commands << event.command if event.visible
commands
end.join(', ')) + "\n\n"
end
end
# Prints the default and special (tile-specific) commands.
#
# @param [Player] player the player who needs help.
def help(player)
display_default_commands
display_special_commands(player)
end
# Describes the tile to the player after each move.
#
# @param [Player] player the player who needs the tile description.
def describe_tile(player)
tile = player.location.map.tiles[player.location.coords.first][player.location.coords.second]
events = tile.events
player.print_minimap
print "#{tile.description}\n\n"
display_special_commands(player)
end
# Handles the player's input and executes the appropriate action.
#
# @param [String] command the player's entire command input.
# @param [Player] player the player using the command.
def interpret_command(command, player)
return if command.eql?("quit")
words = command.split()
# Default commands that take multiple "arguments" (words).
if (words.size > 1)
# TODO: this chunk could be a private function.
# Determine the name of the second "argument."
name = words[1]
for i in 2..(words.size - 1) do
name << " " << words[i]
end
# Determine the appropriate command to use.
# TODO: some of those help messages should be string literals.
if words[0].casecmp("drop").zero?
index = player.has_item(name)
if index && !player.inventory[index].first.disposable
print "You cannot drop that item.\n\n"
elsif index
# TODO: Perhaps the player should be allowed to specify
# how many of the Item to drop.
item = player.inventory[index].first
player.remove_item(item, 1)
print "You have dropped #{item}.\n\n"
else
print NO_ITEM_DROP_ERROR
end
return
elsif words[0].casecmp("equip").zero?
player.equip_item(name); return
elsif words[0].casecmp("unequip").zero?
player.unequip_item(name); return
elsif words[0].casecmp("use").zero?
player.use_item(name, player); return
end
end
# TODO: map command input to functions? Maybe this can
# also be done with the multiple-word commands?
if command.casecmp("w").zero?
player.move_up; return
elsif command.casecmp("a").zero?
player.move_left; return
elsif command.casecmp("s").zero?
player.move_down; return
elsif command.casecmp("d").zero?
player.move_right; return
elsif command.casecmp("help").zero?
help(player); return
elsif command.casecmp("map").zero?
player.print_map; return
elsif command.casecmp("inv").zero?
player.print_inventory; return
elsif command.casecmp("status").zero?
player.print_status; return
elsif command.casecmp("save").zero?
save_game(player, "player.yaml"); return
end
# Other commands.
events = player.location.map.tiles[player.location.coords.first][player.location.coords.second].events
events.each do |event|
if (event.visible && words[0] && words[0].casecmp(event.command).zero?)
event.run(player)
return
end
end
# Text for incorrect commands.
# TODO: Add string literal for this.
puts "That isn't an available command at this time."
print "Type 'help' for a list of available commands.\n\n"
end
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/music.rb | lib/goby/music.rb | module Goby
# Methods for playing/stopping background music (BGM).
module Music
# Specify the program that should play the music.
# Without overwriting, it is set to a default (see @@program).
#
# @param [String] name the name of the music-playing program.
def set_program(name)
@@program = name
end
# Specify if music should play or not.
# May be useful to stop/start music for dramatic effect.
#
# @param [Boolean] flag true iff music should play.
def set_playback(flag)
@@playback = flag
end
# Starts playing the music from the specified file.
# This has only been tested on Ubuntu w/ .mid files.
#
# @param [String] filename the file containing the music.
def play_music(filename)
return unless @@playback
if (filename != @@file)
stop_music
@@file = filename
# This thread loops the music until one calls #stop_music.
@@thread = Thread.new {
while (true)
Process.wait(@@pid) if @@pid
@@pid = Process.spawn("#{@@program} #{filename}", :out=>"/dev/null")
end
}
end
end
# Kills the music process and the looping thread.
def stop_music
return unless @@playback
Process.kill("SIGKILL", @@pid) if @@pid
@@pid = nil
@@thread.kill if @@thread
@@thread = nil
@@file = nil
end
@@file = nil
@@pid = nil
@@playback = false
@@program = "timidity"
@@thread = nil
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/extension.rb | lib/goby/extension.rb | require 'set'
# Provides additional methods for Array.
class Array
# Returns true iff the array is not empty.
def nonempty?
return !empty?
end
end
# Provides additional methods for Integer.
class Integer
# Returns true if the integer is a positive number.
def positive?
return self > 0
end
# Returns true if the integer is not a positive number.
def nonpositive?
return self <= 0
end
# Returns true if the integer is a negative number.
def negative?
return self < 0
end
# Returns true if the integer is not a negative number.
def nonnegative?
return self >= 0
end
end
# Provides additional methods for String.
class String
# Set of all known positive responses.
POSITIVE_RESPONSES = Set.new [ "ok", "okay", "sure", "y", "ye", "yeah", "yes" ]
# Set of all known negative responses.
NEGATIVE_RESPONSES = Set.new [ "n", "nah", "no", "nope" ]
# Returns true iff the string is affirmative/positive.
def is_positive?
return POSITIVE_RESPONSES.include?(self)
end
# Returns true iff the string is negatory/negative.
def is_negative?
return NEGATIVE_RESPONSES.include?(self)
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/util.rb | lib/goby/util.rb | require 'readline'
require 'yaml'
# Collection of classes, modules, and functions that make
# up the Goby framework.
module Goby
# Stores a pair of values as a couple.
class C
# Syntactic sugar to create a couple using C[a, b]
#
# @param [Object] first the first object in the pair.
# @param [Object] second the second object in the pair.
def self.[](first, second)
C.new(first, second)
end
# @param [Object] first the first object in the pair.
# @param [Object] second the second object in the pair.
def initialize(first, second)
@first = first
@second = second
end
# @param [C] rhs the couple on the right.
def ==(rhs)
return ((@first == rhs.first) && (@second == rhs.second))
end
attr_accessor :first, :second
end
# The combination of a map and y-x coordinates,
# which determine a specific position/location on the map.
class Location
# Location constructor.
#
# @param [Map] map the map component.
# @param [C(Integer, Integer)] coords a pair of y-x coordinates.
def initialize(map, coords)
@map = map
@coords = coords
end
attr_reader :map, :coords
end
# Simple player input script.
#
# @param [Boolean] lowercase mark true if response should be returned lowercase.
# @param [String] prompt the prompt for the user to input information.
# @param [Boolean] doublespace mark false if extra space should not be printed after input.
def player_input(lowercase: true, prompt: '', doublespace: true)
# When using Readline, rspec actually prompts the user for input, freezing the tests.
print prompt
input = (ENV['TEST'] == 'rspec') ? gets.chomp : Readline.readline(" \b", false)
puts "\n" if doublespace
if ((input.size > 1) and (input != Readline::HISTORY.to_a[-1]))
Readline::HISTORY.push(input)
end
return lowercase ? input.downcase : input
end
# Prints text as if it were being typed.
#
# @param [String] message the message to type out.
def type(message)
# Amount of time to sleep between printing character.
time = ENV['TEST'] ? 0 : 0.015
# Sleep between printing of each char.
message.split("").each do |i|
sleep(time) if time.nonzero?
print i
end
end
# Serializes the player object into a YAML file and saves it
#
# @param [Player] player the player object to be saved.
# @param [String] filename the name under which to save the file.
def save_game(player, filename)
# Set 'moved' to true so we see minimap on game load.
player.moved = true
player_data = YAML::dump(player)
player.moved = false
File.open(filename, "w") do |file|
file.puts player_data
end
print "Successfully saved the game!\n\n"
return
end
# Reads and check the save file and parses into the player object
#
# @param [String] filename the file containing the save data.
# @return [Player] the player corresponding to the save data.
def load_game(filename)
begin
player = YAML.load_file(filename)
return player
rescue
return nil
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/entity/monster.rb | lib/goby/entity/monster.rb | require 'goby'
module Goby
# An Entity controlled by the CPU. Used for battle against Players.
class Monster < Entity
include Fighter
# @param [String] name the name.
# @param [Hash] stats hash of stats
# @param [[C(Item, Integer)]] inventory an array of pairs of items and their respective amounts.
# @param [Integer] gold the max amount of gold that can be rewarded to the opponent.
# @param [[BattleCommand]] battle_commands the commands that can be used in battle.
# @param [Hash] outfit the coolection of equippable items currently worn.
# @param [[C(Item, Integer)]] treasures an array of treasures and the likelihood of receiving each.
def initialize(name: "Monster", stats: {}, inventory: [], gold: 0, battle_commands: [], outfit: {},
treasures: [])
super(name: name, stats: stats, inventory: inventory, gold: gold, outfit: outfit)
@treasures = treasures
# Find the total number of treasures in the distribution.
@total_treasures = 0
@treasures.each do |pair|
@total_treasures += pair.second
end
add_battle_commands(battle_commands)
end
# Provides a deep copy of the monster. This is necessary since
# the monster can use up its items in battle.
#
# @return [Monster] deep copy of the monster.
def clone
# Create a shallow copy for most of the variables.
monster = super
# Reset the copy's inventory.
monster.inventory = []
# Create a deep copy of the inventory.
@inventory.each do |pair|
monster.inventory << C[pair.first.clone, pair.second]
end
return monster
end
# What to do if the Monster dies in a Battle.
def die
# Do nothing special.
end
# What to do if a Monster wins a Battle.
def handle_victory(fighter)
# Take some of the Player's gold.
fighter.sample_gold
end
# The amount gold given to a victorious Entity after losing a battle
#
# @return[Integer] the amount of gold to award the victorious Entity
def sample_gold
# Sample a random amount of gold.
Random.rand(0..@gold)
end
# Chooses a treasure based on the sample distribution.
#
# @return [Item] the reward for the victor of the battle (or nil - no treasure).
def sample_treasures
# Return nil for no treasures.
return if total_treasures.zero?
# Choose uniformly from the total given above.
index = Random.rand(total_treasures)
# Choose the treasure based on the distribution.
total = 0
treasures.each do |pair|
total += pair.second
return pair.first if index < total
end
end
attr_reader :treasures, :total_treasures
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/entity/fighter.rb | lib/goby/entity/fighter.rb | require 'goby'
module Goby
# Methods and variables for something that can battle with another Fighter.
module Fighter
# Exception thrown when a non-Fighter tries to enter battle.
class UnfightableException < Exception
end
# The function that handles how an Fighter behaves after losing a battle.
# Subclasses must override this function.
def die
raise(NotImplementedError, 'A Fighter must know how to die.')
end
# Handles how a Fighter behaves after winning a battle.
# Subclasses must override this function.
#
# @param [Fighter] fighter the Fighter who lost the battle.
def handle_victory(fighter)
raise(NotImplementedError, 'A Fighter must know how to handle victory.')
end
# The function that returns the treasure given by a Fighter after losing a battle.
#
# @return [Item] the reward for the victor of the battle (or nil - no treasure).
def sample_treasures
raise(NotImplementedError, 'A Fighter must know whether it returns treasure or not after losing a battle.')
end
# The function that returns the gold given by a Fighter after losing a battle.
#
# @return[Integer] the amount of gold to award the victorious Fighter
def sample_gold
raise(NotImplementedError, 'A Fighter must return some gold after losing a battle.')
end
# Adds the specified battle command to the Fighter's collection.
#
# @param [BattleCommand] command the command being added.
def add_battle_command(command)
battle_commands.push(command)
# Maintain sorted battle commands.
battle_commands.sort! { |x, y| x.name <=> y.name }
end
# Adds the specified battle commands to the Fighter's collection.
#
# @param [Array] battle_commands the commands being added.
def add_battle_commands(battle_commands)
battle_commands.each { |command| add_battle_command(command) }
end
# Engages in battle with the specified Entity.
#
# @param [Entity] entity the opponent of the battle.
def battle(entity)
unless entity.class.included_modules.include?(Fighter)
raise(UnfightableException, "You can't start a battle with an Entity of type #{entity.class} as it doesn't implement the Fighter module")
end
system("clear") unless ENV['TEST']
battle = Battle.new(self, entity)
winner = battle.determine_winner
if winner.equal?(self)
handle_victory(entity)
entity.die
elsif winner.equal?(entity)
entity.handle_victory(self)
die
end
end
# Returns the Array for BattleCommands available for the Fighter.
# Sets @battle_commands to an empty Array if it's the first time it's called.
#
# @return [Array] array of the available BattleCommands for the Fighter.
def battle_commands
@battle_commands ||= []
@battle_commands
end
# Determines how the Fighter should select an attack in battle.
# Override this method for control over this functionality.
#
# @return [BattleCommand] the chosen battle command.
def choose_attack
battle_commands[Random.rand(@battle_commands.length)]
end
# Determines how the Fighter should select the item and on whom
# during battle (Use command). Return nil on error.
#
# @param [Fighter] enemy the opponent in battle.
# @return [C(Item, Fighter)] the item and on whom it is to be used.
def choose_item_and_on_whom(enemy)
item = @inventory[Random.rand(@inventory.length)].first
whom = [self, enemy].sample
return C[item, whom]
end
# Returns the index of the specified command, if it exists.
#
# @param [BattleCommand, String] cmd the battle command (or its name).
# @return [Integer] the index of an existing command. Otherwise nil.
def has_battle_command(cmd)
battle_commands.each_with_index do |command, index|
return index if command.name.casecmp(cmd.to_s).zero?
end
return
end
# Removes the battle command, if it exists, from the Fighter's collection.
#
# @param [BattleCommand, String] command the command being removed.
def remove_battle_command(command)
index = has_battle_command(command)
battle_commands.delete_at(index) if index
end
# Prints the available battle commands.
#
# @param [String] header the text to output as a heading for the list of battle commands.
def print_battle_commands(header = "Battle Commands:")
puts header
battle_commands.each do |command|
print "❊ #{command.name}\n"
end
print "\n"
end
# Appends battle commands to the end of the Fighter print_status output.
def print_status
super
print_battle_commands unless battle_commands.empty?
end
# Uses the agility levels of the two Fighters to determine who should go first.
#
# @param [Fighter] fighter the opponent with whom the calling Fighter is competing.
# @return [Boolean] true when calling Fighter should go first. Otherwise, false.
def sample_agilities(fighter)
sum = fighter.stats[:agility] + stats[:agility]
Random.rand(sum) < stats[:agility]
end
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/entity/entity.rb | lib/goby/entity/entity.rb | require 'goby'
module Goby
# Provides the ability to fight, equip/unequip weapons & armor,
# and carry items & gold.
class Entity
# Error when the entity specifies a non-existent item.
NO_SUCH_ITEM_ERROR = "What?! You don't have THAT!\n\n"
# Error when the entity specifies an item not equipped.
NOT_EQUIPPED_ERROR = "You are not equipping THAT!\n\n"
# @param [String] name the name.
# @param [Hash] stats hash of stats
# @option stats [Integer] :max_hp maximum health points. Set to be positive.
# @option stats [Integer] :hp current health points. Set to be nonnegative.
# @option stats [Integer] :attack strength in battle. Set to be positive.
# @option stats [Integer] :defense protection from attacks. Set to be positive.
# @option stats [Integer] :agility speed of commands in battle. Set to be positive.
# @param [[C(Item, Integer)]] inventory a list of pairs of items and their respective amounts.
# @param [Integer] gold the currency used for economical transactions.
# @param [Hash] outfit the collection of equippable items currently worn.
def initialize(name: "Entity", stats: {}, inventory: [], gold: 0, outfit: {})
@name = name
set_stats(stats)
@inventory = inventory
set_gold(gold)
# See its attr_accessor below.
@outfit = {}
outfit.each do |type,value|
value.equip(self)
end
# This should only be switched to true during battle.
@escaped = false
end
# Adds the given amount of gold.
#
# @param [Integer] gold the amount of gold to add.
def add_gold(gold)
@gold += gold
check_and_set_gold
end
# Adds the item and the given amount to the inventory.
#
# @param [Item] item the item being added.
# @param [Integer] amount the amount of the item to add.
def add_item(item, amount = 1)
# Increase the amount if the item already exists in the inventory.
@inventory.each do |couple|
if (couple.first == item)
couple.second += amount
return
end
end
# If not already in the inventory, push a couple.
@inventory.push(C[item, amount])
end
# Adds the specified gold and treasures to the inventory.
#
# @param [Integer] gold the amount of gold.
# @param [[Item]] treasures the list of treasures.
def add_loot(gold, treasures)
type("Loot: ")
if ((gold.positive?) || (treasures && treasures.any?))
print "\n"
if gold.positive?
type("* #{gold} gold\n")
add_gold(gold)
end
if treasures && treasures.any?
treasures.each do |treasure|
unless treasure.nil?
type("* #{treasure.name}\n")
add_item(treasure)
end
end
end
print "\n"
else
type("nothing!\n\n")
end
end
# Removes all items from the entity's inventory.
def clear_inventory
while @inventory.size.nonzero?
@inventory.pop
end
end
# Equips the specified item to the entity's outfit.
#
# @param [Item, String] item the item (or its name) to equip.
def equip_item(item)
index = has_item(item)
if index
actual_item = inventory[index].first
# Checks for Equippable without importing the file.
if (defined? actual_item.equip)
actual_item.equip(self)
# Equipping the item will always remove it from the entity's inventory.
remove_item(actual_item)
else
print "#{actual_item.name} cannot be equipped!\n\n"
end
else
print NO_SUCH_ITEM_ERROR
end
end
# Returns the index of the specified item, if it exists.
#
# @param [Item, String] item the item (or its name).
# @return [Integer] the index of an existing item. Otherwise nil.
def has_item(item)
inventory.each_with_index do |couple, index|
return index if couple.first.name.casecmp(item.to_s).zero?
end
return
end
# Prints the inventory in a nice format.
def print_inventory
print "Current gold in pouch: #{@gold}.\n\n"
if @inventory.empty?
print "#{@name}'s inventory is empty!\n\n"
return
end
puts "#{@name}'s inventory:"
@inventory.each do |couple|
puts "* #{couple.first.name} (#{couple.second})"
end
print "\n"
end
# Prints the status in a nice format.
# TODO: encapsulate print_stats and print_equipment in own functions.
def print_status
puts "Stats:"
puts "* HP: #{@stats[:hp]}/#{@stats[:max_hp]}"
puts "* Attack: #{@stats[:attack]}"
puts "* Defense: #{@stats[:defense]}"
puts "* Agility: #{@stats[:agility]}"
print "\n"
puts "Equipment:"
print "* Weapon: "
puts @outfit[:weapon] ? "#{@outfit[:weapon].name}" : "none"
print "* Shield: "
puts @outfit[:shield] ? "#{@outfit[:shield].name}" : "none"
print "* Helmet: "
puts @outfit[:helmet] ? "#{@outfit[:helmet].name}" : "none"
print "* Torso: "
puts @outfit[:torso] ? "#{@outfit[:torso].name}" : "none"
print "* Legs: "
puts @outfit[:legs] ? "#{@outfit[:legs].name}" : "none"
print "\n"
end
# Removes up to the amount of gold given in the argument.
# Entity's gold will not be less than zero.
#
# @param [Integer] gold the amount of gold to remove.
def remove_gold(gold)
@gold -= gold
check_and_set_gold
end
# Removes the item, if it exists, and, at most, the given amount from the inventory.
#
# @param [Item] item the item being removed.
# @param [Integer] amount the amount of the item to remove.
def remove_item(item, amount = 1)
# Decrease the amount if the item already exists in the inventory.
@inventory.each_with_index do |couple, index|
if (couple.first == item)
couple.second -= amount
# Delete the item if the amount becomes non-positive.
@inventory.delete_at(index) if couple.second.nonpositive?
return
end
end
end
# Sets the Entity's gold to the number in the argument.
# Only nonnegative numbers are accepted.
#
# @param [Integer] gold the amount of gold to set.
def set_gold(gold)
@gold = gold
check_and_set_gold
end
# Sets stats
#
# @param [Hash] passed_in_stats value pairs of stats
# @option passed_in_stats [Integer] :max_hp maximum health points. Set to be positive.
# @option passed_in_stats [Integer] :hp current health points. Set to be nonnegative.
# @option passed_in_stats [Integer] :attack strength in battle. Set to be positive.
# @option passed_in_stats [Integer] :defense protection from attacks. Set to be positive.
# @option passed_in_stats [Integer] :agility speed of commands in battle. Set to be positive.
def set_stats(passed_in_stats)
current_stats = @stats || { max_hp: 1, hp: nil, attack: 1, defense: 1, agility: 1 }
constructed_stats = current_stats.merge(passed_in_stats)
# Set hp to max_hp if hp not specified
constructed_stats[:hp] = constructed_stats[:hp] || constructed_stats[:max_hp]
# hp should not be greater than max_hp
constructed_stats[:hp] = [constructed_stats[:hp], constructed_stats[:max_hp]].min
#ensure hp is at least 0
constructed_stats[:hp] = constructed_stats[:hp] > 0 ? constructed_stats[:hp] : 0
#ensure all other stats > 0
constructed_stats.each do |key,value|
if [:max_hp, :attack, :defense, :agility].include?(key)
constructed_stats[key] = value.nonpositive? ? 1 : value
end
end
@stats = constructed_stats
end
# getter for stats
#
# @return [Object]
def stats
# attr_reader makes sure stats cannot be set via stats=
# freeze makes sure that stats []= cannot be used
@stats.freeze
end
# Unequips the specified item from the entity's outfit.
#
# @param [Item, String] item the item (or its name) to unequip.
def unequip_item(item)
pair = @outfit.detect { |type, value| value.name.casecmp(item.to_s).zero? }
if pair
# On a successful find, the "detect" method always returns
# an array of length 2; thus, the following line should not fail.
item = pair[1]
item.unequip(self)
add_item(item)
else
print NOT_EQUIPPED_ERROR
end
end
# Uses the item, if it exists, on the specified entity.
#
# @param [Item, String] item the item (or its name) to use.
# @param [Entity] entity the entity on which to use the item.
def use_item(item, entity)
index = has_item(item)
if index
actual_item = inventory[index].first
actual_item.use(self, entity)
remove_item(actual_item) if actual_item.consumable
else
print NO_SUCH_ITEM_ERROR
end
end
# @param [Entity] rhs the entity on the right.
def ==(rhs)
@name == rhs.name
end
attr_accessor :escaped, :inventory, :name
attr_reader :gold, :outfit
private
# Safety function that prevents gold
# from decreasing below 0.
def check_and_set_gold
@gold = 0 if @gold.negative?
end
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/entity/player.rb | lib/goby/entity/player.rb | require 'goby'
module Goby
# Extends upon Entity by providing a location in the
# form of a Map and a pair of y-x location. Overrides
# some methods to accept input during battle.
class Player < Entity
include WorldCommand
include Fighter
# Default map when no "good" map & location specified.
DEFAULT_MAP = Map.new(tiles: [[Tile.new]])
# Default location when no "good" map & location specified.
DEFAULT_COORDS = C[0, 0]
# distance in each direction that tiles are acted upon
# used in: update_map, print_minimap
VIEW_DISTANCE = 2
# @param [String] name the name.
# @param [Hash] stats hash of stats
# @param [[C(Item, Integer)]] inventory a list of pairs of items and their respective amounts.
# @param [Integer] gold the currency used for economical transactions.
# @param [[BattleCommand]] battle_commands the commands that can be used in battle.
# @param [Hash] outfit the collection of equippable items currently worn.
# @param [Location] location the place at which the player should start.
# @param [Location] respawn_location the place at which the player respawns.
def initialize(name: "Player", stats: {}, inventory: [], gold: 0, battle_commands: [],
outfit: {}, location: nil, respawn_location: nil)
super(name: name, stats: stats, inventory: inventory, gold: gold, outfit: outfit)
@saved_maps = Hash.new
# Ensure that the map and the location are valid.
new_map = DEFAULT_MAP
new_coords = DEFAULT_COORDS
if (location && location.map && location.coords)
y = location.coords.first; x = location.coords.second
if (location.map.in_bounds(y, x) && location.map.tiles[y][x].passable)
new_map = location.map
new_coords = location.coords
end
end
add_battle_commands(battle_commands)
move_to(Location.new(new_map, new_coords))
@respawn_location = respawn_location || @location
@saved_maps = Hash.new
end
# Uses player input to determine the battle command.
#
# @return [BattleCommand] the chosen battle command.
def choose_attack
print_battle_commands(header = "Choose an attack:")
input = player_input
index = has_battle_command(input)
#input error loop
while !index
puts "You don't have '#{input}'"
print_battle_commands(header = "Try one of these:")
input = player_input
index = has_battle_command(input)
end
return @battle_commands[index]
end
# Requires input to select item and on whom to use it
# during battle (Use command). Return nil on error.
#
# @param [Entity] enemy the opponent in battle.
# @return [C(Item, Entity)] the item and on whom it is to be used.
def choose_item_and_on_whom(enemy)
index = nil
item = nil
# Choose the item to use.
while !index
print_inventory
puts "Which item would you like to use?"
input = player_input prompt: "(or type 'pass' to forfeit the turn): "
return if (input.casecmp("pass").zero?)
index = has_item(input)
if !index
print NO_SUCH_ITEM_ERROR
else
item = @inventory[index].first
end
end
whom = nil
# Choose on whom to use the item.
while !whom
puts "On whom will you use the item (#{@name} or #{enemy.name})?"
input = player_input prompt: "(or type 'pass' to forfeit the turn): "
return if (input.casecmp("pass").zero?)
if (input.casecmp(@name).zero?)
whom = self
elsif (input.casecmp(enemy.name).zero?)
whom = enemy
else
print "What?! Choose either #{@name} or #{enemy.name}!\n\n"
end
end
return C[item, whom]
end
# Sends the player back to a safe location,
# halves its gold, and restores HP.
def die
sleep(2) unless ENV['TEST']
move_to(@respawn_location)
type("After being knocked out in battle,\n")
type("you wake up in #{@location.map.name}.\n\n")
sleep(2) unless ENV['TEST']
# Heal the player.
set_stats(hp: @stats[:max_hp])
end
# Retrieve loot obtained by defeating the enemy.
#
# @param [Fighter] fighter the Fighter who lost the battle.
def handle_victory(fighter)
type("#{@name} defeated the #{fighter.name}!\n")
gold = fighter.sample_gold
treasure = fighter.sample_treasures
add_loot(gold, [treasure]) unless gold.nil? && treasure.nil?
type("Press enter to continue...")
player_input
end
# Moves the player down. Increases 'y' coordinate by 1.
def move_down
down_tile = C[@location.coords.first + 1, @location.coords.second]
move_to(Location.new(@location.map, down_tile))
end
# Moves the player left. Decreases 'x' coordinate by 1.
def move_left
left_tile = C[@location.coords.first, @location.coords.second - 1]
move_to(Location.new(@location.map, left_tile))
end
# Moves the player right. Increases 'x' coordinate by 1.
def move_right
right_tile = C[@location.coords.first, @location.coords.second + 1]
move_to(Location.new(@location.map, right_tile))
end
# Safe setter function for location and map.
#
# @param [Location] location the new location.
def move_to(location)
map = location.map
y = location.coords.first
x = location.coords.second
# Prevents operations on nil.
return if map.nil?
# Save the map.
@saved_maps[@location.map.name] = @location.map if @location
# Even if the player hasn't moved, we still change to true.
# This is because we want to re-display the minimap anyway.
@moved = true
# Prevents moving onto nonexistent and impassable tiles.
return if !(map.in_bounds(y, x) && map.tiles[y][x].passable)
# Update the location and surrounding tiles.
@location = Location.new(
@saved_maps[map.name] ? @saved_maps[map.name] : map, location.coords)
update_map
tile = @location.map.tiles[y][x]
unless tile.monsters.empty?
# 50% chance to encounter monster (TODO: too high?)
if [true, false].sample
clone = tile.monsters[Random.rand(0..(tile.monsters.size-1))].clone
battle(clone)
end
end
end
# Moves the player up. Decreases 'y' coordinate by 1.
def move_up
up_tile = C[@location.coords.first - 1, @location.coords.second]
move_to(Location.new(@location.map, up_tile))
end
# Prints the map in regards to what the player has seen.
# Additionally, provides current location and the map's name.
def print_map
# Provide some spacing from the edge of the terminal.
3.times { print " " };
print @location.map.name + "\n\n"
@location.map.tiles.each_with_index do |row, r|
# Provide spacing for the beginning of each row.
2.times { print " " }
row.each_with_index do |tile, t|
print_tile(C[r, t])
end
print "\n"
end
print "\n"
# Provide some spacing to center the legend.
3.times { print " " }
# Prints the legend.
print "¶ - #{@name}'s\n location\n\n"
end
# Prints a minimap of nearby tiles (using VIEW_DISTANCE).
def print_minimap
print "\n"
for y in (@location.coords.first-VIEW_DISTANCE)..(@location.coords.first+VIEW_DISTANCE)
# skip to next line if out of bounds from above map
next if y.negative?
# centers minimap
10.times { print " " }
for x in (@location.coords.second-VIEW_DISTANCE)..(@location.coords.second+VIEW_DISTANCE)
# Prevents operations on nonexistent tiles.
print_tile(C[y, x]) if (@location.map.in_bounds(y, x))
end
# new line if this row is not out of bounds
print "\n" if y < @location.map.tiles.size
end
print "\n"
end
# Prints the tile based on the player's location.
#
# @param [C(Integer, Integer)] coords the y-x location of the tile.
def print_tile(coords)
if ((@location.coords.first == coords.first) && (@location.coords.second == coords.second))
print "¶ "
else
print @location.map.tiles[coords.first][coords.second].to_s
end
end
# Updates the 'seen' attributes of the tiles on the player's current map.
#
# @param [Location] location to update seen attribute for tiles on the map.
def update_map(location = @location)
for y in (location.coords.first-VIEW_DISTANCE)..(location.coords.first+VIEW_DISTANCE)
for x in (location.coords.second-VIEW_DISTANCE)..(location.coords.second+VIEW_DISTANCE)
@location.map.tiles[y][x].seen = true if (@location.map.in_bounds(y, x))
end
end
end
# The treasure given by a Player after losing a battle.
#
# @return [Item] the reward for the victor of the battle (or nil - no treasure).
def sample_treasures
nil
end
# Returns the gold given to a victorious Entity after losing a battle
# and deducts the figure from the Player's total as necessary
#
# @return[Integer] the amount of gold to award the victorious Entity
def sample_gold
gold_lost = 0
# Reduce gold if the player has any.
if @gold.positive?
type("Looks like you lost some gold...\n\n")
gold_lost = @gold/2
@gold -= gold_lost
end
gold_lost
end
attr_reader :location, :saved_maps
attr_accessor :moved, :respawn_location
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/event/event.rb | lib/goby/event/event.rb | module Goby
# A Player can interact with these on the Map.
class Event
# The default text for when the event doesn't do anything.
DEFAULT_RUN_TEXT = "Nothing happens.\n\n"
# @param [String] command the command to activate the event.
# @param [Integer] mode convenient way for an event to have multiple actions.
# @param [Boolean] visible true when the event can be seen/activated.
def initialize(command: "event", mode: 0, visible: true)
@command = command
@mode = mode
@visible = visible
end
# The function that runs when the player activates the event.
# Override this function for subclasses.
#
# @param [Player] player the one activating the event.
def run(player)
print DEFAULT_RUN_TEXT
end
# @param [Event] rhs the event on the right.
def ==(rhs)
@command == rhs.command
end
# Specify the command in the subclass.
attr_accessor :command, :mode, :visible
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/event/npc.rb | lib/goby/event/npc.rb | require 'goby'
module Goby
# A non-player character with whom the player can interact.
# Always activated with the 'talk' command.
class NPC < Event
# @param [String] name the name.
# @param [Integer] mode convenient way for a NPC to have multiple actions.
# @param [Boolean] visible whether the NPC can be seen/activated.
def initialize(name: "NPC", mode: 0, visible: true)
super(mode: mode, visible: visible)
@name = name
@command = "talk"
end
# The function that runs when the player speaks to the NPC.
#
# @param [Player] player the one speaking to the NPC.
def run(player)
say "Hello!\n\n"
end
# Function that allows NPCs to output a string of words.
#
# @param [String] words string of words for the NPC to speak.
def say(words)
type "#{name}: #{words}"
end
attr_accessor :name
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/event/chest.rb | lib/goby/event/chest.rb | require 'goby'
module Goby
# A chest containing gold and/or items.
class Chest < Event
# @param [Integer] mode convenient way for a chest to have multiple actions.
# @param [Boolean] visible whether the chest can be seen/activated.
# @param [Integer] gold the amount of gold in this chest.
# @param [[Item]] treasures the items found in this chest.
def initialize(mode: 0, visible: true, gold: 0, treasures: [])
super(mode: mode, visible: visible)
@command = "open"
@gold = gold
@treasures = treasures
end
# The function that runs when the player opens the chest.
#
# @param [Player] player the one opening the chest.
def run(player)
type("You open the treasure chest...\n\n")
sleep(1) unless ENV['TEST']
player.add_loot(@gold, @treasures)
@visible = false
end
attr_reader :gold, :treasures
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/event/shop.rb | lib/goby/event/shop.rb | require 'goby'
module Goby
# Allows a player to buy and sell Items.
class Shop < Event
# Message for when the shop has nothing to sell.
NO_ITEMS_MESSAGE = "Sorry, we're out of stock right now!\n\n"
# Message for when the player has nothing to sell.
NOTHING_TO_SELL = "You have nothing to sell!\n\n"
# Introductory greeting at the shop.
WARES_MESSAGE = "Please take a look at my wares.\n\n"
# @param [String] name the name.
# @param [Integer] mode convenient way for a shop to have multiple actions.
# @param [Boolean] visible whether the shop can be seen/activated.
# @param [[Item]] items an array of items that the shop sells.
def initialize(name: "Shop", mode: 0, visible: true, items: [])
super(mode: mode, visible: visible)
@name = name
@command = "shop"
@items = items
end
# The chain of events for buying an item (w/ error checking).
#
# @param [Player] player the player trying to buy an item.
def buy(player)
print_items
return if @items.empty?
print "What would you like (or none)?: "
name = player_input
index = has_item(name)
# The player does not want to buy an item.
return if name.casecmp("none").zero?
if index.nil? # non-existent item.
print "I don't have #{name}!\n\n"
return
end
# The specified item exists in the shop's inventory.
item = @items[index]
print "How many do you want?: "
amount_to_buy = player_input
total_cost = amount_to_buy.to_i * item.price
if total_cost > player.gold # not enough gold.
puts "You don't have enough gold!"
print "You only have #{player.gold}, but you need #{total_cost}!\n\n"
return
elsif amount_to_buy.to_i < 1 # non-positive amount.
puts "Is this some kind of joke?"
print "You need to request a positive amount!\n\n"
return
end
# The player specifies a positive amount.
player.remove_gold(total_cost)
player.add_item(item, amount_to_buy.to_i)
print "Thank you for your patronage!\n\n"
end
# Returns the index of the specified item, if it exists.
#
# @param [String] name the item's name.
# @return [Integer] the index of an existing item. Otherwise nil.
def has_item(name)
@items.each_with_index do |item, index|
return index if item.name.casecmp(name).zero?
end
return
end
# Displays the player's current amount of gold
# and a greeting. Inquires about next action.
#
# @param [Player] player the player interacting with the shop.
# @return [String] the player's input.
def print_gold_and_greeting(player)
puts "Current gold in your pouch: #{player.gold}."
print "Would you like to buy, sell, or exit?: "
input = player_input doublespace: false
print "\n"
return input
end
# Displays a formatted list of the Shop's items
# or a message signaling there is nothing to sell.
def print_items
if @items.empty?
print NO_ITEMS_MESSAGE
else
print WARES_MESSAGE
@items.each { |item| puts "#{item.name} (#{item.price} gold)" }
print "\n"
end
end
# The amount for which the shop will purchase the item.
#
# @param [Item] item the item in question.
# @return [Integer] the amount for which to purchase.
def purchase_price(item)
item.price / 2
end
# The default shop experience.
#
# @param [Player] player the player interacting with the shop.
def run(player)
# Initial greeting.
puts "Welcome to #{@name}."
input = print_gold_and_greeting(player)
while input.casecmp("exit").nonzero?
if input.casecmp("buy").zero?
buy(player)
elsif input.casecmp("sell").zero?
sell(player)
end
input = print_gold_and_greeting(player)
end
print "#{player.name} has left #{@name}.\n\n"
end
# The chain of events for selling an item (w/ error checking).
#
# @param [Player] player the player trying to sell an item.
def sell(player)
# The player has nothing to sell.
if player.inventory.empty?
print NOTHING_TO_SELL
return
end
player.print_inventory
print "What would you like to sell? (or none): "
input = player_input
index = player.has_item(input)
# The player does not want to sell an item.
return if input.casecmp("none").zero?
if index.nil? # non-existent item.
print "You can't sell what you don't have.\n\n"
return
end
item = player.inventory[index].first
item_count = player.inventory[index].second
unless item.disposable # non-disposable item (cannot sell/drop).
print "You cannot sell that item.\n\n"
return
end
puts "I'll buy that for #{purchase_price(item)} gold."
print "How many do you want to sell?: "
amount_to_sell = player_input.to_i
if amount_to_sell > item_count # more than in the inventory.
print "You don't have that many to sell!\n\n"
return
elsif amount_to_sell < 1 # non-positive amount specified.
puts "Is this some kind of joke?"
print "You need to sell a positive amount!\n\n"
return
end
player.add_gold(purchase_price(item) * amount_to_sell)
player.remove_item(item, amount_to_sell)
print "Thank you for your patronage!\n\n"
end
attr_accessor :name, :items
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/battle/battle_command.rb | lib/goby/battle/battle_command.rb | module Goby
# Commands that are used in the battle system. At each turn,
# an Entity specifies which BattleCommand to use.
class BattleCommand
# Text for when the battle command does nothing.
NO_ACTION = "Nothing happens.\n\n"
# @param [String] name the name.
def initialize(name: "BattleCommand")
@name = name
end
# This method can prevent the user from using this command
# based on a defined condition. Override for subclasses.
#
# @param [Entity] user the one who is using the command.
# @return [Boolean] true iff the command cannot be used.
def fails?(user)
false
end
# The process that runs when this command is used in battle.
# Override this function for subclasses.
#
# @param [Entity] user the one who is using the command.
# @param [Entity] entity the one on whom the command is used.
def run(user, entity)
print NO_ACTION
end
# @return [String] the name of the BattleCommand.
def to_s
@name
end
# @param [BattleCommand] rhs the command on the right.
# @return [Boolean] true iff the commands are considered equal.
def ==(rhs)
@name.casecmp(rhs.name).zero?
end
attr_accessor :name
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/battle/escape.rb | lib/goby/battle/escape.rb | require 'goby'
module Goby
# Allows an Entity to try to escape from the opponent.
class Escape < BattleCommand
# Text for successful escape.
SUCCESS = "Successful escape!\n\n"
# Text for failed escape.
FAILURE = "Unable to escape!\n\n"
# Initializes the Escape command.
def initialize
super(name: "Escape")
end
# Samples a probability to determine if the user will escape from battle.
#
# @param [Entity] user the one who is trying to escape.
# @param [Entity] enemy the one from whom the user wants to escape.
def run(user, enemy)
# Higher probability of escape when the enemy has low agility.
if (user.sample_agilities(enemy))
user.escaped = true
type(SUCCESS)
return
end
# Should already be false.
user.escaped = false
type(FAILURE)
end
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/battle/use.rb | lib/goby/battle/use.rb | require 'goby'
module Goby
# Allows an Entity to use an Item in battle.
class Use < BattleCommand
# Initializes the Use command.
def initialize
super(name: "Use")
end
# Returns true iff the user's inventory is empty.
#
# @param [Entity] user the one who is using the command.
# @return [Boolean] status of the user's inventory.
def fails?(user)
empty = user.inventory.empty?
if empty
print "#{user.name}'s inventory is empty!\n\n"
end
return empty
end
# Uses the specified Item on the specified Entity.
# Note that enemy is not necessarily on whom the Item is used.
#
# @param [Entity] user the one who is using the command.
# @param [Entity] enemy the one on whom the command is used.
def run(user, enemy)
# Determine the item and on whom to use the item.
pair = user.choose_item_and_on_whom(enemy)
return if (!pair)
user.use_item(pair.first, pair.second)
end
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/battle/attack.rb | lib/goby/battle/attack.rb | require 'goby'
module Goby
# Simple physical attack.
class Attack < BattleCommand
# @param [String] name the name.
# @param [Integer] strength the strength.
# @param [Integer] success_rate the chance of success.
def initialize(name: "Attack", strength: 1, success_rate: 100)
super(name: name)
@strength = strength
@success_rate = success_rate
end
# Determine how much damage this attack will do on the enemy.
#
# @param [Entity] user the one using the attack.
# @param [Entity] enemy the one on whom the attack is used.
# @return [Integer] the amount of damage to inflict on the enemy.
def calculate_damage(user, enemy)
# RANDOMIZE ATTACK
inflict = Random.rand(0.05..0.15).round(2)
multiplier = 1
if enemy.stats[:defense] > user.stats[:attack]
multiplier = 1 - ((enemy.stats[:defense] * 0.1) - (user.stats[:attack] * inflict))
# Prevent a negative multiplier.
multiplier = 0 if multiplier.negative?
else
multiplier = 1 + ((user.stats[:attack] * inflict) - (enemy.stats[:defense] * 0.1))
end
return (@strength * multiplier).round(0)
end
# Inflicts damage on the enemy and prints output.
#
# @param [Entity] user the one who is using the attack.
# @param [Entity] enemy the one on whom the attack is used.
def run(user, enemy)
if (Random.rand(100) < @success_rate)
# Damage the enemy.
original_enemy_hp = enemy.stats[:hp]
damage = calculate_damage(user, enemy)
old_hp = enemy.stats[:hp]
enemy.set_stats(hp: old_hp - damage)
type("#{user.name} uses #{@name}!\n\n")
type("#{enemy.name} takes #{original_enemy_hp - enemy.stats[:hp]} damage!\n")
type("#{enemy.name}'s HP: #{original_enemy_hp} -> #{enemy.stats[:hp]}\n\n")
else
type("#{user.name} tries to use #{@name}, but it fails.\n\n")
end
end
attr_accessor :strength, :success_rate
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/battle/battle.rb | lib/goby/battle/battle.rb | require 'goby'
module Goby
# Representation of a fight between two Fighters.
class Battle
# @param [Entity] entity_a the first entity in the battle
# @param [Entity] entity_b the second entity in the battle
def initialize(entity_a, entity_b)
@entity_a = entity_a
@entity_b = entity_b
end
# Determine the winner of the battle
#
# @return [Entity] the winner of the battle
def determine_winner
type("#{entity_a.name} enters a battle with #{entity_b.name}!\n\n")
until someone_dead?
#Determine order of attacks
attackers = determine_order
# Both choose an attack.
attacks = attackers.map { |attacker| attacker.choose_attack }
2.times do |i|
# The attacker runs its attack on the other attacker.
attacks[i].run(attackers[i], attackers[(i + 1) % 2])
if (attackers[i].escaped)
attackers[i].escaped = false
return
end
break if someone_dead?
end
end
#If @entity_a is dead return @entity_b, otherwise return @entity_a
entity_a.stats[:hp] <=0 ? entity_b : entity_a
end
private
# Determine the order of attack based on the entitys' agilities
#
# @return [Array] the entities in the order of attack
def determine_order
sum = entity_a.stats[:agility] + entity_b.stats[:agility]
random_number = Random.rand(0..sum - 1)
if random_number < entity_a.stats[:agility]
[entity_a, entity_b]
else
[entity_b, entity_a]
end
end
# Check if either entity is is dead
#
# @return [Boolean] whether an entity is dead or not
def someone_dead?
entity_a.stats[:hp] <= 0 || entity_b.stats[:hp] <= 0
end
attr_reader :entity_a, :entity_b
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/item/food.rb | lib/goby/item/food.rb | require 'goby'
module Goby
# Recovers HP when used.
class Food < Item
# @param [String] name the name.
# @param [Integer] price the cost in a shop.
# @param [Boolean] consumable upon use, the item is lost when true.
# @param [Boolean] disposable allowed to sell or drop item when true.
# @param [Integer] recovers the amount of HP recovered when used.
def initialize(name: "Food", price: 0, consumable: true, disposable: true, recovers: 0)
super(name: name, price: price, consumable: consumable, disposable: disposable)
@recovers = recovers
end
# Heals the entity.
#
# @param [Entity] user the one using the food.
# @param [Entity] entity the one on whom the food is used.
def use(user, entity)
if entity.stats[:hp] + recovers > entity.stats[:max_hp]
this_recover = entity.stats[:max_hp] - entity.stats[:hp]
heal_entity(entity, entity.stats[:max_hp])
else
current_hp = entity.stats[:hp]
this_recover = @recovers
heal_entity(entity, current_hp + this_recover)
end
# Helpful output.
print "#{user.name} uses #{name}"
if (user == entity)
print " and "
else
print " on #{entity.name}!\n#{entity.name} "
end
print "recovers #{this_recover} HP!\n\n"
print "#{entity.name}'s HP: #{entity.stats[:hp]}/#{entity.stats[:max_hp]}\n\n"
end
# The amount of HP that the food recovers.
attr_reader :recovers
private
#sets the hp of entity to new_hp
def heal_entity(entity, new_hp)
entity.set_stats(hp: new_hp)
end
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/item/weapon.rb | lib/goby/item/weapon.rb | require 'goby'
module Goby
# Can be worn in the Player's outfit.
class Weapon < Item
include Equippable
# @param [String] name the name.
# @param [Integer] price the cost in a shop.
# @param [Boolean] consumable determines whether the item is lost when used.
# @param [Boolean] disposable allowed to sell or drop item when true.
# @param [Hash] stat_change the change in stats for when the item is equipped.
# @param [Attack] attack the attack which is added to the entity's battle commands.
def initialize(name: "Weapon", price: 0, consumable: false, disposable: true, stat_change: {}, attack: nil)
super(name: name, price: price, consumable: consumable, disposable: disposable)
@attack = attack
@type = :weapon
@stat_change = stat_change
end
# Equips onto the entity and changes the entity's attributes accordingly.
#
# @param [Entity] entity the entity who is equipping the equippable.
def equip(entity)
prev_weapon = nil
if entity.outfit[@type]
prev_weapon = entity.outfit[@type]
end
super(entity)
if (prev_weapon && prev_weapon.attack)
entity.remove_battle_command(prev_weapon.attack)
end
if @attack
entity.add_battle_command(@attack)
end
end
# Unequips from the entity and changes the entity's attributes accordingly.
#
# @param [Entity] entity the entity who is unequipping the equippable.
def unequip(entity)
super(entity)
if @attack
entity.remove_battle_command(@attack)
end
end
attr_reader :type, :stat_change
# An instance of Attack.
attr_accessor :attack
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/item/legs.rb | lib/goby/item/legs.rb | require 'goby'
module Goby
# Can be worn in the Player's outfit.
class Legs < Item
include Equippable
# @param [String] name the name.
# @param [Integer] price the cost in a shop.
# @param [Boolean] consumable upon use, the item is lost when true.
# @param [Boolean] disposable allowed to sell or drop item when true.
# @param [Hash] stat_change the change in stats for when the item is equipped.
def initialize(name: "Legs", price: 0, consumable: false, disposable: true, stat_change: {})
super(name: name, price: price, consumable: consumable, disposable: disposable)
@type = :legs
@stat_change = stat_change
end
attr_reader :type, :stat_change
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/item/shield.rb | lib/goby/item/shield.rb | require 'goby'
module Goby
# Can be worn in the Player's outfit.
class Shield < Item
include Equippable
# @param [String] name the name.
# @param [Integer] price the cost in a shop.
# @param [Boolean] consumable upon use, the item is lost when true.
# @param [Boolean] disposable allowed to sell or drop item when true.
# @param [Hash] stat_change the change in stats for when the item is equipped.
def initialize(name: "Shield", price: 0, consumable: false, disposable: true, stat_change: {})
super(name: name, price: price, consumable: consumable, disposable: disposable)
@type = :shield
@stat_change = stat_change
end
attr_reader :type, :stat_change
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/item/equippable.rb | lib/goby/item/equippable.rb | module Goby
# Provides methods for equipping & unequipping an Item.
module Equippable
# The function that returns the type of the item.
# Subclasses must override this function.
#
def stat_change
raise(NotImplementedError, 'An Equippable Item must implement a stat_change Hash')
end
# The function that returns the change in stats for when the item is equipped.
# Subclasses must override this function.
#
def type
raise(NotImplementedError, 'An Equippable Item must have a type')
end
# Alters the stats of the entity
#
# @param [Entity] entity the entity equipping/unequipping the item.
# @param [Boolean] equipping flag for when the item is being equipped or unequipped.
# @todo ensure stats cannot go below zero (but does it matter..?).
def alter_stats(entity, equipping)
stats_to_change = entity.stats.dup
affected_stats = [:attack, :defense, :agility, :max_hp]
operator = equipping ? :+ : :-
affected_stats.each do |stat|
stats_to_change[stat]= stats_to_change[stat].send(operator, stat_change[stat]) if stat_change[stat]
end
entity.set_stats(stats_to_change)
#do not kill entity by unequipping
if entity.stats[:hp] < 1
entity.set_stats(hp: 1)
end
end
# Equips onto the entity and changes the entity's attributes accordingly.
#
# @param [Entity] entity the entity who is equipping the equippable.
def equip(entity)
prev_item = entity.outfit[type]
entity.outfit[type] = self
alter_stats(entity, true)
if prev_item
prev_item.alter_stats(entity, false)
entity.add_item(prev_item)
end
print "#{entity.name} equips #{@name}!\n\n"
end
# Unequips from the entity and changes the entity's attributes accordingly.
#
# @param [Entity] entity the entity who is unequipping the equippable.
def unequip(entity)
entity.outfit.delete(type)
alter_stats(entity, false)
print "#{entity.name} unequips #{@name}!\n\n"
end
# The function that executes when one uses the equippable.
#
# @param [Entity] user the one using the item.
# @param [Entity] entity the one on whom the item is used.
def use(user, entity)
print "Type 'equip #{@name}' to equip this item.\n\n"
end
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/item/item.rb | lib/goby/item/item.rb | module Goby
# Can be used by an Entity in order to trigger anything specified.
# Placed into the Entity's inventory.
class Item
# Default text when the Item doesn't do anything.
DEFAULT_USE_TEXT = "Nothing happens.\n\n"
# @param [String] name the name.
# @param [Integer] price the cost in a shop.
# @param [Boolean] consumable upon use, the item is lost when true.
# @param [Boolean] disposable allowed to sell or drop item when true.
def initialize(name: "Item", price: 0, consumable: true, disposable: true)
@name = name
@price = price
@consumable = consumable
@disposable = disposable
end
# The function that executes when one uses the item.
#
# @param [Entity] user the one using the item.
# @param [Entity] entity the one on whom the item is used.
def use(user, entity)
print DEFAULT_USE_TEXT
end
# @param [Item] rhs the item on the right.
def ==(rhs)
return @name.casecmp(rhs.name).zero?
end
# @return [String] the name of the Item.
def to_s
@name
end
attr_accessor :name, :price, :consumable, :disposable
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/item/helmet.rb | lib/goby/item/helmet.rb | require 'goby'
module Goby
# Can be worn in the Player's outfit.
class Helmet < Item
include Equippable
# @param [String] name the name.
# @param [Integer] price the cost in a shop.
# @param [Boolean] consumable upon use, the item is lost when true.
# @param [Boolean] disposable allowed to sell or drop item when true.
# @param [Hash] stat_change the change in stats for when the item is equipped.
def initialize(name: "Helmet", price: 0, consumable: false, disposable: true, stat_change: {})
super(name: name, price: price, consumable: consumable, disposable: disposable)
@type = :helmet
@stat_change = stat_change
end
attr_reader :type, :stat_change
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/item/torso.rb | lib/goby/item/torso.rb | require 'goby'
module Goby
# Can be worn in the Player's outfit.
class Torso < Item
include Equippable
# @param [String] name the name.
# @param [Integer] price the cost in a shop.
# @param [Boolean] consumable determines whether the item is lost when used.
# @param [Boolean] disposable allowed to sell or drop item when true.
# @param [Hash] stat_change the change in stats for when the item is equipped.
def initialize(name: "Torso", price: 0, consumable: false, disposable: true, stat_change: {})
super(name: name, price: price, consumable: consumable, disposable: disposable)
@type = :torso
@stat_change = stat_change
end
attr_reader :type, :stat_change
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/map/map.rb | lib/goby/map/map.rb | module Goby
# A 2D arrangement of Tiles. The Player can move around on it.
class Map
# @param [String] name the name.
# @param [[Tile]] tiles the content of the map.
def initialize(name: "Map", tiles: [[Tile.new]], music: nil)
@name = name
@tiles = tiles
@music = music
end
# Returns true when @tiles[y][x] is an existing index of @tiles.
# Otherwise, returns false.
#
# @param [Integer] y the y-coordinate.
# @param [Integer] x the x-coordinate.
# @return [Boolean] the existence of the tile.
def in_bounds(y, x)
return (y.nonnegative? && y < @tiles.length && x.nonnegative? && x < @tiles[y].length)
end
# Prints the map in a nice format.
def to_s
output = ""
@tiles.each do |row|
row.each do |tile|
output += (tile.graphic + " ")
end
output += "\n"
end
return output
end
# @param [Map] rhs the Map on the right.
def ==(rhs)
return @name == rhs.name
end
attr_accessor :name, :tiles, :music
end
end
| ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
nskins/goby | https://github.com/nskins/goby/blob/56c9ca5f825b50f9126d9e8759ba8666c72d73b5/lib/goby/map/tile.rb | lib/goby/map/tile.rb | module Goby
# Describes a single location on a Map. Can have Events and Monsters.
# Provides variables that control its graphical representation on the Map.
class Tile
# Default graphic for passable tiles.
DEFAULT_PASSABLE = "·"
# Default graphic for impassable tiles.
DEFAULT_IMPASSABLE = "■"
# @param [Boolean] passable if true, the player can move here.
# @param [Boolean] seen if true, it will be printed on the map.
# @param [String] description a summary/message of the contents.
# @param [[Event]] events the events found on this tile.
# @param [[Monster]] monsters the monsters found on this tile.
# @param [String] graphic the respresentation of this tile graphically.
def initialize(passable: true, seen: false, description: "", events: [], monsters: [], graphic: nil)
@passable = passable
@seen = seen
@description = description
@events = events
@monsters = monsters
@graphic = graphic.nil? ? default_graphic : graphic
end
# Create deep copy of Tile.
#
# @return Tile a new Tile object
def clone
# First serialize the object, and then deserialize that into a new ruby object
serialized_tile = Marshal.dump(self)
new_tile = Marshal.load(serialized_tile)
return new_tile
end
# Convenient conversion to String.
#
# @return [String] the string representation.
def to_s
return @seen ? @graphic + " " : " "
end
attr_accessor :passable, :seen, :description, :events, :monsters, :graphic
private
# Returns the default graphic by considering passable.
def default_graphic
return @passable ? DEFAULT_PASSABLE : DEFAULT_IMPASSABLE
end
end
end | ruby | MIT | 56c9ca5f825b50f9126d9e8759ba8666c72d73b5 | 2026-01-04T17:58:11.621150Z | false |
github/rack-statsd | https://github.com/github/rack-statsd/blob/f03b18ef5c27df861384930c206d797be540e956/lib/rack-statsd.rb | lib/rack-statsd.rb | module RackStatsD
VERSION = "0.2.1"
# Simple middleware to add a quick status URL for tools like Nagios.
class RequestStatus
REQUEST_METHOD = 'REQUEST_METHOD'.freeze
GET = 'GET'.freeze
PATH_INFO = 'PATH_INFO'.freeze
STATUS_PATH = '/status'
HEADERS = {"Content-Type" => "text/plain"}.freeze
# Initializes the middleware.
#
# # Responds with "OK" on /status
# use RequestStatus, "OK"
#
# You can change what URL to look for:
#
# use RequestStatus, "OK", "/ping"
#
# You can also check internal systems and return something more informative.
#
# use RequestStatus, lambda {
# status = MyApp.status # A Hash of some live counters or something
# [200, {"Content-Type" => "application/json"}, status.to_json]
# }
#
# app - The next Rack app in the pipeline.
# callback_or_response - Either a Proc or a Rack response.
# status_path - Optional String path that returns the status.
# Default: "/status"
#
# Returns nothing.
def initialize(app, callback_or_response, status_path = nil)
@app = app
@status_path = (status_path || STATUS_PATH).freeze
@callback = callback_or_response
end
def call(env)
if env[REQUEST_METHOD] == GET
if env[PATH_INFO] == @status_path
if @callback.respond_to?(:call)
return @callback.call
else
return [200, HEADERS, [@callback.to_s]]
end
end
end
@app.call env
end
end
# Simple middleware that adds the current host name and current git SHA to
# the response headers. This can help diagnose problems by letting you
# know what code is running from what machine.
class RequestHostname
# Initializes the middlware.
#
# app - The next Rack app in the pipeline.
# options - Hash of options.
# :host - String hostname.
# :revision - String SHA that describes the version of code
# this process is running.
#
# Returns nothing.
def initialize(app, options = {})
@app = app
@host = options.key?(:host) ? options[:host] : `hostname -s`.chomp
@sha = options[:revision] || '<none>'
end
def call(env)
status, headers, body = @app.call(env)
headers['X-Node'] = @host if @host
headers['X-Revision'] = @sha
[status, headers, body]
end
end
# Middleware that tracks the amount of time this process spends processing
# requests, as opposed to being idle waiting for a connection. Statistics
# are dumped to rack.errors every 5 minutes.
#
# NOTE This middleware is not thread safe. It should only be used when
# rack.multiprocess is true and rack.multithread is false.
class ProcessUtilization
REQUEST_METHOD = 'REQUEST_METHOD'.freeze
VALID_METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'].freeze
# Initializes the middleware.
#
# app - The next Rack app in the pipeline.
# domain - The String domain name the app runs in.
# revision - The String SHA that describes the current version of code.
# options - Hash of options.
# :window - The Integer number of seconds before the
# horizon resets.
# :stats - Optional StatsD client.
# :hostname - Optional String hostname. Set to nil
# to exclude.
# :stats_prefix - Optional String prefix for StatsD keys.
# Default: "rack"
def initialize(app, domain, revision, options = {})
@app = app
@domain = domain
@revision = revision
@window = options[:window] || 100
@horizon = nil
@active_time = nil
@requests = nil
@total_requests = 0
@worker_number = nil
@track_gc = GC.respond_to?(:time)
if @stats = options[:stats]
prefix = [options[:stats_prefix] || :rack]
if options.has_key?(:hostname)
prefix << options[:hostname] unless options[:hostname].nil?
else
prefix << `hostname -s`.chomp
end
@stats_prefix = prefix.join(".")
end
end
# the app's domain name - shown in proctitle
attr_accessor :domain
# the currently running git revision as a 7-sha
attr_accessor :revision
# time when we began sampling. this is reset every once in a while so
# averages don't skew over time.
attr_accessor :horizon
# total number of requests that have been processed by this worker since
# the horizon time.
attr_accessor :requests
# decimal number of seconds the worker has been active within a request
# since the horizon time.
attr_accessor :active_time
# total requests processed by this worker process since it started
attr_accessor :total_requests
# the unicorn worker number
attr_accessor :worker_number
# the amount of time since the horizon
def horizon_time
Time.now - horizon
end
# decimal number of seconds this process has been active since the horizon
# time. This is the inverse of the active time.
def idle_time
horizon_time - active_time
end
# percentage of time this process has been active since the horizon time.
def percentage_active
(active_time / horizon_time) * 100
end
# percentage of time this process has been idle since the horizon time.
def percentage_idle
(idle_time / horizon_time) * 100
end
# number of requests processed per second since the horizon
def requests_per_second
requests / horizon_time
end
# average response time since the horizon in milliseconds
def average_response_time
(active_time / requests.to_f) * 1000
end
# called exactly once before the first request is processed by a worker
def first_request
reset_horizon
record_worker_number
end
# resets the horizon and all dependent variables
def reset_horizon
@horizon = Time.now
@active_time = 0.0
@requests = 0
end
# extracts the worker number from the unicorn procline
def record_worker_number
if $0 =~ /^.* worker\[(\d+)\].*$/
@worker_number = $1.to_i
else
@worker_number = nil
end
end
# the generated procline
def procline
"unicorn %s[%s] worker[%02d]: %5d reqs, %4.1f req/s, %4dms avg, %5.1f%% util" % [
domain,
revision,
worker_number.to_i,
total_requests.to_i,
requests_per_second.to_f,
average_response_time.to_i,
percentage_active.to_f
]
end
# called immediately after a request to record statistics, update the
# procline, and dump information to the logfile
def record_request(status, env)
now = Time.now
diff = (now - @start)
@active_time += diff
@requests += 1
$0 = procline
if @stats
@stats.timing("#{@stats_prefix}.response_time", diff * 1000)
if VALID_METHODS.include?(env[REQUEST_METHOD])
stat = "#{@stats_prefix}.response_time.#{env[REQUEST_METHOD].downcase}"
@stats.timing(stat, diff * 1000)
end
if suffix = status_suffix(status)
@stats.increment "#{@stats_prefix}.status_code.#{status_suffix(status)}"
end
if @track_gc && GC.time > 0
@stats.timing "#{@stats_prefix}.gc.time", GC.time / 1000
@stats.count "#{@stats_prefix}.gc.collections", GC.collections
end
end
reset_horizon if now - horizon > @window
rescue => boom
warn "ProcessUtilization#record_request failed: #{boom}"
end
def status_suffix(status)
suffix = case status.to_i
when 200 then :ok
when 201 then :created
when 202 then :accepted
when 301 then :moved_permanently
when 302 then :found
when 303 then :see_other
when 304 then :not_modified
when 305 then :use_proxy
when 307 then :temporary_redirect
when 400 then :bad_request
when 401 then :unauthorized
when 402 then :payment_required
when 403 then :forbidden
when 404 then :missing
when 410 then :gone
when 422 then :invalid
when 500 then :error
when 502 then :bad_gateway
when 503 then :node_down
when 504 then :gateway_timeout
end
end
# Body wrapper. Yields to the block when body is closed. This is used to
# signal when a response is fully finished processing.
class Body
def initialize(body, &block)
@body = body
@block = block
end
def each(&block)
if @body.respond_to?(:each)
@body.each(&block)
else
block.call(@body)
end
end
def close
@body.close if @body.respond_to?(:close)
@block.call
nil
end
end
# Rack entry point.
def call(env)
@start = Time.now
GC.clear_stats if @track_gc
@total_requests += 1
first_request if @total_requests == 1
env['process.request_start'] = @start.to_f
env['process.total_requests'] = total_requests
# newrelic X-Request-Start
env.delete('HTTP_X_REQUEST_START')
status, headers, body = @app.call(env)
body = Body.new(body) { record_request(status, env) }
[status, headers, body]
end
end
end
| ruby | MIT | f03b18ef5c27df861384930c206d797be540e956 | 2026-01-04T17:58:14.947191Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/app/helpers/application_helper.rb | app/helpers/application_helper.rb | module ApplicationHelper
def sortable(column, title = nil)
title ||= column.titleize
css_class = (column == sort_column) ? "current #{sort_direction}" : nil
direction = (column == sort_column && sort_direction == "asc") ? "desc" : "asc"
link_to title, { :sort => column, :direction => direction }, { :class => css_class }
end
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/app/helpers/pages_helper.rb | app/helpers/pages_helper.rb | module PagesHelper
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/app/helpers/admin/users_helper.rb | app/helpers/admin/users_helper.rb | module Admin::UsersHelper
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/app/helpers/admin/base_helper.rb | app/helpers/admin/base_helper.rb | module Admin::BaseHelper
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/app/controllers/pages_controller.rb | app/controllers/pages_controller.rb | class PagesController < ApplicationController
def index
end
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/app/controllers/application_controller.rb | app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
protect_from_forgery
def render404
render :file => File.join(Rails.root, 'public', '404.html'), :status => 404, :layout => false
return true
end
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/app/controllers/admin/users_controller.rb | app/controllers/admin/users_controller.rb | class Admin::UsersController < Admin::BaseController
helper_method :sort_column, :sort_direction, :search_params
before_filter :find_user, :only => [:edit, :update, :show, :destroy]
def index
@q = User.search(params[:q])
search_relation = @q.result
@users = search_relation.order(sort_column + " " + sort_direction).references(:user).page params[:page]
end
def show
end
def edit
end
def update
if @user.update_attributes(params[:user].permit(:email))
redirect_to admin_users_path, :notice => "User successfully updated."
else
render :edit
end
end
def destroy
@user.destroy
redirect_to admin_users_path, :notice => "User deleted."
end
protected
def find_user
@user = User.find(params[:id])
end
private
def sort_column
User.column_names.include?(params[:sort]) ? params[:sort] : "email"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
def search_params
{ :search => params[:search] }
end
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/app/controllers/admin/base_controller.rb | app/controllers/admin/base_controller.rb | class Admin::BaseController < ApplicationController
before_filter :require_admin
layout "admin"
def index
end
protected
def require_admin
unless current_user.try(:admin?)
render404 and return false
end
end
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/app/controllers/users/omniauth_callbacks_controller.rb | app/controllers/users/omniauth_callbacks_controller.rb | class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
@user = User.find_for_facebook_oauth(env["omniauth.auth"], current_user)
if @user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Facebook"
sign_in_and_redirect @user, :event => :authentication
else
session["devise.facebook_data"] = env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/app/models/role.rb | app/models/role.rb | class Role < ActiveRecord::Base
has_and_belongs_to_many :users
def self.admin
find_or_create_by(:name => "admin")
end
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/app/models/user.rb | app/models/user.rb | class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
devise :omniauthable
has_and_belongs_to_many :roles
def role?(role)
return !!self.roles.find_by_name(role.to_s)
end
def make_admin
self.roles << Role.admin
end
def revoke_admin
self.roles.delete(Role.admin)
end
def admin?
role?(:admin)
end
def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
data = access_token['info']
if user = User.find_by_email(data["email"])
user
else # Create a user with a stub password.
User.create!(:email => data["email"], :password => Devise.friendly_token[0,20])
end
end
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/db/seeds.rb | db/seeds.rb | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
# Mayor.create(:name => 'Daley', :city => cities.first)
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/db/schema.rb | db/schema.rb | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20110415110329) do
create_table "roles", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "roles_users", :id => false, :force => true do |t|
t.integer "role_id"
t.integer "user_id"
end
create_table "users", :force => true do |t|
t.string "email", :default => "", :null => false
t.string "encrypted_password", :default => "", :null => false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", :default => 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "users", ["email"], :name => "index_users_on_email", :unique => true
add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/db/migrate/20110405113203_devise_create_users.rb | db/migrate/20110405113203_devise_create_users.rb | class DeviseCreateUsers < ActiveRecord::Migration
def self.up
create_table(:users) do |t|
## Database authenticatable
t.string :email, :null => false, :default => ""
t.string :encrypted_password, :null => false, :default => ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, :default => 0
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Encryptable
# t.string :password_salt
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, :default => 0 # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
# Token authenticatable
# t.string :authentication_token
t.timestamps
end
add_index :users, :email, :unique => true
add_index :users, :reset_password_token, :unique => true
# add_index :users, :confirmation_token, :unique => true
# add_index :users, :unlock_token, :unique => true
# add_index :users, :authentication_token, :unique => true
end
def self.down
drop_table :users
end
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/db/migrate/20110415105605_create_roles.rb | db/migrate/20110415105605_create_roles.rb | class CreateRoles < ActiveRecord::Migration
def self.up
create_table :roles do |t|
t.string :name
t.timestamps
end
end
def self.down
drop_table :roles
end
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/db/migrate/20110415110329_user_has_and_belongs_to_many_roles.rb | db/migrate/20110415110329_user_has_and_belongs_to_many_roles.rb | class UserHasAndBelongsToManyRoles < ActiveRecord::Migration
def self.up
create_table :roles_users, :id => false do |t|
t.references :role, :user
end
end
def self.down
drop_table :roles_users
end
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/features/support/env.rb | features/support/env.rb | require 'rubygems'
require 'cucumber/rails'
require 'email_spec/cucumber'
World FactoryGirl::Syntax::Methods
# Capybara defaults to XPath selectors rather than Webrat's default of CSS3. In
# order to ease the transition to Capybara we set the default here. If you'd
# prefer to use XPath just remove this line and adjust any selectors in your
# steps to use the XPath syntax.
Capybara.default_selector = :css
# By default, any exception happening in your Rails application will bubble up
# to Cucumber so that your scenario will fail. This is a different from how
# your application behaves in the production environment, where an error page will
# be rendered instead.
#
# Sometimes we want to override this default behaviour and allow Rails to rescue
# exceptions and display an error page (just like when the app is running in production).
# Typical scenarios where you want to do this is when you test your error pages.
# There are two ways to allow Rails to rescue exceptions:
#
# 1) Tag your scenario (or feature) with @allow-rescue
#
# 2) Set the value below to true. Beware that doing this globally is not
# recommended as it will mask a lot of errors for you!
#
ActionController::Base.allow_rescue = false
begin
DatabaseCleaner.strategy = :transaction
rescue NameError
raise "You need to add database_cleaner to your Gemfile (in the :test group) if you wish to use it."
end
# Possible values are :truncation and :transaction
# The :transaction strategy is faster, but might give you threading problems.
# See https://github.com/cucumber/cucumber-rails/blob/master/features/choose_javascript_database_strategy.feature
Cucumber::Rails::Database.javascript_strategy = :truncation
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/features/support/paths.rb | features/support/paths.rb | module NavigationHelpers
# Maps a name to a path. Used by the
#
# When /^I go to (.+)$/ do |page_name|
#
# step definition in web_steps.rb
#
def path_to(page_name)
case page_name
when /the home\s?page/
'/'
# Add more mappings here.
# Here is an example that pulls values out of the Regexp:
#
# when /^(.*)'s profile page$/i
# user_profile_path(User.find_by_login($1))
else
begin
page_name =~ /the (.*) page/
path_components = $1.split(/\s+/)
self.send(path_components.push('path').join('_').to_sym)
rescue Object => e
raise "Can't find mapping from \"#{page_name}\" to a path.\n" +
"Now, go and add a mapping in #{__FILE__}"
end
end
end
end
World(NavigationHelpers)
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/features/support/omniauth.rb | features/support/omniauth.rb | FACEBOOK_INFO = {
"id" => "12345",
"link" => "http://facebook.com/john_doe",
"email" => "user@example.com",
"first_name" => "John",
"last_name" => "Doe",
"website" => "http://www.example.com"
}
Before("@omniauth_test") do
OmniAuth.config.test_mode = true
# the symbol passed to mock_auth is the same as the name of the provider set up in the initializer
OmniAuth.config.mock_auth[:facebook] = {
"uid" => "12345",
"provider" => "facebook",
"user_info" => { "nickname" => "Johny" },
"credentials" => { "token" => "exampletoken" },
"info" => FACEBOOK_INFO
}
end
After("@omniauth_test") do
OmniAuth.config.test_mode = false
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/features/support/selectors.rb | features/support/selectors.rb | module HtmlSelectorsHelpers
# Maps a name to a selector. Used primarily by the
#
# When /^(.+) within (.+)$/ do |step, scope|
#
# step definitions in web_steps.rb
#
def selector_for(locator)
case locator
when /the page/
"html > body"
# Add more mappings here.
# Here is an example that pulls values out of the Regexp:
#
# when /the (notice|error|info) flash/
# ".flash.#{$1}"
# You can also return an array to use a different selector
# type, like:
#
# when /the header/
# [:xpath, "//header"]
# This allows you to provide a quoted selector as the scope
# for "within" steps as was previously the default for the
# web steps:
when /"(.+)"/
$1
else
raise "Can't find mapping from \"#{locator}\" to a selector.\n" +
"Now, go and add a mapping in #{__FILE__}"
end
end
end
World(HtmlSelectorsHelpers)
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/features/step_definitions/authentication_steps.rb | features/step_definitions/authentication_steps.rb | Given /^I am registered$/ do
@registered_user = create(:user, :email => "john@doe.com")
end
When(/^I sign up$/) do
click_link "Sign up"
fill_in "Email", :with => "john@doe.com"
fill_in "Password", :with => "password"
fill_in "Password confirmation", :with => "password"
click_button "Sign up"
end
Then(/^I should see a sign up confirmation$/) do
page.should have_content("You have signed up successfully.")
end
Then(/^I should be logged in$/) do
page.should have_content("Account settings")
page.should have_content("Sign out")
end
When(/^I sign in$/) do
click_link "Sign in"
fill_in "Email", :with => "john@doe.com"
fill_in "Password", :with => "password"
click_button "Sign in"
end
Then(/^I should see the sign in confirmation$/) do
page.should have_content("Signed in successfully.")
end
When(/^I sign out$/) do
click_link "Sign out"
end
Then(/^I should see the sign out confirmation$/) do
page.should have_content("Signed out successfully.")
end
When(/^I sign in with Facebook$/) do
click_link "Sign in with Facebook"
end
Then(/^I should see the Facebook sign in confirmation$/) do
page.should have_content("Successfully authorized from Facebook account.")
end
When(/^I reset my password$/) do
click_link "Sign in"
click_link "Forgot your password?"
fill_in "Email", :with => "john@doe.com"
click_button "Send me instructions to reset password"
end
Then(/^I should receive a password reset email$/) do
steps %Q{
Then "john@doe.com" should receive an email
}
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/features/step_definitions/homepage_steps.rb | features/step_definitions/homepage_steps.rb | Given(/^I am on the homepage$/) do
visit("/")
end
Then(/^I should see the welcome message$/) do
page.should have_content("Welcome")
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/features/step_definitions/admin_user_management_steps.rb | features/step_definitions/admin_user_management_steps.rb | Given /^I am admin$/ do
@registered_user.make_admin
end
Given /^I am logged in as admin$/ do
steps %Q{
Given I am registered
And I am admin
And I am on the homepage
When I sign in
}
end
Given /^a user with email "([^"]*)" exists$/ do |email|
@registered_user = create(:user,
:email => email,
:created_at => 2.days.ago,
:last_sign_in_at => 1.day.ago,
:updated_at => 5.hours.ago)
end
When /^I edit user with "([^"]*)" email$/ do |email|
within(:xpath, "//table//tr[contains(., '#{email}')]") do
find_link('Edit').click
end
end
When(/^I open admin users screen$/) do
click_link "Admin"
click_link "Users"
end
Then(/^I should see myself in admin user list$/) do
page.should have_content(@registered_user.email)
end
When(/^I admin change user "(.*?)" email to "(.*?)"$/) do |current_email, new_email|
find_field('Email').value.should eql(current_email)
fill_in "Email", :with => new_email
click_button "Update"
end
Then(/^I should see admin user edit confirmation$/) do
page.should have_content("User successfully updated")
end
Then(/^I should see user "(.*?)" in admin users list$/) do |user_info|
page.should have_content(user_info)
end
When(/^I admin search for user "(.*?)"$/) do |query|
fill_in "q_email_cont", :with => query
click_button "Search"
end
Then(/^admin user search results should include "(.*?)"$/) do |result|
page.should have_content(result)
end
Then(/^admin user search results should not include "(.*?)"$/) do |result|
page.should_not have_content(result)
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/features/step_definitions/email_steps.rb | features/step_definitions/email_steps.rb | # Commonly used email steps
#
# To add your own steps make a custom_email_steps.rb
# The provided methods are:
#
# last_email_address
# reset_mailer
# open_last_email
# visit_in_email
# unread_emails_for
# mailbox_for
# current_email
# open_email
# read_emails_for
# find_email
#
# General form for email scenarios are:
# - clear the email queue (done automatically by email_spec)
# - execute steps that sends an email
# - check the user received an/no/[0-9] emails
# - open the email
# - inspect the email contents
# - interact with the email (e.g. click links)
#
# The Cucumber steps below are setup in this order.
module EmailHelpers
def current_email_address
# Replace with your a way to find your current email. e.g @current_user.email
# last_email_address will return the last email address used by email spec to find an email.
# Note that last_email_address will be reset after each Scenario.
last_email_address || "example@example.com"
end
end
World(EmailHelpers)
#
# Reset the e-mail queue within a scenario.
# This is done automatically before each scenario.
#
Given /^(?:a clear email queue|no emails have been sent)$/ do
reset_mailer
end
#
# Check how many emails have been sent/received
#
Then /^(?:I|they|"([^"]*?)") should receive (an|no|\d+) emails?$/ do |address, amount|
unread_emails_for(address).size.should == parse_email_count(amount)
end
Then /^(?:I|they|"([^"]*?)") should have (an|no|\d+) emails?$/ do |address, amount|
mailbox_for(address).size.should == parse_email_count(amount)
end
Then /^(?:I|they|"([^"]*?)") should receive (an|no|\d+) emails? with subject "([^"]*?)"$/ do |address, amount, subject|
unread_emails_for(address).select { |m| m.subject =~ Regexp.new(subject) }.size.should == parse_email_count(amount)
end
Then /^(?:I|they|"([^"]*?)") should receive an email with the following body:$/ do |address, expected_body|
open_email(address, :with_text => expected_body)
end
#
# Accessing emails
#
# Opens the most recently received email
When /^(?:I|they|"([^"]*?)") opens? the email$/ do |address|
open_email(address)
end
When /^(?:I|they|"([^"]*?)") opens? the email with subject "([^"]*?)"$/ do |address, subject|
open_email(address, :with_subject => subject)
end
When /^(?:I|they|"([^"]*?)") opens? the email with text "([^"]*?)"$/ do |address, text|
open_email(address, :with_text => text)
end
#
# Inspect the Email Contents
#
Then /^(?:I|they) should see "([^"]*?)" in the email subject$/ do |text|
current_email.should have_subject(text)
end
Then /^(?:I|they) should see \/([^"]*?)\/ in the email subject$/ do |text|
current_email.should have_subject(Regexp.new(text))
end
Then /^(?:I|they) should see "([^"]*?)" in the email body$/ do |text|
current_email.default_part_body.to_s.should include(text)
end
Then /^(?:I|they) should see \/([^"]*?)\/ in the email body$/ do |text|
current_email.default_part_body.to_s.should =~ Regexp.new(text)
end
Then /^(?:I|they) should see the email delivered from "([^"]*?)"$/ do |text|
current_email.should be_delivered_from(text)
end
Then /^(?:I|they) should see "([^\"]*)" in the email "([^"]*?)" header$/ do |text, name|
current_email.should have_header(name, text)
end
Then /^(?:I|they) should see \/([^\"]*)\/ in the email "([^"]*?)" header$/ do |text, name|
current_email.should have_header(name, Regexp.new(text))
end
Then /^I should see it is a multi\-part email$/ do
current_email.should be_multipart
end
Then /^(?:I|they) should see "([^"]*?)" in the email html part body$/ do |text|
current_email.html_part.body.to_s.should include(text)
end
Then /^(?:I|they) should see "([^"]*?)" in the email text part body$/ do |text|
current_email.text_part.body.to_s.should include(text)
end
#
# Inspect the Email Attachments
#
Then /^(?:I|they) should see (an|no|\d+) attachments? with the email$/ do |amount|
current_email_attachments.size.should == parse_email_count(amount)
end
Then /^there should be (an|no|\d+) attachments? named "([^"]*?)"$/ do |amount, filename|
current_email_attachments.select { |a| a.filename == filename }.size.should == parse_email_count(amount)
end
Then /^attachment (\d+) should be named "([^"]*?)"$/ do |index, filename|
current_email_attachments[(index.to_i - 1)].filename.should == filename
end
Then /^there should be (an|no|\d+) attachments? of type "([^"]*?)"$/ do |amount, content_type|
current_email_attachments.select { |a| a.content_type.include?(content_type) }.size.should == parse_email_count(amount)
end
Then /^attachment (\d+) should be of type "([^"]*?)"$/ do |index, content_type|
current_email_attachments[(index.to_i - 1)].content_type.should include(content_type)
end
Then /^all attachments should not be blank$/ do
current_email_attachments.each do |attachment|
attachment.read.size.should_not == 0
end
end
Then /^show me a list of email attachments$/ do
EmailSpec::EmailViewer::save_and_open_email_attachments_list(current_email)
end
#
# Interact with Email Contents
#
When /^(?:I|they) follow "([^"]*?)" in the email$/ do |link|
visit_in_email(link)
end
When /^(?:I|they) click the first link in the email$/ do
click_first_link_in_email
end
#
# Debugging
# These only work with Rails and OSx ATM since EmailViewer uses RAILS_ROOT and OSx's 'open' command.
# Patches accepted. ;)
#
Then /^save and open current email$/ do
EmailSpec::EmailViewer::save_and_open_email(current_email)
end
Then /^save and open all text emails$/ do
EmailSpec::EmailViewer::save_and_open_all_text_emails
end
Then /^save and open all html emails$/ do
EmailSpec::EmailViewer::save_and_open_all_html_emails
end
Then /^save and open all raw emails$/ do
EmailSpec::EmailViewer::save_and_open_all_raw_emails
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/spec/spec_helper.rb | spec/spec_helper.rb | require 'rubygems'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require "email_spec"
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = false
# If true, the base class of anonymous controllers will be inferred
# automatically. This will be the default behavior in future versions of
# rspec-rails.
config.infer_base_class_for_anonymous_controllers = false
config.mock_with :rspec
config.include(EmailSpec::Helpers)
config.include(EmailSpec::Matchers)
config.include FactoryGirl::Syntax::Methods
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/spec/helpers/pages_helper_spec.rb | spec/helpers/pages_helper_spec.rb | require 'spec_helper'
describe PagesHelper do
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/spec/factories/role.rb | spec/factories/role.rb | FactoryGirl.define do
factory :role do
name "admin"
end
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/spec/factories/user.rb | spec/factories/user.rb | FactoryGirl.define do
factory :user do
sequence(:email) { |n| "john#{n}@doe.com" }
password "password"
password_confirmation "password"
end
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/spec/controllers/pages_controller_spec.rb | spec/controllers/pages_controller_spec.rb | require 'spec_helper'
describe PagesController do
describe "GET 'index'" do
it "should be successful" do
get 'index'
response.should be_success
end
end
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/spec/controllers/admin/base_controller_spec.rb | spec/controllers/admin/base_controller_spec.rb | require 'spec_helper'
describe Admin::BaseController do
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/spec/controllers/admin/users_controller_spec.rb | spec/controllers/admin/users_controller_spec.rb | require 'spec_helper'
describe Admin::UsersController do
let(:user) { mock_model(User) }
before do
controller.stub(:current_user).and_return(user)
user.should_receive(:admin?).and_return(true)
end
describe "GET 'index'" do
it "assigns all users as @users" do
User.stub_chain(:search, :result, :order, :references, :page).and_return([user])
get :index
assigns[:users].should eql([user])
end
end
describe "GET 'show'" do
before do
User.should_receive(:find).and_return(user)
end
it "assigns requested user as @user" do
get 'show', :id => user.id
assigns[:user].should eql(user)
end
it "renders 'show' template" do
get 'show', :id => user.id
response.should render_template("show")
end
end
describe "GET 'edit'" do
before do
User.should_receive(:find).and_return(user)
end
it "assigns requested user as @user" do
get 'edit', :id => user.id
assigns[:user].should eql(user)
end
it "renders 'edit' template" do
get 'edit', :id => user.id
response.should render_template("edit")
end
end
describe "POST 'update'" do
before do
User.should_receive(:find).and_return(user)
end
context "update successful" do
before(:each) do
user.stub(:update_attributes).and_return(true)
end
it "redirects to users list" do
post "update", :id => user.id, :user => { :email => "new@example.com" }
response.should redirect_to(admin_users_path)
end
it "sets notice on successful update" do
post "update", :id => user.id, :user => { :email => "new@example.com" }
flash[:notice].should_not be_nil
end
end
context "update failed" do
before(:each) do
user.stub(:update_attributes).and_return(false)
end
it "renders 'edit' template" do
post "update", :id => user.id, :user => { :email => "new@example.com" }
response.should render_template("edit")
end
end
end
describe "POST 'destroy'" do
before do
User.should_receive(:find).and_return(user)
end
it "redirects to users list" do
delete "destroy", :id => user.id
response.should redirect_to(admin_users_path)
flash[:notice].should_not be_nil
end
it "sets notice on successful destroy" do
delete 'destroy', :id => user.id
flash[:notice].should_not be_nil
end
end
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/spec/models/role_spec.rb | spec/models/role_spec.rb | require 'spec_helper'
describe Role do
it { should have_db_column(:name).of_type(:string) }
it { should have_and_belong_to_many(:users) }
describe ".admin" do
it "returns role with name 'admin'" do
role = Role.admin
role.name.should == "admin"
end
end
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.