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
frodefi/rails-messaging
https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/config/routes.rb
config/routes.rb
Messaging::Engine.routes.draw do resources :messages do member do delete 'trash' post 'untrash' end collection do delete 'trash' end end post 'search' => 'messages#search' root :to => 'messages#index' end
ruby
MIT
b840f344dbc3af141c124b5f2df0ea9947fe6493
2026-01-04T17:57:44.259159Z
false
gowalla-archive/boxer
https://github.com/gowalla-archive/boxer/blob/a4e1c1d8e3a1649719e0bbd3d605598602248c9f/spec/boxer_spec.rb
spec/boxer_spec.rb
require 'spec_helper' require 'boxer' module MyTestModule def my_test_method; 42 end end module MySecondTestModule def my_second_test_method; 43 end end describe Boxer do describe ".box" do it "can create a box based on a simple hash" do Boxer.box(:foo) do {:working => true} end Boxer.ship(:foo).should eq({:working => true}) end it "defaults to shipping the base view, when it exists" do Boxer.box(:foo) do |box| box.view(:base) { {:working => true} } end Boxer.ship(:foo).should eq({:working => true}) end it "fails if views are specified, but :base is missing" do Boxer.box(:foo) do |box| box.view(:face) { {:working => true} } end expect { Boxer.ship(:foo).should eq({:working => true}) }.to raise_exception(Boxer::ViewMissingError) end it "executes its block in a sandbox context, not a global one" do Boxer.box(:foo) do |box| self end context_obj = Boxer.ship(:foo) context_obj.inspect.should_not include('RSpec') context_obj.inspect.should include('Class') end it "raises a ViewMissing error if given a non-existent view" do Boxer.box(:foo) do |box| box.view(:face) { {:working => true} } end expect { Boxer.ship(:foo).should eq({:working => true}) }.to raise_exception(Boxer::ViewMissingError) end end describe ".clear!" do it "clears all boxes" do Boxer.box(:foo) { {:working => true} } Boxer.clear! Boxer.boxes.should be_empty end end describe ".configure" do it "sets config.box_includes via its supplied block" do Boxer.config.box_includes = [] Boxer.configure {|config| config.box_includes = [MyTestModule] } Boxer.config.box_includes.should include(MyTestModule) end end describe ".ship" do it "accepts arguments and passes them to a box for shipping" do Boxer.box(:bar) do |box, x, y, z| box.view(:base) { {:working => true, :stuff => [x, y, z]} } end Boxer.ship(:bar, 1, 2, 3).should eq( {:working => true, :stuff => [1, 2, 3]} ) end it "allows a hash as the final argument" do Boxer.box(:bar) do |box, x, y, z| box.view(:base) { {:working => true, :stuff => [x, y, z]} } end Boxer.ship(:bar, 1, 2, :banana => true).should eq( {:working => true, :stuff => [1, 2, {:banana => true}]} ) end it "includes modules from config.box_includes in shipping boxes" do Boxer.config.box_includes = [MyTestModule, MySecondTestModule] Boxer.box(:bar) do |box| box.view(:base) { {:a => my_test_method, :b => my_second_test_method} } end Boxer.ship(:bar).should eq({:a => 42, :b => 43}) end it "does not mutate passed in arguments" do Boxer.box(:bar) do |box, num, opts| box.view(:base) { {} } end hash = {:view => :base}.freeze orig_hash = hash.dup Boxer.ship(:bar, 1, hash) hash.should eq(orig_hash) end end describe "#precondition" do it "ships the value emitted in the precondition" do Boxer.box(:foo) do |box, obj| box.precondition {|resp| resp.emit({}) if obj.nil? } box.view(:base) { {:working => true} } end Boxer.ship(:foo, nil).should eq({}) end it "disregards the precondition if no value is emitted" do Boxer.box(:foo) do |box, obj| box.precondition {|resp| resp.emit({}) if obj.nil? } box.view(:base) { {:working => true} } end Boxer.ship(:foo, Object.new).should eq({:working => true}) end it "can handle nil as an emitted precondition value" do Boxer.box(:foo) do |box, obj| box.precondition {|resp| resp.emit(nil) if obj.nil? } box.view(:base) { {:working => true} } end Boxer.ship(:foo, nil).should eq(nil) end it "doesn't remember a fallback value from a previous shipping" do Boxer.box(:foo) do |box, obj| box.precondition {|resp| resp.emit({}) if obj.nil? } box.view(:base) { {:working => true} } end Boxer.ship(:foo, nil).should eq({}) Boxer.ship(:foo, Object.new).should eq({:working => true}) end end describe "#view" do it "allow extending of other views" do Boxer.box(:foo) do |box| box.view(:base) { {:working => true} } box.view(:face, :extends => :base) { {:awesome => true} } end Boxer.ship(:foo, :view => :face).should eq( {:working => true, :awesome => true} ) end it "extends by smashing lesser (extended) views" do Boxer.box(:foo) do |box| box.view(:base) { {:working => true} } box.view(:face, :extends => :base) { {:working => :awesome} } end Boxer.ship(:foo, :view => :face).should eq( {:working => :awesome} ) end it "extends by merging nested keys without overriding" do Boxer.box(:foo) do |box| box.view(:base) { {:working => {:a => 1}} } box.view(:face, :extends => :base) { {:working => {:b => 2}} } end Boxer.ship(:foo, :view => :face).should eq( {:working => {:a => 1, :b => 2}} ) end it "allows extending in a chain of more than two views" do Boxer.box(:foo) do |box| box.view(:base) { {:working => {:a => 1}} } box.view(:face, :extends => :base) { {:working => {:b => 2}} } box.view(:race, :extends => :face) { {:working => {:c => 3}} } end Boxer.ship(:foo, :view => :race).should eq( {:working => {:a => 1, :b => 2, :c => 3}} ) end end end
ruby
MIT
a4e1c1d8e3a1649719e0bbd3d605598602248c9f
2026-01-04T17:57:52.641386Z
false
gowalla-archive/boxer
https://github.com/gowalla-archive/boxer/blob/a4e1c1d8e3a1649719e0bbd3d605598602248c9f/spec/spec_helper.rb
spec/spec_helper.rb
$:.push File.expand_path("../../lib", __FILE__) RSpec.configure do |config| # ... end
ruby
MIT
a4e1c1d8e3a1649719e0bbd3d605598602248c9f
2026-01-04T17:57:52.641386Z
false
gowalla-archive/boxer
https://github.com/gowalla-archive/boxer/blob/a4e1c1d8e3a1649719e0bbd3d605598602248c9f/lib/boxer.rb
lib/boxer.rb
require 'boxer/version' require 'active_support/core_ext/class/attribute_accessors' require 'active_support/core_ext/array/extract_options' require 'active_support/core_ext/hash/deep_merge' require 'ostruct' class Boxer cattr_accessor :config self.config = OpenStruct.new({ :box_includes => [], }) class ViewMissingError < StandardError; end def initialize(name, options={}, &block) @name = name @block = block @fallback = [] @views = {} @views_chain = {} @options = options end ## class methods def self.box(name, options={}, &block) (@boxes ||= {})[name] = self.new(name, options, &block) end def self.boxes @boxes end def self.clear! @boxes = {} end def self.configure yield config end def self.ship(name, *args) fail "Unknown box: #{name.inspect}" unless @boxes.has_key?(name) @boxes[name].ship(*args) end ## instance methods def emit(val) @fallback = [val] end def ship(*args) args = args.dup if args.last.is_a?(Hash) args[-1] = args.last.dup view = args.last.delete(:view) args.slice!(-1) if args.last.empty? end view ||= :base modules = self.class.config.box_includes black_box = Class.new do modules.each do |mod| include mod end end block_result = black_box.new.instance_exec(self, *args, &@block) if @fallback.length > 0 return @fallback.pop elsif @views_chain.any? unless @views_chain.has_key?(view) fail ViewMissingError.new([@name, view].map(&:inspect).join('/')) end return @views_chain[view].inject({}) do |res, view_name| res.deep_merge(@views[view_name].call(*args)) end else return block_result end end def precondition yield self end def view(name, opts={}, &block) @views_chain[name] = [] if opts.has_key?(:extends) ancestors = Array(opts[:extends]).map do |parent| (@views_chain[parent] || []) + [parent] end.flatten.uniq @views_chain[name] += ancestors end @views_chain[name] << name @views[name] = block end end
ruby
MIT
a4e1c1d8e3a1649719e0bbd3d605598602248c9f
2026-01-04T17:57:52.641386Z
false
gowalla-archive/boxer
https://github.com/gowalla-archive/boxer/blob/a4e1c1d8e3a1649719e0bbd3d605598602248c9f/lib/boxer/version.rb
lib/boxer/version.rb
class Boxer VERSION = "1.0.2" end
ruby
MIT
a4e1c1d8e3a1649719e0bbd3d605598602248c9f
2026-01-04T17:57:52.641386Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/app/helpers/application_helper.rb
app/helpers/application_helper.rb
module ApplicationHelper # Returns the full title on a per-page basis def full_title(page_title) base_title = "Bitroad" if page_title.empty? base_title else "#{ page_title } | #{ base_title }" end end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/app/helpers/pages_helper.rb
app/helpers/pages_helper.rb
module PagesHelper end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/app/helpers/listings_helper.rb
app/helpers/listings_helper.rb
module ListingsHelper end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/app/helpers/invoices_helper.rb
app/helpers/invoices_helper.rb
module InvoicesHelper end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/app/controllers/invoices_controller.rb
app/controllers/invoices_controller.rb
require "coinbase" class InvoicesController < ApplicationController def show @invoice = Invoice.friendly.find(params[:id]) if !@invoice.completed coinbase = Coinbase::Client.new(Figaro.env.coinbase_secret) coinbase.send_money @invoice.listing.bitcoin_address, @invoice.listing.price * 0.9 @invoice.update_attributes!(completed: true) elsif @invoice.session_id != request.session_options[:id] redirect_to root_path end end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/app/controllers/listings_controller.rb
app/controllers/listings_controller.rb
require 'bitpay' class ListingsController < ApplicationController def new @listing = Listing.new end def create @listing = Listing.new(listing_params) if @listing.save redirect_to @listing else render "new" end end def show @listing = Listing.find(params[:id]) end def purchase @listing = Listing.find(params[:id]) client = BitPay::Client.new Figaro.env.bitpay_key invoice = @listing.invoices.create(file: @listing.file, session_id: request.session_options[:id]) bp_invoice = client.post 'invoice', { price: @listing.price, currency: 'BTC', redirectURL: "#{root_url[0..-2]}#{invoice_path(invoice)}" } if invoice redirect_to bp_invoice["url"] else redirect_to root_path end end private def listing_params params.require(:listing).permit(:name, :description, :file, :price, :bitcoin_address) end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/app/controllers/pages_controller.rb
app/controllers/pages_controller.rb
class PagesController < ApplicationController def home end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/app/controllers/application_controller.rb
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/app/models/listing.rb
app/models/listing.rb
require 'bitcoin' class Listing < ActiveRecord::Base has_attached_file :file has_many :invoices validate :valid_bitcoin_address validates :name, presence: true validates :description, length: { maximum: 500 } validates :file, presence: true validates :price, presence: true, numericality: { greater_than: 0.005, less_than: 0.05 } validates :bitcoin_address, presence: true private def valid_bitcoin_address if !Bitcoin::valid_address?(bitcoin_address) errors.add(:bitcoin_address, "must be valid") end end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/app/models/invoice.rb
app/models/invoice.rb
class Invoice < ActiveRecord::Base extend FriendlyId friendly_id :code, use: :slugged belongs_to :listing has_attached_file :file validates :file, presence: true validates :session_id, presence: true private def code Digest::SHA1.hexdigest self.file.url end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/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: 'Emanuel', city: cities.first)
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/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 that you check this file into your version control system. ActiveRecord::Schema.define(version: 20131208002027) do create_table "friendly_id_slugs", force: true do |t| t.string "slug", null: false t.integer "sluggable_id", null: false t.string "sluggable_type", limit: 50 t.string "scope" t.datetime "created_at" end add_index "friendly_id_slugs", ["slug", "sluggable_type", "scope"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type_and_scope", unique: true add_index "friendly_id_slugs", ["slug", "sluggable_type"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type" add_index "friendly_id_slugs", ["sluggable_id"], name: "index_friendly_id_slugs_on_sluggable_id" add_index "friendly_id_slugs", ["sluggable_type"], name: "index_friendly_id_slugs_on_sluggable_type" create_table "invoices", force: true do |t| t.boolean "completed" t.integer "listing_id" t.datetime "created_at" t.datetime "updated_at" t.string "file_file_name" t.string "file_content_type" t.integer "file_file_size" t.datetime "file_updated_at" t.string "slug" t.string "session_id" end add_index "invoices", ["slug"], name: "index_invoices_on_slug", unique: true create_table "listings", force: true do |t| t.string "name" t.text "description" t.decimal "price" t.string "bitcoin_address" t.datetime "created_at" t.datetime "updated_at" t.string "file_file_name" t.string "file_content_type" t.integer "file_file_size" t.datetime "file_updated_at" end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/db/migrate/20131207235911_add_slug_to_invoice.rb
db/migrate/20131207235911_add_slug_to_invoice.rb
class AddSlugToInvoice < ActiveRecord::Migration def change add_column :invoices, :slug, :string add_index :invoices, :slug, unique: true end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/db/migrate/20131207231811_create_invoices.rb
db/migrate/20131207231811_create_invoices.rb
class CreateInvoices < ActiveRecord::Migration def change create_table :invoices do |t| t.boolean :completed t.belongs_to :listing t.timestamps end end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/db/migrate/20131207235839_create_friendly_id_slugs.rb
db/migrate/20131207235839_create_friendly_id_slugs.rb
class CreateFriendlyIdSlugs < ActiveRecord::Migration def change create_table :friendly_id_slugs do |t| t.string :slug, :null => false t.integer :sluggable_id, :null => false t.string :sluggable_type, :limit => 50 t.string :scope t.datetime :created_at end add_index :friendly_id_slugs, :sluggable_id add_index :friendly_id_slugs, [:slug, :sluggable_type] add_index :friendly_id_slugs, [:slug, :sluggable_type, :scope], :unique => true add_index :friendly_id_slugs, :sluggable_type end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/db/migrate/20131207231916_add_attachment_file_to_invoices.rb
db/migrate/20131207231916_add_attachment_file_to_invoices.rb
class AddAttachmentFileToInvoices < ActiveRecord::Migration def self.up change_table :invoices do |t| t.attachment :file end end def self.down drop_attached_file :invoices, :file end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/db/migrate/20131208002027_add_session_id_to_invoice.rb
db/migrate/20131208002027_add_session_id_to_invoice.rb
class AddSessionIdToInvoice < ActiveRecord::Migration def change add_column :invoices, :session_id, :string end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/db/migrate/20131207190926_add_attachment_file_to_listings.rb
db/migrate/20131207190926_add_attachment_file_to_listings.rb
class AddAttachmentFileToListings < ActiveRecord::Migration def self.up change_table :listings do |t| t.attachment :file end end def self.down drop_attached_file :listings, :file end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/db/migrate/20131207190900_create_listings.rb
db/migrate/20131207190900_create_listings.rb
class CreateListings < ActiveRecord::Migration def change create_table :listings do |t| t.string :name t.text :description t.decimal :price t.string :bitcoin_address t.timestamps end end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/test/test_helper.rb
test/test_helper.rb
ENV["RAILS_ENV"] ||= "test" require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' class ActiveSupport::TestCase ActiveRecord::Migration.check_pending! # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. # # Note: You'll currently still have to declare fixtures explicitly in integration tests # -- they do not yet inherit this setting fixtures :all # Add more helper methods to be used by all tests here... end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/test/helpers/listings_helper_test.rb
test/helpers/listings_helper_test.rb
require 'test_helper' class ListingsHelperTest < ActionView::TestCase end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/test/helpers/invoices_helper_test.rb
test/helpers/invoices_helper_test.rb
require 'test_helper' class InvoicesHelperTest < ActionView::TestCase end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/test/helpers/pages_helper_test.rb
test/helpers/pages_helper_test.rb
require 'test_helper' class PagesHelperTest < ActionView::TestCase end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/test/controllers/invoices_controller_test.rb
test/controllers/invoices_controller_test.rb
require 'test_helper' class InvoicesControllerTest < ActionController::TestCase test "should get show" do get :show assert_response :success end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/test/controllers/listings_controller_test.rb
test/controllers/listings_controller_test.rb
require 'test_helper' class ListingsControllerTest < ActionController::TestCase test "should get new" do get :new assert_response :success end test "should get show" do get :show assert_response :success end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/test/controllers/pages_controller_test.rb
test/controllers/pages_controller_test.rb
require 'test_helper' class PagesControllerTest < ActionController::TestCase test "should get home" do get :home assert_response :success end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/test/models/listing_test.rb
test/models/listing_test.rb
require 'test_helper' class ListingTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/test/models/invoice_test.rb
test/models/invoice_test.rb
require 'test_helper' class InvoiceTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/config/application.rb
config/application.rb
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) module Bitroad class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/config/environment.rb
config/environment.rb
# Load the Rails application. require File.expand_path('../application', __FILE__) # Initialize the Rails application. Bitroad::Application.initialize!
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/config/routes.rb
config/routes.rb
Bitroad::Application.routes.draw do resources :listings do member do patch "purchase" end end resources :invoices get "home", to: redirect("/") root to: "pages#home" %w[home].each do |page| get page, controller: "pages", action: page end end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/config/boot.rb
config/boot.rb
# Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/config/initializers/simple_form_foundation.rb
config/initializers/simple_form_foundation.rb
# Use this setup block to configure all options available in SimpleForm. SimpleForm.setup do |config| config.wrappers :foundation, class: :input, hint_class: :field_with_hint, error_class: :error do |b| b.use :html5 b.use :placeholder b.optional :maxlength b.optional :pattern b.optional :min_max b.optional :readonly b.use :label_input b.use :error, wrap_with: { tag: :small } # Uncomment the following line to enable hints. The line is commented out by default since Foundation # does't provide styles for hints. You will need to provide your own CSS styles for hints. b.use :hint, wrap_with: { tag: :span, class: :hint } end # CSS class for buttons config.button_class = 'button' # CSS class to add for error notification helper. config.error_notification_class = 'alert-box alert' # The default wrapper to be used by the FormBuilder. config.default_wrapper = :foundation end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/config/initializers/filter_parameter_logging.rb
config/initializers/filter_parameter_logging.rb
# Be sure to restart your server when you modify this file. # Configure sensitive parameters which will be filtered from the log file. Rails.application.config.filter_parameters += [:password]
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/config/initializers/session_store.rb
config/initializers/session_store.rb
# Be sure to restart your server when you modify this file. Bitroad::Application.config.session_store :cookie_store, key: '_bitroad_session'
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/config/initializers/friendly_id.rb
config/initializers/friendly_id.rb
# FriendlyId Global Configuration # # Use this to set up shared configuration options for your entire application. # Any of the configuration options shown here can also be applied to single # models by passing arguments to the `friendly_id` class method or defining # methods in your model. # # To learn more, check out the guide: # # http://norman.github.io/friendly_id/file.Guide.html FriendlyId.defaults do |config| # ## Reserved Words # # Some words could conflict with Rails's routes when used as slugs, or are # undesirable to allow as slugs. Edit this list as needed for your app. config.use :reserved config.reserved_words = %w(new edit index session login logout users admin stylesheets assets javascripts images) # ## Friendly Finders # # Uncomment this to use friendly finders in all models. By default, if # you wish to find a record by its friendly id, you must do: # # MyModel.friendly.find('foo') # # If you uncomment this, you can do: # # MyModel.find('foo') # # This is significantly more convenient but may not be appropriate for # all applications, so you must explicity opt-in to this behavior. You can # always also configure it on a per-model basis if you prefer. # # Something else to consider is that using the :finders addon boosts # performance because it will avoid Rails-internal code that makes runtime # calls to `Module.extend`. # # config.use :finders # # ## Slugs # # Most applications will use the :slugged module everywhere. If you wish # to do so, uncomment the following line. # # config.use :slugged # # By default, FriendlyId's :slugged addon expects the slug column to be named # 'slug', but you can change it if you wish. # # config.slug_column = 'slug' # # When FriendlyId can not generate a unique ID from your base method, it appends # a UUID, separated by a single dash. You can configure the character used as the # separator. If you're upgrading from FriendlyId 4, you may wish to replace this # with two dashes. # # config.sequence_separator = '-' # # ## Tips and Tricks # # ### Controlling when slugs are generated # # As of FriendlyId 5.0, new slugs are generated only when the slug field is # nil, but you if you're using a column as your base method can change this # behavior by overriding the `should_generate_new_friendly_id` method that # FriendlyId adds to your model. The change below makes FriendlyId 5.0 behave # more like 4.0. # # config.use Module.new { # def should_generate_new_friendly_id? # slug.blank? || <your_column_name_here>_changed? # end # } # # FriendlyId uses Rails's `parameterize` method to generate slugs, but for # languages that don't use the Roman alphabet, that's not usually suffient. Here # we use the Babosa library to transliterate Russian Cyrillic slugs to ASCII. If # you use this, don't forget to add "babosa" to your Gemfile. # # config.use Module.new { # def normalize_friendly_id(text) # text.to_slug.normalize! :transliterations => [:russian, :latin] # end # } end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/config/initializers/wrap_parameters.rb
config/initializers/wrap_parameters.rb
# Be sure to restart your server when you modify this file. # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] if respond_to?(:wrap_parameters) end # To enable root element in JSON for ActiveRecord objects. # ActiveSupport.on_load(:active_record) do # self.include_root_in_json = true # end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/config/initializers/inflections.rb
config/initializers/inflections.rb
# Be sure to restart your server when you modify this file. # Add new inflection rules using the following format. Inflections # are locale specific, and you may define rules for as many different # locales as you wish. All of these examples are active by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # inflect.uncountable %w( fish sheep ) # end # These inflection rules are supported but not enabled by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.acronym 'RESTful' # end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/config/initializers/simple_form.rb
config/initializers/simple_form.rb
# Use this setup block to configure all options available in SimpleForm. SimpleForm.setup do |config| # Wrappers are used by the form builder to generate a # complete input. You can remove any component from the # wrapper, change the order or even add your own to the # stack. The options given below are used to wrap the # whole input. config.wrappers :default, class: :input, hint_class: :field_with_hint, error_class: :field_with_errors do |b| ## Extensions enabled by default # Any of these extensions can be disabled for a # given input by passing: `f.input EXTENSION_NAME => false`. # You can make any of these extensions optional by # renaming `b.use` to `b.optional`. # Determines whether to use HTML5 (:email, :url, ...) # and required attributes b.use :html5 # Calculates placeholders automatically from I18n # You can also pass a string as f.input placeholder: "Placeholder" b.use :placeholder ## Optional extensions # They are disabled unless you pass `f.input EXTENSION_NAME => :lookup` # to the input. If so, they will retrieve the values from the model # if any exists. If you want to enable the lookup for any of those # extensions by default, you can change `b.optional` to `b.use`. # Calculates maxlength from length validations for string inputs b.optional :maxlength # Calculates pattern from format validations for string inputs b.optional :pattern # Calculates min and max from length validations for numeric inputs b.optional :min_max # Calculates readonly automatically from readonly attributes b.optional :readonly ## Inputs b.use :label_input b.use :hint, wrap_with: { tag: :span, class: :hint } b.use :error, wrap_with: { tag: :span, class: :error } end # The default wrapper to be used by the FormBuilder. config.default_wrapper = :default # Define the way to render check boxes / radio buttons with labels. # Defaults to :nested for bootstrap config. # inline: input + label # nested: label > input config.boolean_style = :nested # Default class for buttons config.button_class = 'btn' # Method used to tidy up errors. Specify any Rails Array method. # :first lists the first message for each field. # Use :to_sentence to list all errors for each field. # config.error_method = :first # Default tag used for error notification helper. config.error_notification_tag = :div # CSS class to add for error notification helper. config.error_notification_class = 'alert alert-error' # ID to add for error notification helper. # config.error_notification_id = nil # Series of attempts to detect a default label method for collection. # config.collection_label_methods = [ :to_label, :name, :title, :to_s ] # Series of attempts to detect a default value method for collection. # config.collection_value_methods = [ :id, :to_s ] # You can wrap a collection of radio/check boxes in a pre-defined tag, defaulting to none. # config.collection_wrapper_tag = nil # You can define the class to use on all collection wrappers. Defaulting to none. # config.collection_wrapper_class = nil # You can wrap each item in a collection of radio/check boxes with a tag, # defaulting to :span. Please note that when using :boolean_style = :nested, # SimpleForm will force this option to be a label. # config.item_wrapper_tag = :span # You can define a class to use in all item wrappers. Defaulting to none. # config.item_wrapper_class = nil # How the label text should be generated altogether with the required text. # config.label_text = lambda { |label, required| "#{required} #{label}" } # You can define the class to use on all labels. Default is nil. config.label_class = 'control-label' # You can define the class to use on all forms. Default is simple_form. # config.form_class = :simple_form # You can define which elements should obtain additional classes # config.generate_additional_classes_for = [:wrapper, :label, :input] # Whether attributes are required by default (or not). Default is true. # config.required_by_default = true # Tell browsers whether to use the native HTML5 validations (novalidate form option). # These validations are enabled in SimpleForm's internal config but disabled by default # in this configuration, which is recommended due to some quirks from different browsers. # To stop SimpleForm from generating the novalidate option, enabling the HTML5 validations, # change this configuration to true. config.browser_validations = false # Collection of methods to detect if a file type was given. # config.file_methods = [ :mounted_as, :file?, :public_filename ] # Custom mappings for input types. This should be a hash containing a regexp # to match as key, and the input type that will be used when the field name # matches the regexp as value. # config.input_mappings = { /count/ => :integer } # Custom wrappers for input types. This should be a hash containing an input # type as key and the wrapper that will be used for all inputs with specified type. # config.wrapper_mappings = { string: :prepend } # Default priority for time_zone inputs. # config.time_zone_priority = nil # Default priority for country inputs. # config.country_priority = nil # When false, do not use translations for labels. # config.translate_labels = true # Automatically discover new inputs in Rails' autoload path. # config.inputs_discovery = true # Cache SimpleForm inputs discovery # config.cache_discovery = !Rails.env.development? # Default class for inputs # config.input_class = nil end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/config/initializers/backtrace_silencers.rb
config/initializers/backtrace_silencers.rb
# Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. # Rails.backtrace_cleaner.remove_silencers!
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/config/initializers/mime_types.rb
config/initializers/mime_types.rb
# Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf # Mime::Type.register_alias "text/html", :iphone
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/config/initializers/secret_token.rb
config/initializers/secret_token.rb
# Be sure to restart your server when you modify this file. # Your secret key is used for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. # You can use `rake secret` to generate a secure secret key. # Make sure your secret_key_base is kept private # if you're sharing your code publicly. Bitroad::Application.config.secret_key_base = '0bcfc94d605d63ec905c1bb20912c42ad7d3b952fed6aae2846e0234431feddeba4f322081509b3a215ca0b4d70c2db324a2599896139e188a5c29f80e6abfda'
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/config/environments/test.rb
config/environments/test.rb
Bitroad::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Do not eager load code on boot. This avoids loading your whole application # just for the purpose of running a single test. If you are using a tool that # preloads Rails for running tests, you may have to set it to true. config.eager_load = false # Configure static asset server for tests with Cache-Control for performance. config.serve_static_assets = true config.static_cache_control = "public, max-age=3600" # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates. config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/config/environments/development.rb
config/environments/development.rb
Bitroad::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
zachlatta/bitroad
https://github.com/zachlatta/bitroad/blob/aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38/config/environments/production.rb
config/environments/production.rb
Bitroad::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both thread web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Enable Rack::Cache to put a simple HTTP cache in front of your application # Add `rack-cache` to your Gemfile before enabling this. # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid. # config.action_dispatch.rack_cache = true # Disable Rails's static asset server (Apache or nginx will already do this). config.serve_static_assets = false # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Generate digests for assets URLs. config.assets.digest = true # Version of your assets, change this if you want to expire all your assets. config.assets.version = '1.0' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Set to :debug to see everything in the log. config.log_level = :info # Prepend all log lines with the following tags. # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups. # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production. # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # config.assets.precompile += %w( search.js ) # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Disable automatic flushing of the log to improve performance. # config.autoflush_log = false # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Amazon S3 settings for Paperclip uploads config.paperclip_defaults = { storage: :s3, s3_protocol: 'http', s3_credentials: { bucket: ENV["AWS_BUCKET"], access_key_id: ENV["AWS_ACCESS_KEY_ID"], secret_access_key: ENV["AWS_SECRET_ACCESS_KEY"] } } end
ruby
MIT
aee67f2cc87fbbcb467e098b9fcf178b5b9cfa38
2026-01-04T17:57:48.681008Z
false
nickelser/suo
https://github.com/nickelser/suo/blob/7bb28cc0073bf7d6dc8b30f26b11a9b520678024/test/test_helper.rb
test/test_helper.rb
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__) if ENV["CODECLIMATE_REPO_TOKEN"] require "codeclimate-test-reporter" CodeClimate::TestReporter.start end require "suo" require "thread" require "minitest/autorun" require "minitest/benchmark" ENV["SUO_TEST"] = "true"
ruby
MIT
7bb28cc0073bf7d6dc8b30f26b11a9b520678024
2026-01-04T17:57:58.197698Z
false
nickelser/suo
https://github.com/nickelser/suo/blob/7bb28cc0073bf7d6dc8b30f26b11a9b520678024/test/client_test.rb
test/client_test.rb
require "test_helper" TEST_KEY = "suo_test_key".freeze module ClientTests def client(options = {}) @client.class.new(options[:key] || TEST_KEY, options.merge(client: @client.client)) end def test_throws_failed_error_on_bad_client assert_raises(Suo::LockClientError) do client = @client.class.new(TEST_KEY, client: {}) client.lock end end def test_single_resource_locking lock1 = @client.lock refute_nil lock1 locked = @client.locked? assert_equal true, locked lock2 = @client.lock assert_nil lock2 @client.unlock(lock1) locked = @client.locked? assert_equal false, locked end def test_lock_with_custom_token token = 'foo-bar' lock = @client.lock token assert_equal lock, token end def test_empty_lock_on_invalid_data @client.send(:initial_set, "bad value") assert_equal false, @client.locked? end def test_clear lock1 = @client.lock refute_nil lock1 @client.clear assert_equal false, @client.locked? end def test_multiple_resource_locking @client = client(resources: 2) lock1 = @client.lock refute_nil lock1 assert_equal false, @client.locked? lock2 = @client.lock refute_nil lock2 assert_equal true, @client.locked? @client.unlock(lock1) assert_equal false, @client.locked? assert_equal 1, @client.locks.size @client.unlock(lock2) assert_equal false, @client.locked? assert_equal 0, @client.locks.size end def test_block_single_resource_locking locked = false @client.lock { locked = true } assert_equal true, locked end def test_block_unlocks_on_exception assert_raises(RuntimeError) do @client.lock{ fail "Test" } end assert_equal false, @client.locked? end def test_readme_example output = Queue.new @client = client(resources: 2) threads = [] threads << Thread.new { @client.lock { output << "One"; sleep 0.5 } } threads << Thread.new { @client.lock { output << "Two"; sleep 0.5 } } sleep 0.1 threads << Thread.new { @client.lock { output << "Three" } } threads.each(&:join) ret = [] ret << (output.size > 0 ? output.pop : nil) ret << (output.size > 0 ? output.pop : nil) ret.sort! assert_equal 0, output.size assert_equal %w(One Two), ret assert_equal false, @client.locked? end def test_block_multiple_resource_locking success_counter = Queue.new failure_counter = Queue.new @client = client(acquisition_timeout: 0.9, resources: 50) 100.times.map do |i| Thread.new do success = @client.lock do sleep(3) success_counter << i end failure_counter << i unless success end end.each(&:join) assert_equal 50, success_counter.size assert_equal 50, failure_counter.size assert_equal false, @client.locked? end def test_block_multiple_resource_locking_longer_timeout success_counter = Queue.new failure_counter = Queue.new @client = client(acquisition_timeout: 3, resources: 50) 100.times.map do |i| Thread.new do success = @client.lock do sleep(0.5) success_counter << i end failure_counter << i unless success end end.each(&:join) assert_equal 100, success_counter.size assert_equal 0, failure_counter.size assert_equal false, @client.locked? end def test_unstale_lock_acquisition success_counter = Queue.new failure_counter = Queue.new @client = client(stale_lock_expiration: 0.5) t1 = Thread.new { @client.lock { sleep 0.6; success_counter << 1 } } sleep 0.3 t2 = Thread.new do locked = @client.lock { success_counter << 1 } failure_counter << 1 unless locked end [t1, t2].each(&:join) assert_equal 1, success_counter.size assert_equal 1, failure_counter.size assert_equal false, @client.locked? end def test_stale_lock_acquisition success_counter = Queue.new failure_counter = Queue.new @client = client(stale_lock_expiration: 0.5) t1 = Thread.new { @client.lock { sleep 0.6; success_counter << 1 } } sleep 0.55 t2 = Thread.new do locked = @client.lock { success_counter << 1 } failure_counter << 1 unless locked end [t1, t2].each(&:join) assert_equal 2, success_counter.size assert_equal 0, failure_counter.size assert_equal false, @client.locked? end def test_refresh @client = client(stale_lock_expiration: 0.5) lock1 = @client.lock assert_equal true, @client.locked? @client.refresh(lock1) assert_equal true, @client.locked? sleep 0.55 assert_equal false, @client.locked? lock2 = @client.lock @client.refresh(lock1) assert_equal true, @client.locked? @client.unlock(lock1) # edge case with refresh lock in the middle assert_equal true, @client.locked? @client.clear assert_equal false, @client.locked? @client.refresh(lock2) assert_equal true, @client.locked? @client.unlock(lock2) # now finally unlocked assert_equal false, @client.locked? end def test_block_refresh success_counter = Queue.new failure_counter = Queue.new @client = client(stale_lock_expiration: 0.5) t1 = Thread.new do @client.lock do |token| sleep 0.6 @client.refresh(token) sleep 1 success_counter << 1 end end t2 = Thread.new do sleep 0.8 locked = @client.lock { success_counter << 1 } failure_counter << 1 unless locked end [t1, t2].each(&:join) assert_equal 1, success_counter.size assert_equal 1, failure_counter.size assert_equal false, @client.locked? end def test_refresh_multi success_counter = Queue.new failure_counter = Queue.new @client = client(stale_lock_expiration: 0.5, resources: 2) t1 = Thread.new do @client.lock do |token| sleep 0.4 @client.refresh(token) success_counter << 1 sleep 0.5 end end t2 = Thread.new do sleep 0.55 locked = @client.lock do success_counter << 1 sleep 0.5 end failure_counter << 1 unless locked end t3 = Thread.new do sleep 0.75 locked = @client.lock { success_counter << 1 } failure_counter << 1 unless locked end [t1, t2, t3].each(&:join) assert_equal 2, success_counter.size assert_equal 1, failure_counter.size assert_equal false, @client.locked? end def test_increment_reused_client i = 0 threads = 2.times.map do Thread.new do @client.lock { i += 1 } end end threads.each(&:join) assert_equal 2, i assert_equal false, @client.locked? end def test_increment_new_client i = 0 threads = 2.times.map do Thread.new do # note this is the method that generates a *new* client client.lock { i += 1 } end end threads.each(&:join) assert_equal 2, i assert_equal false, @client.locked? end end class TestBaseClient < Minitest::Test def setup @client = Suo::Client::Base.new(TEST_KEY, client: {}) end def test_not_implemented assert_raises(NotImplementedError) do @client.send(:get) end assert_raises(NotImplementedError) do @client.send(:set, "", "") end assert_raises(NotImplementedError) do @client.send(:initial_set) end assert_raises(NotImplementedError) do @client.send(:clear) end end end class TestMemcachedClient < Minitest::Test include ClientTests def setup @dalli = Dalli::Client.new("127.0.0.1:11211") @client = Suo::Client::Memcached.new(TEST_KEY) teardown end def teardown @dalli.delete(TEST_KEY) end end class TestRedisClient < Minitest::Test include ClientTests def setup @redis = Redis.new @client = Suo::Client::Redis.new(TEST_KEY) teardown end def teardown @redis.del(TEST_KEY) end end class TestLibrary < Minitest::Test def test_that_it_has_a_version_number refute_nil ::Suo::VERSION end end
ruby
MIT
7bb28cc0073bf7d6dc8b30f26b11a9b520678024
2026-01-04T17:57:58.197698Z
false
nickelser/suo
https://github.com/nickelser/suo/blob/7bb28cc0073bf7d6dc8b30f26b11a9b520678024/lib/suo.rb
lib/suo.rb
require "securerandom" require "monitor" require "dalli" require "dalli/cas/client" require "redis" require "msgpack" require "suo/version" require "suo/errors" require "suo/client/base" require "suo/client/memcached" require "suo/client/redis"
ruby
MIT
7bb28cc0073bf7d6dc8b30f26b11a9b520678024
2026-01-04T17:57:58.197698Z
false
nickelser/suo
https://github.com/nickelser/suo/blob/7bb28cc0073bf7d6dc8b30f26b11a9b520678024/lib/suo/version.rb
lib/suo/version.rb
module Suo VERSION = "0.4.0".freeze end
ruby
MIT
7bb28cc0073bf7d6dc8b30f26b11a9b520678024
2026-01-04T17:57:58.197698Z
false
nickelser/suo
https://github.com/nickelser/suo/blob/7bb28cc0073bf7d6dc8b30f26b11a9b520678024/lib/suo/errors.rb
lib/suo/errors.rb
module Suo class LockClientError < StandardError; end end
ruby
MIT
7bb28cc0073bf7d6dc8b30f26b11a9b520678024
2026-01-04T17:57:58.197698Z
false
nickelser/suo
https://github.com/nickelser/suo/blob/7bb28cc0073bf7d6dc8b30f26b11a9b520678024/lib/suo/client/redis.rb
lib/suo/client/redis.rb
module Suo module Client class Redis < Base OK_STR = "OK".freeze def initialize(key, options = {}) options[:client] ||= ::Redis.new(options[:connection] || {}) super end def clear with { |r| r.del(@key) } end private def with(&block) if @client.respond_to?(:with) @client.with(&block) else yield @client end end def get [with { |r| r.get(@key) }, nil] end def set(newval, _, expire: false) ret = with do |r| r.multi do |rr| if expire rr.setex(@key, @options[:ttl], newval) else rr.set(@key, newval) end end end ret && ret[0] == OK_STR end def synchronize with { |r| r.watch(@key) { yield } } ensure with { |r| r.unwatch } end def initial_set(val = BLANK_STR) set(val, nil) nil end end end end
ruby
MIT
7bb28cc0073bf7d6dc8b30f26b11a9b520678024
2026-01-04T17:57:58.197698Z
false
nickelser/suo
https://github.com/nickelser/suo/blob/7bb28cc0073bf7d6dc8b30f26b11a9b520678024/lib/suo/client/memcached.rb
lib/suo/client/memcached.rb
module Suo module Client class Memcached < Base def initialize(key, options = {}) options[:client] ||= Dalli::Client.new(options[:connection] || ENV["MEMCACHE_SERVERS"] || "127.0.0.1:11211") super end def clear @client.with { |client| client.delete(@key) } end private def get @client.with { |client| client.get_cas(@key) } end def set(newval, cas, expire: false) if expire @client.with { |client| client.set_cas(@key, newval, cas, @options[:ttl]) } else @client.with { |client| client.set_cas(@key, newval, cas) } end end def initial_set(val = BLANK_STR) @client.with do |client| client.set(@key, val) _val, cas = client.get_cas(@key) cas end end end end end
ruby
MIT
7bb28cc0073bf7d6dc8b30f26b11a9b520678024
2026-01-04T17:57:58.197698Z
false
nickelser/suo
https://github.com/nickelser/suo/blob/7bb28cc0073bf7d6dc8b30f26b11a9b520678024/lib/suo/client/base.rb
lib/suo/client/base.rb
module Suo module Client class Base DEFAULT_OPTIONS = { acquisition_timeout: 0.1, acquisition_delay: 0.01, stale_lock_expiration: 3600, resources: 1, ttl: 60, }.freeze BLANK_STR = "".freeze attr_accessor :client, :key, :resources, :options include MonitorMixin def initialize(key, options = {}) fail "Client required" unless options[:client] @options = DEFAULT_OPTIONS.merge(options) @retry_count = (@options[:acquisition_timeout] / @options[:acquisition_delay].to_f).ceil @client = @options[:client] @resources = @options[:resources].to_i @key = key super() # initialize Monitor mixin for thread safety end def lock(custom_token = nil) token = acquire_lock(custom_token) if block_given? && token begin yield ensure unlock(token) end else token end end def locked? locks.size >= resources end def locks val, _ = get cleared_locks = deserialize_and_clear_locks(val) cleared_locks end def refresh(token) retry_with_timeout do val, cas = get cas = initial_set if val.nil? cleared_locks = deserialize_and_clear_locks(val) refresh_lock(cleared_locks, token) break if set(serialize_locks(cleared_locks), cas, expire: cleared_locks.empty?) end end def unlock(token) return unless token retry_with_timeout do val, cas = get break if val.nil? cleared_locks = deserialize_and_clear_locks(val) acquisition_lock = remove_lock(cleared_locks, token) break unless acquisition_lock break if set(serialize_locks(cleared_locks), cas, expire: cleared_locks.empty?) end rescue LockClientError => _ # rubocop:disable Lint/HandleExceptions # ignore - assume success due to optimistic locking end def clear fail NotImplementedError end private attr_accessor :retry_count def acquire_lock(token = nil) token ||= SecureRandom.base64(16) retry_with_timeout do val, cas = get cas = initial_set if val.nil? cleared_locks = deserialize_and_clear_locks(val) if cleared_locks.size < resources add_lock(cleared_locks, token) newval = serialize_locks(cleared_locks) return token if set(newval, cas) end end nil end def get fail NotImplementedError end def set(newval, cas) # rubocop:disable Lint/UnusedMethodArgument fail NotImplementedError end def initial_set(val = BLANK_STR) # rubocop:disable Lint/UnusedMethodArgument fail NotImplementedError end def synchronize mon_synchronize { yield } end def retry_with_timeout start = Process.clock_gettime(Process::CLOCK_MONOTONIC) retry_count.times do elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start break if elapsed >= options[:acquisition_timeout] synchronize do yield end sleep(rand(options[:acquisition_delay] * 1000).to_f / 1000) end rescue => _ raise LockClientError end def serialize_locks(locks) MessagePack.pack(locks.map { |time, token| [time.to_f, token] }) end def deserialize_and_clear_locks(val) clear_expired_locks(deserialize_locks(val)) end def deserialize_locks(val) unpacked = (val.nil? || val == BLANK_STR) ? [] : MessagePack.unpack(val) unpacked.map do |time, token| [Time.at(time), token] end rescue EOFError, MessagePack::MalformedFormatError => _ [] end def clear_expired_locks(locks) expired = Time.now - options[:stale_lock_expiration] locks.reject { |time, _| time < expired } end def add_lock(locks, token, time = Time.now.to_f) locks << [time, token] end def remove_lock(locks, acquisition_token) lock = locks.find { |_, token| token == acquisition_token } locks.delete(lock) end def refresh_lock(locks, acquisition_token) remove_lock(locks, acquisition_token) add_lock(locks, acquisition_token) end end end end
ruby
MIT
7bb28cc0073bf7d6dc8b30f26b11a9b520678024
2026-01-04T17:57:58.197698Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/gems.rb
gems.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. source "https://rubygems.org" # Specify your gem's dependencies in bake.gemspec gemspec group :maintenance, optional: true do gem "bake-modernize" gem "bake-gem" gem "bake-releases" gem "utopia-project" end group :test do gem "sus" gem "covered" gem "decode" gem "rubocop" gem "rubocop-md" gem "rubocop-socketry" gem "bake-test" gem "bake-test-external" end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/bake.rb
bake.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. # Update the project documentation with the new version number. # # @parameter version [String] The new version number. def after_gem_release_version_increment(version) context["releases:update"].call(version) context["utopia:project:update"].call end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake.rb
test/bake.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require "bake" describe Bake do it "has a version number" do expect(Bake::VERSION).to be =~ /\d+\.\d+\.\d+/ end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/recipe.rb
test/bake/recipe.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2025, by Samuel Williams. require "bake/recipe" class TestObject < Bake::Base def test(*arguments, **options, &block) [arguments, options, block] end end describe Bake::Recipe do let(:instance) {TestObject.new} let(:name) {"test"} let(:recipe) {subject.new(instance, name)} with "#call" do it "can call method with no arguments" do result = recipe.call expect(result).to be == [[], {}, nil] end it "can call method with arguments" do result = recipe.call(1, 2, 3) expect(result).to be == [[1, 2, 3], {}, nil] end it "can call method with options" do result = recipe.call(option: 1) expect(result).to be == [[], {option: 1}, nil] end it "can call method with block" do block = ->{} result = recipe.call(&block) expect(result).to be == [[], {}, block] end end with "#output?" do it "returns false by default" do expect(recipe.output?).to be == false end it "returns true if instance has output?" do expect(instance).to receive(:output?).and_return(true) expect(recipe.output?).to be == true end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/type.rb
test/bake/type.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require "bake/type" require "bake/context" describe Bake::Type do it "can use | operator" do type = Bake::Type::Array(Bake::Type::Integer) | Bake::Type::String end with "test project" do let(:bakefile) {File.expand_path(".test-project/bake.rb", __dir__)} let(:context) {Bake::Context.load(bakefile)} it "should parse integer" do result = context.call("types:square", "5") expect(result).to be_a(Integer) expect(result).to be == 25 end it "should parse an array of integers" do result = context.call("types:sum", "1,2,3,4,5") expect(result).to be_a(Integer) expect(result).to be == 15 end it "should parse a symbol and a hash" do result = context.call("types:index", "foo", "foo:10,bar:20") expect(result).to be_a(Integer) expect(result).to be == 10 end it "should parse a JSON string" do result = context.call("types:inspect", '{"x": 10}') expect(result).to be_a(Hash) expect(result).to be == {"x" => 10} end it "should parse a URI string" do result = context.call("types:hostname", "https://www.google.com") expect(result).to be_a(String) expect(result).to be == "www.google.com" end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/base.rb
test/bake/base.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require "bake/base" describe Bake::Base do let(:path) {["foo", "bar"]} let(:base) {subject.derive(path)} it "has a path" do expect(base::PATH).to be == path end it "formats nicely" do expect(base.inspect).to be == "Bake::Base[foo:bar]" end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/context.rb
test/bake/context.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require "bake/context" describe Bake::Context do let(:bakefile) {File.expand_path(".test-project/bake.rb", __dir__)} let(:context) {subject.load(bakefile)} it "can invoke root task" do recipe = context.lookup("doot") expect(recipe).to receive(:call) expect(recipe.instance).to receive(:doot) context.call("doot") end with "#invoke" do let(:instance) {context.lookup("invoke:task1").instance} it "can invoke another task" do expect(instance).to receive(:task1).with("argument", option: "option") expect(instance).to receive(:task2) context.call("invoke:task2") end it "can invoke task with required argument" do context.call("invoke:task3", "argument") end end with "#lookup" do it "can lookup method on parent instance" do parent = context.lookup("parent") expect(parent).not.to be_nil expect(parent.instance).to be(:respond_to?, :parent) end it "can lookup method on child instance" do child = context.lookup("parent:child") expect(child).not.to be_nil expect(child.instance).to be(:respond_to?, :child) end it "can lookup method on sibling instance" do parent = context.lookup("parent:sibling") expect(parent).not.to be_nil expect(parent.instance).to be(:respond_to?, :parent) end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/type/array.rb
test/bake/type/array.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2023-2025, by Samuel Williams. require "bake/type/array" require "bake/type" describe Bake::Type::Array do let(:type) {Bake::Type.parse(typename)} with typename: "Array(Integer)" do it "can parse an array of integers" do expect(type.parse("1,2,3,4,5")).to be == [1, 2, 3, 4, 5] end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/type/output.rb
test/bake/type/output.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2023-2025, by Samuel Williams. require "bake/type/output" describe Bake::Type::Output do let(:value) {subject.parse(text)} with text: "-" do it "should be stdout" do expect(value).to be_a(IO) expect(value).to be == $stdout end end with text: File.expand_path("output.txt", __dir__) do it "should open file" do expect(value).to be_a(IO) end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/type/boolean.rb
test/bake/type/boolean.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2023-2025, by Samuel Williams. require "bake/type/boolean" describe Bake::Type::Boolean do let(:value) {subject.parse(text)} with text: "true" do it "should be true" do expect(value).to be_a(TrueClass) expect(value).to be == true end end with text: "false" do it "should be false" do expect(value).to be_a(FalseClass) expect(value).to be == false end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/type/input.rb
test/bake/type/input.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2023-2025, by Samuel Williams. require "bake/type/input" describe Bake::Type::Input do let(:value) {subject.parse(text)} with text: "-" do it "should be stdin" do expect(value).to be_a(IO) expect(value).to be == $stdin end end with text: File.expand_path("input.txt", __dir__) do it "should open file" do expect(value).to be_a(IO) expect(value.gets).to be == "Hello World!\n" end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/type/nil.rb
test/bake/type/nil.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2023-2025, by Samuel Williams. require "bake/type/nil" describe Bake::Type::Nil do let(:value) {subject.parse(text)} with text: "nil" do it "should be nil" do expect(value).to be_a(NilClass) expect(value).to be == nil end end with text: "null" do it "should be nil" do expect(value).to be_a(NilClass) expect(value).to be == nil end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/command/list.rb
test/bake/command/list.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require "bake/command/top" require "bake/command/list" describe Bake::Command::List do let(:root) {File.expand_path(".test-project", __dir__)} let(:buffer) {StringIO.new} let(:parent) {Bake::Command::Top["--bakefile", root, output: buffer]} let(:command) {subject[parent: parent]} it "can list tasks" do inform(command.call) expect(buffer.string).to be =~ /A test method./ end with "pattern" do let(:command) {subject["a_very_unique_method", parent: parent]} it "lists only matching tasks" do inform(command.call) expect(buffer.string).to be =~ /a_very_unique_method/ end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/command/call.rb
test/bake/command/call.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require "bake/command/top" require "bake/command/call" describe Bake::Command::Call do let(:root) {File.expand_path(".test-project", __dir__)} let(:parent) {Bake::Command::Top["--bakefile", root]} let(:command) {subject["test_called", parent: parent]} it "can invoke task" do expect(command.call).to be == true end with "arguments" do let(:command) {subject["test_arguments", "A", "B", parent: parent]} it "can invoke task" do expect(command.call).to be =~ /AB/ end end with "mixed arguments" do let(:command) {subject["test_mixed", "A", "--y", "B", parent: parent]} it "can invoke task" do expect(command.call).to be =~ /AB/ end end with "= options" do let(:command) {subject["test_options", "x=A", "y=B", parent: parent]} it "can invoke task" do expect(command.call).to be =~ /AB/ end end with "-- options" do let(:command) {subject["test_options", "--x", "A", "--y", "B", parent: parent]} it "can invoke task" do expect(command.call).to be =~ /AB/ end end with "test_argument_normalized" do let(:command) {subject[parent: parent]} it "can accept --foo_bar" do expect(command["test_argument_normalized", "--foo_bar", "A"].call).to be =~ /A/ end it "can accept --foo-bar" do expect(command["test_argument_normalized", "--foo-bar", "A"].call).to be =~ /A/ end end with "value generating task" do let(:command) {subject[parent: parent]} let(:buffer) {StringIO.new} with "json output format" do it "can print the value" do command["value", "output", "--format", "json", "--file", buffer].call expect(buffer.string).to be == <<~JSON [ 1, 2, 3 ] JSON end end with "raw output format" do it "can print the value" do command["value", "output", "--format", "raw", "--file", buffer].call expect(buffer.string).to be == "[1, 2, 3]\n" end end with "yaml output format" do it "can print the value" do command["value", "output", "--format", "yaml", "--file", buffer].call expect(buffer.string).to be == <<~YAML --- - 1 - 2 - 3 YAML end end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/command/.test-project/bake.rb
test/bake/command/.test-project/bake.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. def initialize(*) super @called = false end attr :called # A test method. # # A second paragraph. # def test_called @called = true end def a_very_unique_method end def test_arguments(x, y) x+y end def test_options(x:, y:) x+y end # @parameter x [String] The x value. # @parameter y [String] The y value. def test_mixed(x, y: "Y") x+y end def test_argument_normalized(foo_bar:) foo_bar end def value [1, 2, 3] end def output?(recipe) true end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/.test-project/bake.rb
test/bake/.test-project/bake.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2024, by Samuel Williams. def doot end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/.test-project/bake/setup.rb
test/bake/.test-project/bake/setup.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2024, by Samuel Williams. recipe :setup do |x, y| end recipe :deploy do |x:, y:| end recipe :self_destruct do |**options| end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/.test-project/bake/invoke.rb
test/bake/.test-project/bake/invoke.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2024, by Samuel Williams. def task1(argument, option:) end def task2 task1("argument", option: "option") end def task3(argument) end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/.test-project/bake/parent.rb
test/bake/.test-project/bake/parent.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2024, by Samuel Williams. def parent end def sibling end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/.test-project/bake/types.rb
test/bake/.test-project/bake/types.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2024, by Samuel Williams. # @parameter x [Integer] the number to square. def square(x) x*x end # @parameter numbers [Array(Integer)] the numbers to sum up. def sum(numbers) numbers.sum end # @parameter key [Symbol] the key to lookup. # @parameter values [Hash(Symbol, Integer)] the hash of values. def index(key, values) values[key] end require 'json' # @parameter object [JSON] the object to inspect def inspect(object) object end require 'uri' # @parameter url [URI] the url to parse def hostname(url) url.hostname end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/.test-project/bake/wrap.rb
test/bake/.test-project/bake/wrap.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2024-2025, by Samuel Williams. def wrap(...) self.invoked(...) end protected def invoked(...) end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/.test-project/bake/parent/child.rb
test/bake/.test-project/bake/parent/child.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2024, by Samuel Williams. def child end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/test/bake/.test-project/bake/parent/sibling.rb
test/bake/.test-project/bake/parent/sibling.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2024, by Samuel Williams. def hello end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/bake/output.rb
bake/output.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2022-2025, by Samuel Williams. def initialize(...) super require_relative "../lib/bake/format" end # Dump the last result to the specified file (defaulting to stdout) in the specified format (defaulting to Ruby's pretty print). # @parameter file [Output] The input file. # @parameter format [Symbol] The output format. def output(input:, file: $stdout, format: nil) if format = format_for(file, format) format.output(file, input) else raise "Unable to determine output format!" end # Allow chaining of output processing: return input end # Do not produce any output. def null(input:) # This is a no-op, used to indicate that no output should be produced. return input end # This command produces output, and therefore doesn't need default output handling. def output?(recipe) true end private def format_for(file, name) if file.respond_to?(:path) and path = file.path name ||= file_type(path) end # Default to pretty print: name ||= :raw Bake::Format[name] end def file_type(path) if extension = File.extname(path) extension.sub!(/\A\./, "") return if extension.empty? return extension.to_sym end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/bake/input.rb
bake/input.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2022-2025, by Samuel Williams. def initialize(...) super require_relative "../lib/bake/format" end # Parse an input file (defaulting to stdin) in the specified format. The format can be extracted from the file extension if left unspecified. # @parameter file [Input] The input file. # @parameter format [Symbol] The input format, e.g. json, yaml. def input(file: $stdin, format: nil) if format = format_for(file, format) format.input(file) else raise "Unable to determine input format of #{file}!" end end # Parse some input text in the specified format (defaulting to JSON). # @parameter text [String] The input text. # @parameter format [Symbol] The input format, e.g. json, yaml. def parse(text, format: :json) file = StringIO.new(text) if format = format_for(nil, format) format.input(file) else raise "Unable to determine input format!" end end private def format_for(file, name) if file.respond_to?(:path) and path = file.path name ||= file_type(path) end Bake::Format[name] end def file_type(path) if extension = File.extname(path) extension.sub!(/\A\./, "") return if extension.empty? return extension.to_sym end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake.rb
lib/bake.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "bake/version" require_relative "bake/registry" require_relative "bake/context" require_relative "bake/format"
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/recipe.rb
lib/bake/recipe.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "type" require_relative "arguments" require_relative "documentation" module Bake # Structured access to an instance method in a bakefile. class Recipe # Initialize the recipe. # # @parameter instance [Base] The instance this recipe is attached to. # @parameter name [String] The method name. # @parameter method [Method | Nil] The method if already known. def initialize(instance, name, method = nil) @instance = instance @name = name @command = nil @comments = nil @signature = nil @documentation = nil @method = method @arity = nil end # The {Base} instance that this recipe is attached to. attr :instance # The name of this recipe. attr :name # Sort by location in source file. def <=> other (self.source_location || []) <=> (other.source_location || []) end # The method implementation. def method @method ||= @instance.method(@name) end # The source location of this recipe. def source_location self.method.source_location end # The recipe's formal parameters, if any. # @returns [Array | Nil] def parameters parameters = method.parameters unless parameters.empty? return parameters end end # Whether this recipe has optional arguments. # @returns [Boolean] def options? if parameters = self.parameters parameters.any? do |type, name| type == :keyrest || type == :keyreq || type == :key end end end # If a recipe produces output, we do not need to invoke the default output command. # @returns [Boolean] Whether this recipe produces output. def output? @instance.output?(self) end def required_options if parameters = self.parameters parameters.map do |(type, name)| if type == :keyreq name end end.compact end end # The command name for this recipe. def command @command ||= compute_command end def to_s self.command end # The method's arity, the required number of positional arguments. def arity if @arity.nil? @arity = method.parameters.count{|type, name| type == :req} end return @arity end # Process command line arguments into the ordered and optional arguments. # @parameter arguments [Array(String)] The command line arguments # @returns ordered [Array] # @returns options [Hash] def prepare(arguments, last_result = nil) Arguments.extract(self, arguments, input: last_result) end # Call the recipe with the specified arguments and options. # If the recipe does not accept options, they will be ignored. def call(*arguments, **options, &block) if options.any? and self.options? @instance.send(@name, *arguments, **options, &block) else # Ignore options... @instance.send(@name, *arguments, &block) end end # Any comments associated with the source code which defined the method. # @returns [Array(String)] The comment lines. def comments @comments ||= read_comments end # The documentation object which provides structured access to the {comments}. # @returns [Documentation] def documentation @documentation ||= Documentation.new(self.comments) end # The documented type signature of the recipe. # @returns [Array] An array of {Type} instances. def signature @signature ||= read_signature end # @deprecated Use {signature} instead. alias types signature private def parse(name, value, arguments, types) if count = arguments.index(";") value = arguments.shift(count) arguments.shift end if type = types[name] value = type.parse(value) end return value end def compute_command path = @instance.path if path.empty? @name.to_s elsif path.last.to_sym == @name path.join(":") else (path + [@name]).join(":") end end COMMENT = /\A\s*\#\s?(.*?)\Z/ def read_comments unless source_location = self.method&.source_location # Bail early if we don't have a source location (there are some inconsequential cases on JRuby): return [] end file, line_number = source_location lines = File.readlines(file) line_index = line_number - 1 description = [] line_index -= 1 # Extract comment preceeding method: while line = lines[line_index] # \Z matches a trailing newline: if match = line.match(COMMENT) description.unshift(match[1]) else break end line_index -= 1 end return description end def read_signature types = {} self.documentation.parameters do |parameter| types[parameter[:name].to_sym] = Type.parse(parameter[:type]) end return types end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/command.rb
lib/bake/command.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "command/top" module Bake # The command line interface. module Command def self.call(*arguments) Top.call(*arguments) end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/version.rb
lib/bake/version.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. module Bake VERSION = "0.24.1" end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/type.rb
lib/bake/type.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "type/any" require_relative "type/array" require_relative "type/boolean" require_relative "type/decimal" require_relative "type/float" require_relative "type/hash" require_relative "type/input" require_relative "type/integer" require_relative "type/nil" require_relative "type/output" require_relative "type/string" require_relative "type/symbol" require_relative "type/tuple" module Bake module Type def self.parse(signature) eval(signature, binding) end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/format.rb
lib/bake/format.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2025, by Samuel Williams. module Bake module Format REGISTRY = {} def self.[](name) unless name =~ /\A[a-z_]+\z/ raise ArgumentError.new("Invalid format name: #{name}") end begin require_relative "format/#{name}" rescue LoadError raise ArgumentError.new("Unknown format: #{name}") end return REGISTRY[name.to_sym] end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/documentation.rb
lib/bake/documentation.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "scope" module Bake # Structured access to a set of comment lines. class Documentation # Initialize the documentation with an array of comments. # # @parameter comments [Array(String)] An array of comment lines. def initialize(comments) @comments = comments end DESCRIPTION = /\A\s*([^@\s].*)?\z/ # The text-only lines of the comment block. # # @yields {|match| ...} # @parameter match [MatchData] The regular expression match for each line of documentation. # @returns [Enumerable] If no block given. def description return to_enum(:description) unless block_given? # We track empty lines and only yield a single empty line when there is another line of text: gap = false @comments.each do |comment| if match = comment.match(DESCRIPTION) if match[1] if gap yield "" gap = false end yield match[1] else gap = true end else break end end end ATTRIBUTE = /\A\s*@(?<name>.*?)\s+(?<value>.*?)\z/ # The attribute lines of the comment block. # e.g. `@returns [String]`. # # @yields {|match| ...} # @parameter match [MatchData] The regular expression match with `name` and `value` keys. # @returns [Enumerable] If no block given. def attributes return to_enum(:attributes) unless block_given? @comments.each do |comment| if match = comment.match(ATTRIBUTE) yield match end end end PARAMETER = /\A@param(eter)?\s+(?<name>.*?)\s+\[(?<type>.*?)\](\s+(?<details>.*?))?\z/ # The parameter lines of the comment block. # e.g. `@parameter value [String] The value.` # # @yields {|match| ...} # @parameter match [MatchData] The regular expression match with `name`, `type` and `details` keys. # @returns [Enumerable] If no block given. def parameters return to_enum(:parameters) unless block_given? @comments.each do |comment| if match = comment.match(PARAMETER) yield match end end end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/arguments.rb
lib/bake/arguments.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "type" require_relative "documentation" module Bake # Structured access to arguments. class Arguments def self.extract(recipe, arguments, **defaults) # Only supply defaults that match the recipe option names: defaults = defaults.slice(*recipe.required_options) self.new(recipe, defaults).extract(arguments) end def initialize(recipe, defaults) @recipe = recipe @types = recipe.types @parameters = recipe.parameters @arity = recipe.arity @ordered = [] @options = defaults end attr :ordered attr :options def extract(arguments) while argument = arguments.first if /^--(?<name>.*)$/ =~ argument # Consume the argument: arguments.shift if name.empty? break end name = normalize(name) # Extract the trailing arguments: @options[name] = extract_arguments(name, arguments) elsif /^(?<name>.*?)=(?<value>.*)$/ =~ argument # Consume the argument: arguments.shift name = name.to_sym # Extract the single argument: @options[name] = extract_argument(name, value) elsif @ordered.size < @arity _, name = @parameters.shift value = arguments.shift # Consume it: @ordered << extract_argument(name, value) else break end end return @ordered, @options end private def normalize(name) name.tr("-", "_").to_sym end def delimiter_index(arguments) arguments.index{|argument| argument =~ /\A(--|;\z)/} end def extract_arguments(name, arguments) value = nil type = @types[name] # Can this named parameter accept more than one input argument? if type&.composite? if count = delimiter_index(arguments) value = arguments.shift(count) arguments.shift if arguments.first == ";" else value = arguments.dup arguments.clear end else # Otherwise we just take one item: value = arguments.shift end if type value = type.parse(value) end return value end def extract_argument(name, value) if type = @types[name] value = type.parse(value) end return value end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/registry.rb
lib/bake/registry.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2024-2025, by Samuel Williams. require_relative "registry/aggregate" module Bake # Structured access to the working directory and loaded gems for loading bakefiles. module Registry def self.default(...) Aggregate.default(...) end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/base.rb
lib/bake/base.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "recipe" require_relative "scope" module Bake # The base class for including {Scope} instances which define {Recipe} instances. class Base < Struct.new(:context) # Generate a base class for the specified path. # @parameter path [Array(String)] The command path. def self.derive(path = []) klass = Class.new(self) klass.const_set(:PATH, path) return klass end # Format the class as a command. # @returns [String] def self.to_s if path = self.path path.join(":") else super end end def self.inspect if path = self.path "Bake::Base[#{path.join(':')}]" else super end end # The path of this derived base class. # @returns [Array(String)] def self.path self.const_get(:PATH) rescue nil end # If an instance generates output, it should override this method to return `true`, otherwise default output handling will be used (essentially the return value of the last recipe). # # @returns [Boolean] Whether this instance handles its own output. def output?(recipe) false end # The path for this derived base class. # @returns [Array(String)] def path self.class.path end # Proxy a method call using command line arguments through to the {Context} instance. # @parameter arguments [Array(String)] def call(*arguments) self.context.call(*arguments) end # Recipes defined in this scope. # # @yields {|recipe| ...} # @parameter recipe [Recipe] # @returns [Enumerable] def recipes return to_enum(:recipes) unless block_given? names = self.public_methods - Base.public_instance_methods names.each do |name| yield recipe_for(name) end end # Look up a recipe with a specific name. # # @parameter name [String] The instance method to look up. def recipe_for(name) Recipe.new(self, name) end def to_s "\#<#{self.class}>" end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/scope.rb
lib/bake/scope.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "recipe" module Bake # Used for containing all methods defined in a bakefile. module Scope # Load the specified file into a unique scope module, which can then be included into a {Base} instance. def self.load(file_path, path = []) scope = Module.new if scope.respond_to?(:set_temporary_name) scope.set_temporary_name("#{self.name}[#{file_path}]") end scope.extend(self) scope.const_set(:FILE_PATH, file_path) scope.const_set(:PATH, path) # yield scope if block_given? scope.module_eval(File.read(file_path), file_path) return scope end # Recipes defined in this scope. # # @yields {|recipe| ...} # @parameter recipe [Recipe] # @returns [Enumerable] def recipes return to_enum(:recipes) unless block_given? names = self.instance_methods names.each do |name| yield recipe_for(name) end end # The path of the file that was used to {load} this scope. def file_path pp file_path_self: self self.const_get(:FILE_PATH) end # The path of the scope, relative to the root of the context. def path self.const_get(:PATH) end # Look up a recipe with a specific name. # # @parameter name [String] The instance method to look up. def recipe_for(name) Recipe.new(self, name, self.instance_method(name)) end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/context.rb
lib/bake/context.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. # Copyright, 2020, by Olle Jonsson. require_relative "base" require_relative "registry" module Bake # The default file name for the top level bakefile. BAKEFILE = "bake.rb" # Represents a context of task execution, containing all relevant state. class Context # Search upwards from the specified path for a {BAKEFILE}. # If path points to a file, assume it's a `bake.rb` file. Otherwise, recursively search up the directory tree starting from `path` to find the specified bakefile. # @returns [String | Nil] The path to the bakefile if it could be found. def self.bakefile_path(path, bakefile: BAKEFILE) if File.file?(path) return path end current = path while current bakefile_path = File.join(current, BAKEFILE) if File.exist?(bakefile_path) return bakefile_path end parent = File.dirname(current) if current == parent break else current = parent end end return nil end # Load a context from the specified path. # @path [String] A file-system path. def self.load(path = Dir.pwd) if bakefile_path = self.bakefile_path(path) working_directory = File.dirname(bakefile_path) else working_directory = path end registry = Registry.default(working_directory, bakefile_path) context = self.new(registry, working_directory) context.bakefile return context end # Initialize the context with the specified registry. # @parameter registry [Registry] def initialize(registry, root = nil) @registry = registry @root = root @instances = Hash.new do |hash, key| hash[key] = instance_for(key) end @recipes = Hash.new do |hash, key| hash[key] = recipe_for(key) end end def bakefile @instances[[]] end # The registry which will be used to resolve recipes in this context. attr :registry # The root path of this context. # @returns [String | Nil] attr :root # Invoke recipes on the context using command line arguments. # # e.g. `context.call("gem:release:version:increment", "0,0,1")` # # @parameter commands [Array(String)] # @yield {|recipe, result| If a block is given, it will be called with the last recipe and its result. # @parameter recipe [Recipe] The last recipe that was called. # @parameter result [Object | Nil] The result of the last recipe. # @returns [Object] The result of the last recipe. def call(*commands, &block) recipe = nil last_result = nil # Invoke the recipes in the order they were specified: while command = commands.shift if recipe = @recipes[command] arguments, options = recipe.prepare(commands, last_result) last_result = recipe.call(*arguments, **options) else raise ArgumentError, "Could not find recipe for #{command}!" end end # If a block is given, we yield the last recipe and its result: if block_given? yield recipe, last_result end return last_result end # Lookup a recipe for the given command name. # @parameter command [String] The command name, e.g. `bundler:release`. def lookup(command) @recipes[command] end alias [] lookup def to_s if @root "#{self.class} #{File.basename(@root)}" else self.class.name end end def inspect "\#<#{self.class} #{@root}>" end private def recipe_for(command) path = command.split(":") # If the command is in the form `foo:bar`, we check two cases: # # (1) We check for an instance at path `foo:bar` and if it responds to `bar`. if instance = @instances[path] and instance.respond_to?(path.last) return instance.recipe_for(path.last) else # (2) We check for an instance at path `foo` and if it responds to `bar`. *path, name = *path if instance = @instances[path] and instance.respond_to?(name) return instance.recipe_for(name) end end return nil end def instance_for(path) if base = base_for(path) return base.new(self) end end # @parameter path [Array(String)] the path for the scope. def base_for(path) base = nil # For each loader, we check if it has a scope for the given path. If it does, we prepend it to the base: @registry.scopes_for(path) do |scope| base ||= Base.derive(path) base.prepend(scope) end return base end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/type/tuple.rb
lib/bake/type/tuple.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "any" module Bake module Type class Tuple include Type def initialize(item_types) @item_types = item_types end def composite? true end def parse(input) case input when ::String return input.split(",").map{|value| @item_type.parse(value)} when ::Array return input.map{|value| @item_type.parse(value)} else raise ArgumentError, "Cannot coerce #{input.inspect} into tuple!" end end def to_s "a Tuple of (#{@item_types.join(', ')})" end end def self.Tuple(*item_types) Tuple.new(item_types) end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/type/decimal.rb
lib/bake/type/decimal.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "any" require "bigdecimal" module Bake module Type module Decimal extend Type def self.composite? false end def self.parse(input) BigDecimal(input) end end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/type/array.rb
lib/bake/type/array.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "any" module Bake module Type class Array include Type def initialize(item_type) @item_type = item_type end def composite? true end def map(values) values.map{|value| @item_type.parse(value)} end def parse(input) case input when ::String return input.split(",").map{|value| @item_type.parse(value)} when ::Array return input.map{|value| @item_type.parse(value)} else raise ArgumentError, "Cannot coerce #{input.inspect} into array!" end end def to_s "an Array of #{@item_type}" end end def self.Array(item_type = Any) Array.new(item_type) end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/type/float.rb
lib/bake/type/float.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "any" module Bake module Type module Float extend Type def self.composite? false end def self.parse(input) input.to_f end end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false
ioquatix/bake
https://github.com/ioquatix/bake/blob/4f6cba256c9757d72772e02bde264a456feeeb4b/lib/bake/type/output.rb
lib/bake/type/output.rb
# frozen_string_literal: true # Released under the MIT License. # Copyright, 2020-2025, by Samuel Williams. require_relative "any" module Bake module Type module Output extend Type def self.composite? false end def self.parse(input) case input when "-" return $stdout when IO, StringIO return input else File.open(input, "w") end end end end end
ruby
MIT
4f6cba256c9757d72772e02bde264a456feeeb4b
2026-01-04T17:58:02.163537Z
false