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 |
|---|---|---|---|---|---|---|---|---|
chrishunt/rubiks-cube | https://github.com/chrishunt/rubiks-cube/blob/3b276ac7dbc8c2afd02d351316d4eb6b1e0d14e0/lib/rubiks_cube/cube.rb | lib/rubiks_cube/cube.rb | module RubiksCube
# Standard 3x3x3 Rubik's Cube with normal turn operations (l, r, u, d, f, b)
class Cube
SOLVED_STATE = %w(
UF UR UB UL FL FR BR BL DF DR DB DL UFL URF UBR ULB DLF DFR DRB DBL
)
def initialize(state = nil)
@state = build_state_from_string(
state.to_s.empty? ? SOLVED_STATE.join(' ') : state
)
end
def state=(stickers)
@state = build_state_from_string(
StickerStateTransform.new(stickers).to_cube
)
end
def ==(other)
state == other.state
end
def state
@state.join ' '
end
def edges
@state[0..11]
end
def corners
@state[12..-1]
end
def solved?
state == SOLVED_STATE.join(' ')
end
def edge_permuted?(edge)
cubie_permuted? :edges, edge
end
def corner_permuted?(corner)
cubie_permuted? :corners, corner
end
def permuted_location_for(cubie)
while (location = SOLVED_STATE.index cubie.state) == nil
cubie = cubie.rotate
end
location -= 12 if location >= 12
location
end
def perform!(algorithm)
algorithm.split.each { |move| perform_move! move }
algorithm
end
def r
turn [1, 5, 9, 6], [13, 17, 18, 14]
rotate [13, 14, 14, 17, 17, 18]
self
end
def l
turn [3, 7, 11, 4], [12, 15, 19, 16]
rotate [12, 12, 15, 16, 19, 19]
self
end
def u
turn [0, 1, 2, 3], [12, 13, 14, 15]
self
end
def d
turn [8, 11, 10, 9], [16, 19, 18, 17]
self
end
def f
turn [0, 4, 8, 5], [12, 16, 17, 13]
rotate [0, 4, 8, 5], [12, 13, 13, 16, 16, 17]
self
end
def b
turn [2, 6, 10, 7], [14, 18, 19, 15]
rotate [2, 6, 10, 7], [14, 15, 15, 18, 18, 19]
self
end
def m
turn [0, 2, 10, 8]
rotate [0, 2, 10, 8]
self
end
[:edge, :corner].each do |cubie|
[:orientation, :permutation].each do |step|
define_method "incorrect_#{cubie}_#{step}_locations" do
send "incorrect_#{step}_locations_for", cubie
end
define_method "has_correct_#{cubie}_#{step}?" do
send("incorrect_#{cubie}_#{step}_locations").empty?
end
end
end
private
def build_state_from_string(state)
state.split.map { |state| RubiksCube::Cubie.new state }
end
def cubie_permuted?(type, cubie)
send(type).index(cubie) == permuted_location_for(cubie)
end
def incorrect_permutation_locations_for(type)
send("#{type}s").each_with_index.map do |cubie, location|
location unless location == permuted_location_for(cubie)
end.compact
end
def incorrect_orientation_locations_for(type)
send("#{type}s").each_with_index.map do |cubie, location|
oriented_state = SOLVED_STATE.fetch(
if type == :corner
location + 12
else
location
end
)
location unless cubie.state == oriented_state
end.compact
end
def turn(*sequences)
sequences.each do |sequence|
location = sequence.shift
first_cubie = @state.fetch(location)
sequence.each do |next_location|
@state[location] = @state.fetch(next_location)
location = next_location
end
@state[location] = first_cubie
end
end
def rotate(*sequences)
sequences.each do |cubies|
cubies.each { |cubie| @state[cubie].rotate! }
end
end
def perform_move!(move)
operation = "#{move[0].downcase}"
case modifier = move[-1]
when "'"
3.times { send operation }
when "2"
2.times { send operation }
else
send operation
end
end
end
end
| ruby | MIT | 3b276ac7dbc8c2afd02d351316d4eb6b1e0d14e0 | 2026-01-04T17:51:24.361634Z | false |
chrishunt/rubiks-cube | https://github.com/chrishunt/rubiks-cube/blob/3b276ac7dbc8c2afd02d351316d4eb6b1e0d14e0/lib/rubiks_cube/solution.rb | lib/rubiks_cube/solution.rb | module RubiksCube
# Abstract interface for a RubiksCube solution
#
# Must implement:
# solution: array or string of moves necessary to solve the cube
# pretty: human readable string of solution
class Solution
attr_reader :cube
# Array or String of moves necessary to solve the cube
def solution
raise "#solution unimplemented in #{self.class.name}"
end
# Human readable string of solution
def pretty
raise "#pretty unimplemented in #{self.class.name}"
end
def initialize(cube)
@cube = Cube.new(cube.state)
end
def state
cube.state
end
def solved?
cube.solved?
end
def length
Array(solution).flatten.join(' ').split.count
end
end
end
| ruby | MIT | 3b276ac7dbc8c2afd02d351316d4eb6b1e0d14e0 | 2026-01-04T17:51:24.361634Z | false |
chrishunt/rubiks-cube | https://github.com/chrishunt/rubiks-cube/blob/3b276ac7dbc8c2afd02d351316d4eb6b1e0d14e0/lib/rubiks_cube/bicycle_solution.rb | lib/rubiks_cube/bicycle_solution.rb | module RubiksCube
# Alias for TwoCycleSolution
BicycleSolution = TwoCycleSolution
end
| ruby | MIT | 3b276ac7dbc8c2afd02d351316d4eb6b1e0d14e0 | 2026-01-04T17:51:24.361634Z | false |
chrishunt/rubiks-cube | https://github.com/chrishunt/rubiks-cube/blob/3b276ac7dbc8c2afd02d351316d4eb6b1e0d14e0/lib/rubiks_cube/cubie.rb | lib/rubiks_cube/cubie.rb | # Generic cubie piece, either edge cubie or corner cubie
module RubiksCube
Cubie = Struct.new(:state) do
def ==(other)
state == other.state
end
def rotate!
self.state = state.split('').rotate.join
self
end
def rotate
Cubie.new(state.dup).rotate!
end
def to_s
state
end
end
end
| ruby | MIT | 3b276ac7dbc8c2afd02d351316d4eb6b1e0d14e0 | 2026-01-04T17:51:24.361634Z | false |
chrishunt/rubiks-cube | https://github.com/chrishunt/rubiks-cube/blob/3b276ac7dbc8c2afd02d351316d4eb6b1e0d14e0/lib/rubiks_cube/algorithms.rb | lib/rubiks_cube/algorithms.rb | module RubiksCube
# Permutation and Orientation algorithms for two-cycle solution
module Algorithms
def self.reverse(algorithm)
algorithm.split.map do |move|
case modifier = move[-1]
when "'"
move[0]
when "2"
move
else
"#{move}'"
end
end.reverse.join ' '
end
module Permutation
Edge = "R U R' U' R' F R2 U' R' U' R U R' F'"
Corner = "U F R U' R' U' R U R' F' R U R' U' R' F R F' U'"
module Setup
Edge = {
0 => "M2 D L2",
2 => "M2 D' L2",
3 => "",
4 => "U' F U",
5 => "U' F' U",
6 => "U B U'",
7 => "U B' U'",
8 => "D' L2",
9 => "D2 L2",
10 => "D L2",
11 => "L2"
}
Corner = {
1 => "R2 D' R2",
2 => "",
3 => "B2 D' R2",
4 => "D R2",
5 => "R2",
6 => "D' R2",
7 => "D2 R2"
}
end
end
module Orientation
Edge = "M' U M' U M' U2 M U M U M U2"
Corner = "R' D R F D F' U' F D' F' R' D' R U"
module Setup
Edge = {
1 => "R B",
2 => "",
3 => "L' B'",
4 => "L2 B'",
5 => "R2 B",
6 => "B",
7 => "B'",
8 => "D2 B2",
9 => "D B2",
10 => "B2",
11 => "D' B2"
}
Corner = {
1 => "",
2 => "R'",
3 => "B2 R2",
4 => "D2 R2",
5 => "D R2",
6 => "R2",
7 => "D' R2"
}
end
end
end
end
| ruby | MIT | 3b276ac7dbc8c2afd02d351316d4eb6b1e0d14e0 | 2026-01-04T17:51:24.361634Z | false |
chrishunt/rubiks-cube | https://github.com/chrishunt/rubiks-cube/blob/3b276ac7dbc8c2afd02d351316d4eb6b1e0d14e0/lib/rubiks_cube/sticker_state_transform.rb | lib/rubiks_cube/sticker_state_transform.rb | module RubiksCube
# Transform manual sticker state entry to cube state
class StickerStateTransform
attr_reader :state
CENTER_LOCATIONS = [ 4, 13, 22, 31, 40, 49 ]
CORNER_LOCATIONS = [
42, 0 , 29, 44, 9, 2 , 38, 18, 11, 36, 27, 20,
45, 35, 6 , 47, 8, 15, 53, 17, 24, 51, 26, 33
]
EDGE_LOCATIONS = [
43, 1 , 41, 10, 37, 19, 39, 28,
3 , 32, 5 , 12, 21, 14, 23, 30,
46, 7 , 50, 16, 52, 25, 48, 34
]
def initialize(state)
@state = state.gsub(/\s/, '').split('')
end
def to_cube
(edges + corners).join(' ').gsub(/./) { |c| color_mapping.fetch(c, c) }
end
private
def color_mapping
Hash[state.values_at(*CENTER_LOCATIONS).zip %w(F R B L U D)]
end
def edges
state.values_at(*EDGE_LOCATIONS).each_slice(2).map(&:join)
end
def corners
state.values_at(*CORNER_LOCATIONS).each_slice(3).map(&:join)
end
end
end
| ruby | MIT | 3b276ac7dbc8c2afd02d351316d4eb6b1e0d14e0 | 2026-01-04T17:51:24.361634Z | false |
chrishunt/rubiks-cube | https://github.com/chrishunt/rubiks-cube/blob/3b276ac7dbc8c2afd02d351316d4eb6b1e0d14e0/lib/rubiks_cube/two_cycle_solution.rb | lib/rubiks_cube/two_cycle_solution.rb | module RubiksCube
# Very inefficient two-cycle solving algorithm (aka bicycle solution)
# Useful for learning and blindfold
class TwoCycleSolution < Solution
def solution
@solution ||= begin
solution = []
solution << solution_for(:permutation)
solution << solution_for(:orientation)
solution.flatten
end
end
def pretty
solution.each_slice(3).map do |setup, correction, undo|
step = []
step << "Setup:\t#{setup}" unless setup.empty?
step << "Fix:\t#{correction}"
step << "Undo:\t#{undo}" unless undo.empty?
step.join "\n"
end.join("\n\n").strip
end
private
def solution_for(step)
[:edge, :corner].map do |cubie|
solve_for cubie, step
end
end
def solve_for(cubie, step)
solution = []
solution << [perform(cubie, step)] until finished_with?(cubie, step)
solution
end
def finished_with?(cubie, step)
cube.public_send "has_correct_#{cubie}_#{step}?"
end
def perform(cubie, step)
algorithms_for(cubie, step).map { |algorithm| cube.perform! algorithm }
end
def next_orientation_location_for(cubie)
locations = incorrect_locations_for(cubie, :orientation)
locations.delete 0
locations.first
end
def next_permutation_location_for(cubie)
buffer_cubie = send("permutation_buffer_#{cubie}")
if cube.public_send("#{cubie}_permuted?", buffer_cubie)
incorrect_locations_for(cubie, :permutation).first
else
cube.permuted_location_for buffer_cubie
end
end
def permutation_buffer_edge
cube.edges[1]
end
def permutation_buffer_corner
cube.corners[0]
end
def incorrect_locations_for(cubie, step)
cube.public_send "incorrect_#{cubie}_#{step}_locations"
end
def algorithms_for(cubie, step)
location = send("next_#{step}_location_for", cubie)
setup = setup_algorithms_for(cubie, step, location)
correction = correction_algorithm_for(cubie, step)
undo = RubiksCube::Algorithms.reverse(setup)
[ setup, correction, undo ]
end
def correction_algorithm_for(cubie, step)
load_algorithms step, cubie
end
def setup_algorithms_for(cubie, step, location)
load_algorithms(step, :setup, cubie).fetch(location)
end
def load_algorithms(*modules)
[ 'RubiksCube',
'Algorithms',
*modules.map(&:capitalize)
].inject(Kernel) { |klass, mod| klass.const_get mod }
end
end
end
| ruby | MIT | 3b276ac7dbc8c2afd02d351316d4eb6b1e0d14e0 | 2026-01-04T17:51:24.361634Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/spec/spec_helper.rb | spec/spec_helper.rb |
require "coveralls"
Coveralls.wear!
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
]
SimpleCov.start
require "bundler"
Bundler.setup :default, :development
require "minitest/spec"
require "minitest/autorun"
require "minitest/mock"
require "ostruct"
require "camper_van"
alias :context :describe
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/spec/camper_van/command_definition_spec.rb | spec/camper_van/command_definition_spec.rb | require "spec_helper"
describe CamperVan::CommandDefinition do
before :each do
@test_commands = Class.new do
include CamperVan::CommandDefinition
attr_accessor :nick
handle :nick do |args|
@nick = args.first
args
end
end
end
it "defines a handle class method on a class" do
@test_commands.must_respond_to :handle
end
it "defines a handle instance method on a class" do
@test_commands.new.must_respond_to :handle
end
describe "#handle" do
before :each do
@cmd = @test_commands.new
end
it "raises an exception when no handler is available" do
lambda { @cmd.handle(:foo => []) }.must_raise(CamperVan::HandlerMissing)
end
it "passes the arguments to the block" do
@cmd.handle(:nick => %w(lol what)).must_equal %w(lol what)
end
it "evaluates the block in the instance context" do
@cmd.nick.must_equal nil
@cmd.handle(:nick => ["bob"])
@cmd.nick.must_equal "bob"
end
end
describe ".handle" do
it "defines a handler for the given command" do
@test_commands.handle :foo do
"success"
end
@test_commands.new.handle(:foo => []).must_equal "success"
end
end
end
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/spec/camper_van/server_reply_spec.rb | spec/camper_van/server_reply_spec.rb | require "spec_helper"
describe CamperVan::ServerReply do
before :each do
@test_server = Class.new do
include CamperVan::ServerReply
attr_reader :sent, :nick, :user, :host
def initialize
@sent = []
@nick, @user, @host = %w(nathan nathan localhost)
end
def send_line(data)
@sent << data
end
end
@server = @test_server.new
end
describe "#numeric_reply" do
it "sends the coded command from the server" do
@server.numeric_reply(:rpl_welcome, ":welcome")
@server.sent.size.must_equal 1
@server.sent.first.must_equal ":camper_van 001 nathan :welcome"
end
end
describe "#command_reply" do
it "replies with the given command and arguments" do
@server.command_reply :notice, "nickname", "hello there"
@server.sent.size.must_equal 1
@server.sent.first.must_equal ":camper_van NOTICE nickname :hello there"
end
it "does not prefix strings with a : if they have one already" do
@server.command_reply :notice, "nickname", ":hello there"
@server.sent.size.must_equal 1
@server.sent.first.must_equal ":camper_van NOTICE nickname :hello there"
end
end
describe "#user_reply" do
it "replies with the given command directed to the user" do
@server.user_reply :join, "#chan"
@server.sent.size.must_equal 1
@server.sent.first.must_equal ":nathan!nathan@localhost JOIN #chan"
end
it "prefixes the final argument with : if it has spaces" do
@server.user_reply :privmsg, "#chan", "hello world"
@server.sent.size.must_equal 1
@server.sent.first.must_equal ":nathan!nathan@localhost PRIVMSG #chan :hello world"
end
end
describe "#campfire_reply" do
it "replies with a command from the given nickname" do
@server.campfire_reply :privmsg, "joe", "#chan", "hello world"
@server.sent.size.must_equal 1
@server.sent.first.must_equal ":joe!joe@campfire PRIVMSG #chan :hello world"
end
end
end
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/spec/camper_van/ircd_spec.rb | spec/camper_van/ircd_spec.rb | require "spec_helper"
describe CamperVan::IRCD do
class TestConnection
attr_reader :sent
def initialize
@sent = []
end
def send_line(line)
@sent << line
end
def close_connection
end
def remote_ip
"127.0.0.1"
end
end
class TestIRCD < CamperVan::IRCD
attr_writer :campfire
attr_writer :away
attr_accessor :saved_channels
end
before :each do
@connection = TestConnection.new
@server = TestIRCD.new(@connection)
@server.campfire = Class.new do
def user(*args)
yield OpenStruct.new(:name => "Nathan")
end
end.new
end
describe "#handle" do
it "saves the subdomain and API key from the PASS command" do
@server.handle :pass => ["test:asdf1234"]
@server.subdomain.must_equal "test"
@server.api_key.must_equal "asdf1234"
end
it "allows '-' as a domain/api key separator" do
@server.handle :pass => ["test-asdf1234"]
@server.subdomain.must_equal "test"
@server.api_key.must_equal "asdf1234"
end
it "uses the *last* '-' as the separator in a domain/api key pair" do
@server.handle :pass => ["test-subdomain-asdf1234"]
@server.subdomain.must_equal "test-subdomain"
@server.api_key.must_equal "asdf1234"
end
it "only uses the subdomain if a full domain is specified" do
@server.handle :pass => ["test.campfirenow.com:asdf1234"]
@server.subdomain.must_equal "test"
@server.api_key.must_equal "asdf1234"
end
it "saves the nickname from the NICK command" do
@server.handle :nick => ["nathan"]
@server.nick.must_equal "nathan"
end
it "saves the user and host from the USER command" do
@server.handle :user => ["nathan", 0, 0, "Nathan"]
@server.user.must_equal "nathan"
@server.host.must_equal "127.0.0.1"
end
it "responds with an error when given a nick and user without a password" do
@server.handle :nick => ["nathan"]
@server.handle :user => ["nathan", 0, 0, "Nathan"]
@connection.sent.first.must_match /^:camper_van NOTICE AUTH :.*password/
end
it "responds with welcome messages after receiving a valid registration" do
@server.handle :pass => ["test:1234asdf"]
@server.handle :nick => ["nathan"]
@server.handle :user => ["nathan", 0, 0, "Nathan"]
@connection.sent.first.must_match /^:camper_van 001 nathan/
end
it "forces a nick change to match the campfire user if it doesn't match" do
@server.handle :pass => ["test:1234asdf"]
@server.handle :nick => ["bob"]
@server.handle :user => ["nathan", 0, 0, "Nathan"]
line = @connection.sent.detect { |c| c =~ /NICK/ }
line.must_match /NICK nathan/
end
it "returns an error and shuts down if campfire can't be contacted" do
@server.campfire = Class.new do
def user(*args)
raise Firering::Connection::HTTPError,
OpenStruct.new(:error => "could not connect")
end
end.new
@server.handle :pass => ["test:1234asdf"]
@server.handle :nick => ["bob"]
@server.handle :user => ["nathan", 0, 0, "Nathan"]
@connection.sent.last.must_match /NOTICE .*could not connect/
end
it "returns an error if the campfire api key is incorrect (user info is nil)" do
@server.campfire = Class.new do
def user(*args)
yield OpenStruct.new # nil everything
end
end.new
@server.handle :pass => ["test:1234asdf"]
@server.handle :nick => ["bob"]
@server.handle :user => ["nathan", 0, 0, "Nathan"]
@connection.sent.last.must_match /NOTICE .*invalid api key/i
end
context "when registered" do
before :each do
@server.handle :pass => ["test:1234asdf"]
@server.handle :nick => ["nathan"]
@server.handle :user => ["nathan", 0, 0, "Nathan"]
end
context "with a JOIN command" do
before :each do
@server.campfire = Class.new do
def rooms
yield [
OpenStruct.new(:name => "Test"),
OpenStruct.new(:name => "Day Job")
]
end
end.new
@connection.sent.clear
end
it "joins the given room" do
@server.handle :join => ["#test"]
@server.channels["#test"].must_be_instance_of CamperVan::Channel
end
it "returns an error if the room doesn't exist" do
@server.handle :join => ["#foo"]
@server.channels["#foo"].must_equal nil
@connection.sent.last.must_match /no such.*room/i
end
it "joins multiple channels if given" do
@server.handle :join => ["#test,#day_job"]
@connection.sent.must_be_empty
@server.channels["#test"].must_be_instance_of CamperVan::Channel
@server.channels["#day_job"].must_be_instance_of CamperVan::Channel
@ser
end
end
end
context "with a MODE command" do
before :each do
@channel = MiniTest::Mock.new
# register
@server.handle :pass => ["test:1234asdf"]
@server.handle :nick => ["nathan"]
@server.handle :user => ["nathan", 0, 0, "Nathan"]
@server.channels["#test"] = @channel
end
after :each do
@channel.verify
end
it "asks the channel to send its mode" do
@channel.expect :current_mode, nil
@server.handle :mode => ["#test"]
end
it "with a +i sets the channel mode to +i" do
@channel.expect :set_mode, nil, ["+i"]
@server.handle :mode => ["#test", "+i"]
end
it "with a -i sets the channel mode to -i" do
@channel.expect :set_mode, nil, ["-i"]
@server.handle :mode => ["#test", "-i"]
end
context "with an unknown mode argument" do
it "responds with an error" do
@server.handle :mode => ["#test", "-t"]
@connection.sent.last.must_match /472 nathan t :Unknown mode t/
end
end
end
context "with a WHO command" do
before :each do
@channel = MiniTest::Mock.new
# register
@server.handle :pass => ["test:1234asdf"]
@server.handle :nick => ["nathan"]
@server.handle :user => ["nathan", 0, 0, "Nathan"]
@server.channels["#test"] = @channel
end
after :each do
@channel.verify
end
it "asks campfire for a list of users" do
@channel.expect(:list_users, nil)
@server.handle :who => ["#test"]
end
it "returns 'end of list' only when an invalid channel is specified" do
@server.handle :who => ["#invalid"]
@connection.sent.last.must_match /^:camper_van 315 nathan #invalid :End/
end
end
context "with a QUIT command" do
before :each do
@channel = MiniTest::Mock.new
# register
@server.handle :pass => ["test:1234asdf"]
@server.handle :nick => ["nathan"]
@server.handle :user => ["nathan", 0, 0, "Nathan"]
@server.channels["#test"] = @channel
end
after :each do
@channel.verify
end
it "calls #part on the connected channels" do
@channel.expect(:part, nil)
@server.handle :quit => ["leaving..."]
end
end
context "with an AWAY command" do
before :each do
# register
@server.handle :pass => ["test:1234asdf"]
@server.handle :nick => ["nathan"]
@server.handle :user => ["nathan", 0, 0, "Nathan"]
end
context "with part_on_away set" do
before :each do
@server.options[:part_on_away] = true
@server.campfire = Class.new do
def rooms
yield [
OpenStruct.new(:name => "Test"),
OpenStruct.new(:name => "Day Job")
]
end
end.new
@server.handle :join => ["#test"]
@channel = MiniTest::Mock.new
@server.channels["#test"] = @channel
@connection.sent.clear
end
after :each do
@channel.verify
end
it "parts joined channels when not away" do
@channel.expect :part, nil
@server.away = false
@server.handle :away => ["bbl..."]
@server.away.must_equal true
end
it "rejoins previous channels when away" do
@channel.expect :join, nil
@server.saved_channels = ["#test"]
@server.away = true
@server.handle :away => []
@server.away.must_equal false
end
end
context "without part_on_away set" do
it "calls #away while not away" do
@server.away = false
@server.handle :away => ["bbl..."]
@server.away.must_equal true
@connection.sent.last.must_equal ":nathan!nathan@127.0.0.1 306 :You have been marked as being away"
end
it "returns from #away while away" do
@server.away = true
@server.handle :away => []
@server.away.must_equal false
@connection.sent.last.must_equal ":nathan!nathan@127.0.0.1 305 :You are no longer marked as being away"
end
end
end
end
end
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/spec/camper_van/command_parser_spec.rb | spec/camper_van/command_parser_spec.rb | require "spec_helper"
describe CamperVan::CommandParser do
class TestParser
include CamperVan::CommandParser
end
it "defines a parse method on a class that includes it" do
TestParser.new.must_respond_to :parse
end
describe "#parse" do
before :each do
@parser = TestParser.new
end
it "returns nil for a malformed command" do
@parser.parse("lolwhat").must_equal nil
end
it "parses a LIST command" do
@parser.parse("LIST").must_equal :list => []
end
it "parses a NICK command" do
@parser.parse("NICK nathan").must_equal :nick => ["nathan"]
end
it "parses a PRIVMSG command" do
@parser.parse("PRIVMSG #chan :hello there").must_equal(
:privmsg => ["#chan", "hello there"]
)
end
it "parses a MODE command" do
@parser.parse("MODE +i").must_equal :mode => ["+i"]
end
end
end
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/spec/camper_van/server_spec.rb | spec/camper_van/server_spec.rb | require "spec_helper"
describe CamperVan::Server do
it "has a run module method" do
CamperVan::Server.must_respond_to :run
end
class TestServer
include CamperVan::Server
attr_reader :sent
attr_reader :tls_started
def initialize(*)
super
@sent = []
@tls_started = false
end
def start_tls(*)
@tls_started = true
end
def close_connection
end
def send_data(data)
@sent << data
end
def get_peername
"xx" + [6667, 127, 0, 0, 1].pack("nC4")
end
end
describe "#post_init" do
it "starts TLS if the ssl option is true" do
@server = TestServer.new(:ssl => true)
@server.post_init
@server.tls_started.must_equal true
end
it "does not start TLS if the ssl option is not true" do
@server = TestServer.new
@server.post_init
@server.tls_started.must_equal false
end
end
describe "#receive_line" do
it "allows for a failed attempt at registration" do
@server = TestServer.new
@server.post_init
@server.receive_line "PASS invalid"
@server.receive_line "NICK nathan" # ignored
@server.receive_line "USER nathan 0 0 :Nathan" # ignored
@server.sent.first.must_match /must specify/
end
end
end
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/spec/camper_van/user_spec.rb | spec/camper_van/user_spec.rb | require "spec_helper"
describe CamperVan::User do
context "when initialized from a firering user" do
# User = Struct.new(:connection, :id, :name, :email_address, :admin,
# :created_at, :type, :api_auth_token, :avatar_url)
let(:firering_user) {
Firering::User.new(
nil, 12345, "Joe Q. Bob", "joe_bob@example.com", true, Time.now, "asdf", ""
)
}
let(:user) { CamperVan::User.new(firering_user) }
it "has a nick" do
user.nick.must_equal "joe_q_bob"
end
it "has a name" do
user.name.must_equal "Joe Q. Bob"
end
it "has an account" do
user.account.must_equal "joe_bob"
end
it "has a server" do
user.server.must_equal "example.com"
end
it "has an id" do
user.id.must_equal 12345
end
it "can be an admin" do
user.admin?.must_equal true
end
context "without an email address" do
let(:firering_user) {
Firering::User.new(
nil, 12345, "Joe Q. Bob", nil, true, Time.now, "asdf", ""
)
}
it "has an unknown account" do
user.account.must_equal "unknown"
end
it "has an unknown server" do
user.server.must_equal "unknown"
end
end
end
end
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/spec/camper_van/channel_spec.rb | spec/camper_van/channel_spec.rb | require "spec_helper"
describe CamperVan::Channel do
class TestClient
attr_reader :sent, :nick, :user, :host
attr_writer :nick
include CamperVan::ServerReply
def initialize
@nick, @user, @host = "nathan", "nathan", "localhost"
@sent = []
end
def send_line(line)
@sent << line
end
def subdomain
"subdomain"
end
end
class TestRoom
attr_reader :locked, :full, :topic, :membership_limit
attr_reader :sent
attr_reader :stream_count
attr_reader :left
attr_writer :users, :topic, :locked, :full, :open_to_guests
attr_writer :stream
attr_accessor :connection
def initialize
@users = []
@sent = []
@membership_limit = 12
@stream_count = 0
end
def id
10
end
def locked?
@locked
end
def full?
@full
end
def open_to_guests?
@open_to_guests
end
def join
yield
end
def leave
@left = true
end
def users
yield @users if block_given?
@users
end
def text(line)
@sent << line
end
def tweet(line)
@sent << [:tweet, line]
end
def stream
@stream_count += 1
if @messages
@messages.each { |m| yield m }
end
@stream ||= "message stream" # must be truthy
end
end
before :each do
@client = TestClient.new
@room = TestRoom.new
@room.topic = "the topic"
@channel = CamperVan::Channel.new("#test", @client, @room)
end
describe "#join" do
it "sends a user join as the command" do
@channel.join
@client.sent.first.must_equal ":nathan!nathan@localhost JOIN :#test"
end
it "sends the topic as a command" do
@channel.join
@client.sent[1].must_equal ":camper_van 332 nathan #test :the topic"
end
it "sends the topic as a command even if the topic is nil" do
@room.topic = nil
@channel.join
@client.sent[1].must_equal ":camper_van 332 nathan #test :"
end
it "sends the list of users" do
@room.users = [
OpenStruct.new(:id => 10, :name => "Nathan", :email_address => "x@y.com"),
OpenStruct.new(:id => 11, :name => "Bob", :email_address => "x@y.com"),
OpenStruct.new(:id => 12, :name => "Joe", :email_address => "x@y.com")
]
@channel.join
@client.sent[2].must_equal ":camper_van 353 nathan = #test :nathan bob joe"
@client.sent[3].must_equal ":camper_van 366 nathan #test :End of /NAMES list."
end
it "sends the list of users including myself, even if the server doesn't say i'm there" do
@room.users = [
OpenStruct.new(:id => 11, :name => "Bob", :email_address => "x@y.com"),
OpenStruct.new(:id => 12, :name => "Joe", :email_address => "x@y.com")
]
@channel.join
@client.sent[2].must_equal ":camper_van 353 nathan = #test :nathan bob joe"
end
it "does not stream messages from the room on a second join" do
@channel.join
@channel.join
@room.stream_count.must_equal 1
end
it "returns an error if the room is locked" do
@room.locked = true
@channel.join
@client.sent.last.must_match /Cannot join #test.*locked/
end
it "returns an error if the room is full" do
@room.full = true
@channel.join
@client.sent.last.must_match /Cannot join #test.*full/
end
end
describe "#part" do
it "sends a part command to the client" do
@channel.part
@client.sent.last.must_match /PART #test/
end
it "closes the connection on the stream" do
stream = Class.new do
attr_reader :closed
def close_connection
@closed = true
end
end
@room.stream = stream.new
@channel.stream_campfire_to_channel # sets up stream
@channel.part
assert @room.stream.closed
end
it "closes the em-http connection if present" do
stream = Class.new do
attr_reader :closed
def close # em-http defines this
@closed = true
end
end
@room.stream = stream.new
@channel.stream_campfire_to_channel # sets up stream
@channel.part
assert @room.stream.closed
end
it "leaves the channel" do
@channel.part
assert @room.left
end
end
describe "#list_users" do
before :each do
@room.users = [OpenStruct.new(:id => 10, :name => "Joe", :email_address => "user@example.com")]
@channel.join
@client.sent.clear
end
it "retrieves a list of users and sends them to the client" do
@channel.list_users
@client.sent.first.must_equal(
":camper_van 352 nathan #test user example.com camper_van joe H :0 Joe"
)
@client.sent.last.must_match /:camper_van 315 nathan #test :End/
end
it "issues JOIN irc commands for users who have joined but aren't yet tracked" do
@channel.list_users
@room.users << OpenStruct.new(:id => 11, :name => "Bob", :email_address => "bob@example.com")
@client.sent.clear
@channel.list_users
@client.sent.first.must_match /bob.*JOIN #test/
end
it "issues PART commands for users who have left but are still tracked" do
@room.users = []
@channel.list_users
@client.sent.first.must_match /joe.*PART #test/
end
it "shows a user as away if they are idle" do
@channel.users[10].idle = true
@channel.list_users
@client.sent.first.must_match /joe G :0 Joe/
end
it "shows admin users as having +o" do
@channel.users[10].admin = true
@channel.list_users
@client.sent.first.must_match /joe H@ :0 Joe/
end
end
describe "#privmsg" do
it "sends the message as text to the room" do
@channel.privmsg "hello world"
@room.sent.first.must_equal "hello world"
end
it "converts ACTION messages to campfire-appropriate messages" do
@channel.privmsg "\01ACTION runs away\01"
@room.sent.first.must_equal "*runs away*"
end
it "converts twitter urls to tweet messages" do
url = "https://twitter.com/aniero/status/12345"
@channel.privmsg url
@room.sent.first.must_equal [:tweet, url]
end
it "converts leading nicknames into campfire names" do
# get the users into the room
@room.users = [
OpenStruct.new(:id => 11, :name => "Bob Fred", :email_address => "x@y.com"),
OpenStruct.new(:id => 12, :name => "Joe", :email_address => "x@y.com")
]
@channel.list_users
@channel.privmsg "bob_fred: sup dude"
@room.sent.last.must_match /Bob Fred: sup dude/
end
it "converts names on any part" do
@room.users = [
OpenStruct.new(:id => 11, :name => "JD Wolk", :email_address => "x@y.com"),
OpenStruct.new(:id => 12, :name => "Joe", :email_address => "x@y.com")
]
@channel.list_users
@channel.privmsg "sup dude jd_wolk"
@room.sent.last.must_match /sup dude JD Wolk/
end
it "does not convert names in words" do
@room.users = [
OpenStruct.new(:id => 11, :name => "JD Wolk", :email_address => "x@y.com"),
OpenStruct.new(:id => 12, :name => "Nathan", :email_address => "x@y.com")
]
@channel.list_users
@channel.privmsg "sup dude jd_wolk and jonathan and nathan"
@room.sent.last.must_match /sup dude JD Wolk and jonathan and Nathan/
end
it "converts various nicknames" do
@room.users = [
OpenStruct.new(:id => 11, :name => "JD Wolk", :email_address => "x@y.com"),
OpenStruct.new(:id => 12, :name => "Pedro Nascimento", :email_address => "x@y.com"),
OpenStruct.new(:id => 13, :name => "Joe", :email_address => "x@y.com")
]
@channel.list_users
@channel.privmsg "sup dude jd_wolk and pedro_nascimento!"
@room.sent.last.must_match /sup dude JD Wolk and Pedro Nascimento!/
end
it "converts leading nicknames followed by punctuation" do
@room.users = [
OpenStruct.new(:id => 11, :name => "Bob Fred", :email_address => "x@y.com"),
OpenStruct.new(:id => 12, :name => "Joe", :email_address => "x@y.com")
]
@channel.list_users
@channel.privmsg "bob_fred! sup!"
@room.sent.last.must_match /Bob Fred! sup/
end
it "converts just leading nicks to names" do
@room.users = [
OpenStruct.new(:id => 11, :name => "Bob Fred", :email_address => "x@y.com"),
OpenStruct.new(:id => 12, :name => "Joe", :email_address => "x@y.com")
]
@channel.list_users
@channel.privmsg "bob_fred"
@room.sent.last.must_match /Bob Fred/
end
end
describe "#current_mode" do
it "sends the current mode to the client" do
@channel.current_mode
@client.sent.last.must_match ":camper_van 324 nathan #test +ls 12"
end
context "and a locked room" do
it "includes +i mode" do
@room.locked = true
@channel.current_mode
@client.sent.last.must_match ":camper_van 324 nathan #test +ils 12"
end
end
context "and a room that allows guests" do
it "drops the +s from the mode" do
@room.open_to_guests = true
@channel.current_mode
@client.sent.last.must_match ":camper_van 324 nathan #test +l 12"
end
end
end
describe "#set_mode" do
before :each do
@room = OpenStruct.new :membership_limit => 10
class << @room
def locked?
self.locked
end
def lock
self.lock_called = true
end
def unlock
self.unlock_called = true
end
end
@channel = CamperVan::Channel.new("#test", @client, @room)
end
context "with a +i" do
it "locks the room" do
@channel.set_mode "+i"
@room.lock_called.must_equal true
@room.locked.must_equal true
end
it "tells the client that the channel mode has changed" do
@channel.set_mode "+i"
@client.sent.last.must_match /MODE #test \+ils 10/
end
end
context "with a -i" do
it "unlocks the room" do
@channel.set_mode "-i"
@room.unlock_called.must_equal true
@room.locked.must_equal false
end
it "tells the client the channel mode has changed" do
@channel.set_mode "-i"
@client.sent.last.must_match /MODE #test \+ls 10/
end
end
context "with an unknown mode" do
it "replies with an irc error" do
@channel.set_mode "+m"
@client.sent.last.must_match /472 nathan :.*unknown mode/
end
end
end
describe "#map_message_to_irc when streaming" do
class TestMessage < OpenStruct
def user
yield OpenStruct.new :name => "Joe", :id => 10, :email_address => "joe@example.com"
end
end
def msg(type, attributes={})
TestMessage.new(
attributes.merge :type => "#{type}Message", :id => 1234
)
end
it "skips text messages from the current user" do
@client.nick = "joe"
@channel.map_message_to_irc msg("Text", :body => "hello", :user_id => 10)
@client.sent.last.must_equal nil
end
it "sends a privmsg with the message when a user says something" do
@channel.map_message_to_irc msg("Text", :body => "hello there")
@client.sent.last.must_match ":joe!joe@campfire PRIVMSG #test :hello there"
end
it "splits text messages on newline and carriage returns" do
@channel.map_message_to_irc msg("Text", :body => "hello\n\r\r\nthere")
@client.sent[-2].must_match ":joe!joe@campfire PRIVMSG #test :hello"
@client.sent[-1].must_match ":joe!joe@campfire PRIVMSG #test :there"
end
it "sends the first few lines, split by newline or carriage return, for a paste" do
@channel.map_message_to_irc msg("Paste", :body => "foo\r\nbar\nbaz\nbleh")
@client.sent[-4].must_match %r(:joe\S+ PRIVMSG #test :> foo)
@client.sent.last.must_match %r(:joe\S+ PRIVMSG #test .*room/10/paste/1234)
end
it "sends a privmsg with the pasted url and the first line when a user pastes something" do
@channel.map_message_to_irc msg("Paste", :body => "foo\nbar\nbaz\nbleh")
@client.sent.last.must_match %r(:joe\S+ PRIVMSG #test .*room/10/paste/1234)
end
it "sends a privmsg with an action when a user message is wrapped in *'s" do
@channel.map_message_to_irc msg("Text", :body => "*did a thing*")
@client.sent.last.must_match /PRIVMSG #test :\x01ACTION did a thing\x01/
end
it "converts leading name matches to irc nicks" do
# get the users into the room
@room.users = [
OpenStruct.new(:id => 11, :name => "Bob Fred", :email_address => "x@y.com"),
OpenStruct.new(:id => 12, :name => "Joe", :email_address => "x@y.com")
]
@channel.list_users
@client.sent.clear
# now check the mapping
@channel.map_message_to_irc msg("Text", :body => "Bob Fred: hello")
@client.sent.last.must_match %r(PRIVMSG #test :bob_fred: hello)
end
it "converts just leading names to nicks" do
@room.users = [
OpenStruct.new(:id => 11, :name => "Bob Fred", :email_address => "x@y.com"),
OpenStruct.new(:id => 12, :name => "Joe", :email_address => "x@y.com")
]
@channel.list_users
@channel.map_message_to_irc msg("Text", :body => "Bob Fred")
@client.sent.last.must_match %r(PRIVMSG #test :bob_fred)
end
it "converts leading names plus punctuation to nicks" do
@room.users = [
OpenStruct.new(:id => 11, :name => "Bob Fred", :email_address => "x@y.com"),
OpenStruct.new(:id => 12, :name => "Joe", :email_address => "x@y.com")
]
@channel.list_users
@channel.map_message_to_irc msg("Text", :body => "Bob Fred!!? dude!")
@client.sent.last.must_match %r(PRIVMSG #test :bob_fred!!\? dude)
end
it "sends an action when a user plays the crickets sound" do
@channel.map_message_to_irc msg("Sound", :body => "crickets")
@client.sent.last.must_match /\x01ACTION hears crickets chirping\x01/
end
it "sends an action when a user plays the rimshot sound" do
@channel.map_message_to_irc msg("Sound", :body => "rimshot")
@client.sent.last.must_match /\x01ACTION plays a rimshot\x01/
end
it "sends an action when a user plays the trombone sound" do
@channel.map_message_to_irc msg("Sound", :body => "trombone")
@client.sent.last.must_match /\x01ACTION plays a sad trombone\x01/
end
it "sends an action when a user plays the vuvuzela sound" do
@channel.map_message_to_irc msg("Sound", :body => "vuvuzela")
@client.sent.last.must_match /ACTION ======<\(\)/
end
it "sends an action when a user plays an unknown sound" do
@channel.map_message_to_irc msg("Sound", :body => "boing")
@client.sent.last.must_match /\x01ACTION played a boing sound\x01/
end
it "sends a mode change when the room is locked" do
@channel.map_message_to_irc msg("Lock")
@client.sent.last.must_match %r/:joe\S+ MODE #test \+i/
end
it "sends a mode change when the room is unlocked" do
@channel.map_message_to_irc msg("Unlock")
@client.sent.last.must_match %r/:joe\S+ MODE #test -i/
end
it "sends a mode change when the room disallows guests" do
@channel.map_message_to_irc msg("DisallowGuests")
@client.sent.last.must_match %r/:joe\S+ MODE #test \+s/
end
it "sends a mode change when the room allows guests" do
@channel.map_message_to_irc msg("AllowGuests")
@client.sent.last.must_match %r/:joe\S+ MODE #test -s/
end
it "sends a join command when a user enters the room" do
@channel.map_message_to_irc msg("Enter")
@client.sent.last.must_match %r/:joe\S+ JOIN #test/
end
it "does not resend a join command when a user enters the room twice" do
@channel.map_message_to_irc msg("Enter")
@client.sent.clear
@client.sent.last.must_equal nil
@channel.map_message_to_irc msg("Enter")
@client.sent.last.must_equal nil
end
it "adds the user to the internal tracking list when a user joins" do
@channel.map_message_to_irc msg("Enter")
@client.sent.last.must_match %r/:joe\S+ JOIN #test/
@channel.users[10].wont_equal nil
end
it "sends a part command when a user leaves the room" do
@channel.map_message_to_irc msg("Leave")
@client.sent.last.must_match %r/:joe\S+ PART #test/
end
it "removes the user from the tracking list when they depart" do
@channel.map_message_to_irc msg("Enter")
@channel.map_message_to_irc msg("Leave")
@channel.users.size.must_equal 0
end
it "sends a part command when a user is kicked from the room" do
@channel.map_message_to_irc msg("Kick")
@client.sent.last.must_match %r/:joe\S+ PART #test/
end
it "sends a topic command when a user changes the topic" do
@channel.map_message_to_irc msg("TopicChange", :body => "new topic")
@client.sent.last.must_match ":joe!joe@campfire TOPIC #test :new topic"
end
it "sends a message containing the upload link when a user uploads a file" do
conn = Class.new do
def http(method, url)
raise "bad method #{method}" unless method == :get
raise "bad url #{url}" unless url == "/room/456/messages/1234/upload.json"
yield :upload => {:full_url => "filename"}
end
end.new
@room.connection = conn
@channel.map_message_to_irc msg("Upload", :body => "filename", :room_id => 456)
@client.sent.last.must_match %r(:joe\S+ PRIVMSG #test .* filename)
end
it "sends a message containing the tweet url when a user posts a tweet" do
body = "hello world -- @author, twitter.com/aniero/status/12345.*"
@channel.map_message_to_irc msg("Tweet", :body => body)
@client.sent.last.must_match %r(:joe\S+ PRIVMSG #test .*twitter.com/aniero/status/12345.*)
end
it "splits on newline or carriage returns in tweets" do
body = "hello world\nsays me -- @author, twitter.com/aniero/status/12345.*"
@channel.map_message_to_irc msg("Tweet", :body => body)
@client.sent[-2].must_match %r(:joe\S+ PRIVMSG #test :hello world)
@client.sent.last.must_match %r(:joe\S+ PRIVMSG #test :says.*twitter.com/aniero/status/12345.*)
end
# it "sends a notice with the message when the system sends a message"
it "marks the user as away when a user goes idle" do
@channel.map_message_to_irc msg("Enter")
@channel.map_message_to_irc msg("Idle")
@channel.users[10].idle?.must_equal true
end
it "marks the user as back when a user becomes active" do
@channel.map_message_to_irc msg("Enter")
@channel.map_message_to_irc msg("Idle")
@channel.map_message_to_irc msg("Unidle")
@channel.users[10].idle?.must_equal false
end
end
end
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/lib/camper_van.rb | lib/camper_van.rb | require "camper_van/version"
require "eventmachine"
require "firering"
require "logging"
module CamperVan
require "camper_van/debug_proxy" # debug proxy
require "camper_van/utils" # utility methods
require "camper_van/logger" # logging helper
require "camper_van/command_parser" # irc command parser
require "camper_van/command_definition" # command definition and processing
require "camper_van/server_reply" # ircd responses and helpers
require "camper_van/user" # channel/campfire user
require "camper_van/ircd" # ircd server
require "camper_van/channel" # campfire room <-> channel bridge
require "camper_van/server" # the core campfire EM server
# Public: return the logger for the module
#
# Returns a Logging::Logger instance.
def self.logger
@logger = Logging::Logger[self.name]
end
end
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/lib/camper_van/server_reply.rb | lib/camper_van/server_reply.rb | module CamperVan
module ServerReply
# not an exhaustive list, just what i'm using
NUMERIC_REPLIES = {
# successful registration / welcome to the network
:rpl_welcome => "001",
:rpl_yourhost => "002",
:rpl_created => "003",
:rpl_myinfo => "004",
# more welcome messages
:rpl_luserclient => "251",
:rpl_luserop => "252",
:rpl_luserchannels => "254",
:rpl_luserme => "255",
# MOTD
:rpl_motdstart => "375",
:rpl_motd => "372",
:rpl_endofmotd => "376",
# MODE
:rpl_channelmodeis => "324",
# room listing
:rpl_list => "322",
:rpl_listend => "323",
:rpl_whoreply => "352",
:rpl_endofwho => "315",
# channel joins
:rpl_notopic => "331",
:rpl_topic => "332",
:rpl_namereply => "353",
:rpl_endofnames => "366",
# errors
:err_nosuchnick => "401", # no privmsgs to nicks allowed
:err_nosuchchannel => "403", # no such channel yo
:err_nonicknamegiven => "413",
:err_notonchannel => "442",
:err_needmoreparams => "461",
:err_passwdmismatch => "464",
:err_channelisfull => "471", # room is full
:err_unknownmode => "472",
:err_inviteonlychan => "473", # couldn't join the room, it's locked
:err_unavailresource => "437" # no such room!
}
def numeric_reply(code, *args)
number = NUMERIC_REPLIES[code]
raise ArgumentError, "unknown code #{code}" unless number
send_line ":camper_van #{number} #{nick}" << reply_args(args)
end
def command_reply(command, *args)
send_line ":camper_van #{command.to_s.upcase}" << reply_args(args)
end
def user_reply(command, *args)
send_line ":#{nick}!#{user}@#{host} #{command.to_s.upcase}" << reply_args(args)
end
def campfire_reply(command, username, *args)
# TODO instead of @campfire, use user's email address
send_line ":#{username}!#{username}@campfire #{command.to_s.upcase}" << reply_args(args)
end
def error_reply(reason)
send_line "ERROR :#{reason}"
end
private
def reply_args(args)
reply = ""
if args.size > 0
if args.last =~ /\s/ && !args.last.start_with?(':')
args[-1] = ':' + args.last
end
reply << " " << args.join(" ")
end
reply
end
end
end
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/lib/camper_van/version.rb | lib/camper_van/version.rb | module CamperVan
VERSION = "0.0.16"
end
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/lib/camper_van/channel.rb | lib/camper_van/channel.rb | # encoding: utf-8
require "yaml"
module CamperVan
class Channel
# The irc channel name this channel instance is for
attr_reader :channel
# The connected irc client connection
attr_reader :client
# The campfire room to which this channel is connected
attr_reader :room
# Accessor for the EM http request representing the live stream from
# the campfire api
attr_reader :stream
# Accessor for hash of known users in the room/channel
# Kept up to date by update_users command, as well as Join/Leave
# campfire events.
attr_reader :users
include Utils
include Logger
# Public: create a new campfire channel
#
# channel - name of the channel we're joining
# client - the EM::Connection representing the irc client
# room - the campfire room we're joining
def initialize(channel, client, room)
@channel, @client, @room = channel, client, room
@users = {}
end
# Public: Joins a campfire room and sends the necessary topic
# and name list messages back to the IRC client.
#
# Returns true if the join was successful,
# false if the room was full or locked.
def join
if room.locked?
client.numeric_reply :err_inviteonlychan, "Cannot join #{channel} (locked)"
return false
elsif room.full?
client.numeric_reply :err_channelisfull, "Cannot join #{channel} (full)"
return false
else
update_users do
# join channel
client.user_reply :join, ":#{channel}"
# current topic
client.numeric_reply :rpl_topic, channel, ':' + (room.topic || "")
# List the current users, which must always include myself
# (race condition, server may not realize the user has joined yet)
nicks = users.values.map { |u| u.nick }
nicks.unshift client.nick unless nicks.include? client.nick
nicks.each_slice(10) do |list|
client.numeric_reply :rpl_namereply, "=", channel, ":#{list.join ' '}"
end
client.numeric_reply :rpl_endofnames, channel, "End of /NAMES list."
# begin streaming the channel events (joins room implicitly)
stream_campfire_to_channel
end
end
true
end
# Public: "leaves" a campfire room, per the PART irc command.
# Confirms with the connected client to PART the channel.
def part
client.user_reply :part, channel
if stream
stream.close if stream.respond_to?(:close) # EM/em-http-request gem is installed and uses .close
stream.close_connection if stream.respond_to?(:close_connection)
end
room.leave
end
# Public: replies to a WHO command with a list of users for a campfire room,
# including their nicks, names, and status.
#
# For WHO response: http://www.mircscripts.org/forums.php?cid=3&id=159227
# In short, H = here, G = away, append @ for chanops (admins)
def list_users
update_users(:include_joins_and_parts) do
users.values.each do |user|
status = (user.idle? ? "G" : "H") + (user.admin? ? "@" : "")
client.numeric_reply :rpl_whoreply, channel, user.account, user.server,
"camper_van", user.nick, status, ":0 #{user.name}"
end
client.numeric_reply :rpl_endofwho, channel, "End of WHO list"
end
end
# Public: accepts an IRC PRIVMSG and converts it to an appropriate
# campfire text message for the room.
#
# msg - the IRC PRIVMSG message contents
#
def privmsg(msg)
# convert twitter urls to tweets
if msg =~ %r(^https://twitter.com/(\w+)/status/(\d+)$)
room.tweet(msg) { } # async, no-op callback
else
# convert ACTIONs
msg.sub! /^\01ACTION (.*)\01$/, '*\1*'
users.values.each do |user|
msg.sub!(/\b#{user.nick}\b/, user.name)
end
room.text(msg) { } # async, no-op callback
end
end
# Public: sends the current channel mode to the client
def current_mode
n = room.membership_limit
client.numeric_reply :rpl_channelmodeis, channel, current_mode_string, n
end
# Public: set the mode on the campfire channel, mapping from the provided
# IRC chanmode to the campfire setting.
#
# mode - the IRC mode flag change. Must be one of:
# "+i" - lock room
# "-i" - unlock room
#
# TODO support these when the firering client does:
# "+s" - disable guest access
# "-s" - enable guest access
#
# Returns nothing, but lets the client know the results of the call. Sends
# an error to the client for an invalid mode string.
def set_mode(mode)
case mode
# when "+s"
# when "-s"
when "+i"
room.lock
room.locked = true
client.user_reply :mode, channel,
current_mode_string, room.membership_limit
when "-i"
room.unlock
room.locked = false
client.user_reply :mode, channel,
current_mode_string, room.membership_limit
else
client.numeric_reply :err_unknownmode,
"is unknown mode char to me for #{channel}"
end
end
# Returns the current mode string
def current_mode_string
n = room.membership_limit
s = room.open_to_guests? ? "" : "s"
i = room.locked? ? "i" : ""
"+#{i}l#{s}"
end
# Public: returns the current topic of the campfire room
def current_topic
client.numeric_reply :rpl_topic, channel, ':' + room.topic
end
# Public: set the topic of the campfire room to the given string
# and lets the irc client know about the change
#
# topic - the new topic
def set_topic(topic)
room.update("topic" => topic) do
room.topic = topic
client.numeric_reply :rpl_topic, channel, ':' + room.topic
end
end
# Get the list of users from a room, and update the internal
# tracking state as well as the connected client. If the user list
# is out of sync, the irc client may receive the associated
# JOIN/PART commands.
#
# include_joins_and_parts - whether or not to include JOIN/PART commands if
# the user list has changed since the last update
# (defaults to false)
# callback - optional callback after the users have been
# updated
#
# Returns nothing, but keeps the users list updated
def update_users(include_joins_and_parts=false, &callback)
room.users do |user_list|
before = users.dup
present = {}
user_list.each do |user|
if before[user.id]
present[user.id] = before.delete user.id
# if present[user.id].nick != nick
# # NICK CHANGE
# present[user.id].nick = nick
# end
else
new_user = present[user.id] = User.new(user)
if include_joins_and_parts
client.campfire_reply :join, new_user.nick, channel
end
end
end
# Now that the list of users is updated, the remaining users
# in 'before' have left. Let the irc client know.
before.each do |id, user|
if include_joins_and_parts
client.campfire_reply :part, user.nick, channel
end
end
@users = present
callback.call if callback
end
end
# Stream messages from campfire and map them to IRC commands for the
# connected client.
#
# Only starts the stream once.
def stream_campfire_to_channel
@stream ||= room.stream do |message|
map_message_to_irc message
end
end
# Map a campfire message to one or more IRC commands for the client
#
# message - the campfire message to map to IRC
#
# Returns nothing, but responds according to the message
def map_message_to_irc(message)
user_for_message(message) do |message, user|
# needed in most cases
name = user ? irc_name(user.name) : nil
# strip Message off the type to simplify readability
type = message.type.sub(/Message$/, '')
if %w(Text Tweet Sound Paste Upload).include?(type) && name == client.nick
logger.debug "skipping message from myself: #{message.type} #{message.body}"
next
end
case type
when "Timestamp", "Advertisement"
# ignore these
when "Lock"
client.campfire_reply :mode, name, channel, "+i"
when "Unlock"
client.campfire_reply :mode, name, channel, "-i"
when "DisallowGuests"
name = irc_name(user.name)
client.campfire_reply :mode, name, channel, "+s"
when "AllowGuests"
name = irc_name(user.name)
client.campfire_reply :mode, name, channel, "-s"
when "Idle"
if u = users[user.id]
u.idle = true
end
when "Unidle"
if u = users[user.id]
u.idle = false
end
when "Enter"
unless users[user.id]
client.campfire_reply :join, name, channel
users[user.id] = User.new(user)
end
when "Leave", "Kick" # kick is used for idle timeouts
client.campfire_reply :part, name, channel, "Leaving..."
users.delete user.id
when "Paste"
lines = message.body.split(/\n|\r\n|\r/)
lines[0..2].each do |line|
client.campfire_reply :privmsg, name, channel, ":> " + line
end
if lines.size > 3
client.campfire_reply :privmsg, name, channel, ":> more: " +
"https://#{client.subdomain}.campfirenow.com/room/#{room.id}/paste/#{message.id}"
end
when "Sound"
text = case message.body
when "crickets"
"hears crickets chirping"
when "rimshot"
"plays a rimshot"
when "trombone"
"plays a sad trombone"
when "vuvuzela"
"======<() ~ ♪ ~♫"
else
"played a #{message.body} sound"
end
client.campfire_reply :privmsg, name, channel, "\x01ACTION #{text}\x01"
# when "System"
# # NOTICE from :camper_van to channel?
when "Text"
if message.body =~ /^\*.*\*$/
client.campfire_reply :privmsg, name, channel, ":\01ACTION " + message.body[1..-2] + "\01"
else
matched = users.values.detect do |user|
message.body =~ /^#{Regexp.escape(user.name)}(\W+(\s|$)|$)/
end
if matched
body = message.body.sub(/^#{matched.name}/, matched.nick)
else
body = message.body
end
body.split(/[\r\n]+/).each do |line|
client.campfire_reply :privmsg, name, channel, ":" + line
end
end
when "TopicChange"
client.campfire_reply :topic, name, channel, message.body
room.topic = message.body
# client.numeric_reply :rpl_topic, channel, ':' + message.body
when "Upload"
room.connection.http(:get, "/room/#{message.room_id}/messages/#{message.id}/upload.json") do |data|
client.campfire_reply :privmsg, name, channel, ":\01ACTION uploaded " + data[:upload][:full_url]
end
when "Tweet"
message.body.split(/\n|\r\n|\r/).each do |line|
client.campfire_reply :privmsg, name, channel, line
end
else
logger.warn "unknown message #{message.type}: #{message.body}"
end
end
end
# Retrieve the user from a message, either by finding it in the current
# list of known users, or by asking campfire for the user.
#
# message - the message for which to look up the user
#
# Yields the message and the user associated with the message
def user_for_message(message)
if user = users[message.user_id]
yield message, user
else
message.user do |user|
yield message, user
end
end
end
end
end
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/lib/camper_van/logger.rb | lib/camper_van/logger.rb | module CamperVan
module Logger
# Public: the logger for this class
#
# Returns a Logging::Logger instance
def logger
CamperVan.logger
end
end
end
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/lib/camper_van/ircd.rb | lib/camper_van/ircd.rb | require "socket" # for gethostname
module CamperVan
# the IRCD is the server that IRC clients connect to. It handles:
#
# * irc client registration and validation against campfire
# * mapping irc commands to internal Commands
# * proxying irc commands to campfire channels
class IRCD
# The IRC client
attr_reader :client
# Registration information for campfire authentication,
# comes from the PASS command from the irc client
attr_reader :subdomain, :api_key
# Information for the connected user
attr_reader :nick, :user, :host, :away
# A Hash of connected CampfireChannels
attr_reader :channels
# Whether or not this server is actively sending/receiving data.
# Set to false when shutting down so extra commands are ignored.
attr_reader :active
# Additional options
attr_reader :options
MOTD = <<-motd
Welcome to CamperVan.
To see what campfire rooms are available to the
configured subdomain and api key, use the LIST command.
motd
include CommandDefinition # handle :command { ... }
include CommandParser # parses IRC commands
include ServerReply # IRC reply helpers
include Utils # irc translation helpers
include Logger # logging helper
# Public: initialize an IRC server connection
#
# client - the EM connection representing the IRC client
# options - a Hash of additional options, defaults to {}
# :part_on_away - leave connected campfire rooms when irc client
# goes away, rejoin when coming back
#
def initialize(client, options = {})
@client = client
@active = true
@channels = {}
@away = false
@saved_channels = []
@options = options
end
# The campfire client
#
# Returns the existing or initializes a new instance of a campfire
# client using the configured subdomain and API key.
def campfire
@campfire ||= Firering::Connection.new(
"https://#{subdomain}.campfirenow.com"
) do |c|
c.token = api_key
c.logger = CamperVan.logger
end
end
# Handler for when a client sends an IRC command
def receive_line(line)
if @active
cmd = parse(line)
handle cmd
end
rescue HandlerMissing
logger.info "ignoring irc command #{cmd.inspect}: no handler"
end
# Send a line back to the irc client
def send_line(line)
client.send_line line if @active
end
# Shuts down this connection to the server
def shutdown
@active = false
client.close_connection
end
# IRC registration sequence:
#
# PASS <password> (may not be sent!)
# NICK <nickname>
# USER <user info>
#
# PASS command handler
handle :pass do |args|
if args.empty?
numeric_reply :err_needmoreparams, ":must specify a password: subdomain:api_key"
shutdown
else
@subdomain, @api_key = *args.first.split(":")
# allow alternate '-' separator
if !@api_key
# split on the last occurrence of '-':
@subdomain, @api_key = *args.first.split(/-(?=[^-]+$)/)
end
# ignore full "mycompany.campfirenow.com" being set as the subdomain
@subdomain = subdomain.split(".").first
end
end
# NICK command handler
#
# As a part of the registration sequence, sets the nickname.
# If sent after the client is registered, responds with an IRC
# error, as nick changes with campfire are disallowed (TODO)
handle :nick do |args|
if args.empty?
numeric_reply :err_nonicknamegiven, ":no nickname given"
else
if @nick
# TODO error
else
@nick = args.first
end
end
end
# USER command handler
#
# Final part of the registration sequence.
# If registration is successful, sends a welcome reply sequence.
handle :user do |args|
if args.size < 4
numeric_reply :err_needmoreparams, "Need more params"
else
@user = args.first
# grab the remote IP address for the client
@host = client.remote_ip
unless @api_key
command_reply :notice, "AUTH", "*** must specify campfire API key as password ***"
shutdown
return
end
successful_registration
end
end
# PING command handler.
#
# Responds with a PONG
handle :ping do |args|
command_reply :pong, *args
end
# LIST command handler
#
# Sends the list of available campfire channels to the client.
handle :list do |args|
# hooray async code: have to do gymnastics to make this appear
# sequential
campfire.rooms do |rooms|
sent = 0
rooms.each do |room|
name = "#" + irc_name(room.name)
topic = room.topic
room.users do |users|
numeric_reply :rpl_list, name, users.size, topic
sent += 1
if sent == rooms.size
numeric_reply :rpl_listend, "End of list"
end
end
end
end
end
handle :who do |args|
if channel = channels[args.first]
channel.list_users
else
if args.empty?
numeric_reply :rpl_endofwho, "End of WHO list"
else
numeric_reply :rpl_endofwho, args.first, "End of WHO list"
end
end
end
handle :join do |args|
args = args.map { |args| args.split(",")}.flatten
args.each do |channel|
join_channel channel
end
end
handle :part do |args|
name = args.first
# FIXME parting a channel should remove the channel from channels, except
# that there's a bug with EM that won't disconnect the streaming request.
# Because of that, leave the channel in the list, and assume the irc
# client attached to this IRCD will ignore messages from channels it's not
# currently in.
if channel = channels[name]
channel.part
else
numeric_reply :err_notonchannel, "You're not on that channel"
end
end
handle :topic do |args|
name, new_topic = *args
if channel = channels[name]
if new_topic
channel.set_topic new_topic
else
channel.current_topic
end
else
# TODO topic error
end
end
handle :privmsg do |args|
name, msg = *args
if channel = channels[name]
channel.privmsg msg
else
numeric_reply :err_nonicknamegiven, name, "No such nick/channel"
end
end
handle :mode do |args|
if channel = channels[args.shift]
if mode = args.first
if mode =~ /^[+-][si]$/
channel.set_mode mode
else
mode = mode.gsub(/\W/,'')
numeric_reply :err_unknownmode, mode, "Unknown mode #{mode}"
end
else
channel.current_mode
end
else
# no error message for this situation, so ignore it silently
end
end
handle :away do |args|
if @away
user_reply 305, "You are no longer marked as being away"
if options[:part_on_away]
@saved_channels.each do |channel|
join_channel channel
end
@saved_channels = []
end
else
user_reply 306, "You have been marked as being away"
if options[:part_on_away]
@saved_channels = channels.keys
channels.values.each do |channel|
channel.part
end
end
end
@away = !@away
end
handle :quit do |args|
channels.values.each do |channel|
channel.part
end
shutdown
end
# Completes a successful registration with the appropriate responses
def successful_registration
check_campfire_authentication do
check_nick_matches_authenticated_user
send_welcome
send_luser_info
send_motd
end
end
# Checks that the campfire authentication is successful.
#
# callback - a block to call if successful.
#
# Yields to the callback on success (async)
#
# If it fails, it replies with an error to the client and
# disconnects.
def check_campfire_authentication(&callback)
# invalid user only returns a nil result!
campfire.user("me") do |user|
if user.name
yield
else
command_reply :notice, "AUTH", "could not connect to campfire: invalid API key"
shutdown
end
end
rescue Firering::Connection::HTTPError => e
command_reply :notice, "AUTH", "could not connect to campfire: #{e.message}"
shutdown
end
# Check to see that the nick as provided during the registration
# process matches the authenticated campfire user. If the nicks don't
# match, send a nick change to the connected client.
def check_nick_matches_authenticated_user
campfire.user("me") do |user|
name = irc_name user.name
if name != nick
user_reply :nick, name
@nick = name
end
end
end
def send_welcome
hostname = Socket.gethostname
numeric_reply :rpl_welcome, "Welcome to CamperVan, #{nick}!#{user}@#{host}"
numeric_reply :rpl_yourhost, "Your host is #{hostname}, " +
"running CamperVan version #{CamperVan::VERSION}"
# using Time.now instead of a global start time since, well, this
# particular instance really did just start right now. Give or
# take a few seconds.
numeric_reply :rpl_created, "This server was created #{Time.now}"
numeric_reply :rpl_myinfo, hostname, CamperVan::VERSION,
# channel modes: invite-only, secret
"is",
# user modes: away
"a"
end
def send_luser_info
numeric_reply :rpl_luserclient, "There is 1 user on 1 channel"
numeric_reply :rpl_luserop, 0, "IRC Operators online"
numeric_reply :rpl_luserchannels, 0, "channels formed"
numeric_reply :rpl_myinfo, "I have 1 client and 0 servers"
end
def send_motd
numeric_reply :rpl_motdstart, ":- MOTD for camper_van -"
MOTD.split("\n").each do |line|
numeric_reply :rpl_motd, ":- #{line.strip}"
end
numeric_reply :rpl_endofmotd, "END of MOTD"
end
def join_channel(name)
campfire.rooms do |rooms|
if room = rooms.detect { |r| "#" + irc_name(r.name) == name }
channel = channels[name] || Channel.new(name, self, room)
if channel.join
channels[name] = channel
end
else
numeric_reply :err_nosuchchannel, name, "No such campfire room!"
end
end
end
end
end
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/lib/camper_van/utils.rb | lib/camper_van/utils.rb | module CamperVan
module Utils
# TODO make irc-safe substitutions, etc.
def irc_name(name)
name.gsub('/', '-').
gsub(/\W/, ' ').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
gsub(/\s+/, "_").
tr("-", "_").
downcase
end
def stringify_keys(hash)
hash.keys.each do |key|
hash[key.to_s] = hash.delete(key)
end
hash
end
end
end
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/lib/camper_van/command_definition.rb | lib/camper_van/command_definition.rb | module CamperVan
class HandlerMissing < StandardError
attr_reader :command
def initialize(command)
@command = command
@message = "no handler for the #{command and command.keys.first} command"
end
end
module CommandDefinition
def self.included(base)
base.module_eval { include InstanceMethods }
base.extend ClassMethods
end
module ClassMethods
# Public: defines a handler for the given irc command
#
# command - the irc command to define a handler for
#
# Example:
#
# handle :nick do |args|
# # ... change nickname to ...
# end
#
# ```
# def handle_nick(*args)
# # contents of block
# end
# ```
def handle(command, &block)
define_method "handle_#{command}".to_sym, &block
end
end
module InstanceMethods
# Public: handles the given command using the handler method
# defined by the class-level handler metaprogramming, if it
# exists.
#
# command - the Hash command as provided by the irc command parser
#
# Example:
#
# handle :nick => ["joe"]
#
# Raises CamperVan::HandlerMissing if there is no handler method
# defined for the given command.
def handle(command)
name, args = command.to_a.first
method_name = "handle_#{name}".to_sym
if self.respond_to? method_name
m = method(method_name)
if m.arity > 0
send method_name, args
else
send method_name
end
else
raise CamperVan::HandlerMissing, command
end
end
end
end
end
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/lib/camper_van/debug_proxy.rb | lib/camper_van/debug_proxy.rb | # debug proxy for dumping all irc traffic between a client and a server
module CamperVan
class DebugProxy < EM::Connection
include EM::Protocols::LineText2
def self.run(server, server_port=6667)
EM.run do
EM.start_server "localhost", 6667, DebugProxy, server, server_port
puts "* waiting for connections..."
trap("INT") do
puts "* shutting down"
EM.stop
end
end
end
class Server < EM::Connection
include EM::Protocols::LineText2
attr_reader :client
def initialize(client)
super
@lt2_delimiter = "\r\n"
@client = client
end
def post_init
puts "* established connection to server"
end
def receive_line(line)
puts "> #{line}"
client.send_data line + "\r\n"
end
def unbind
puts "* server closed connection"
end
end
def initialize(server, server_port)
@server = EM.connect(server, server_port, IrcProxy::Server, self)
@lt2_delimiter = "\r\n"
end
def post_init
puts "* client connected, establishing connection to server..."
end
def receive_line(line)
puts "< #{line}"
@server.send_data line + "\r\n"
end
def unbind
puts "* client closed connection"
end
end
end
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/lib/camper_van/server.rb | lib/camper_van/server.rb | module CamperVan
# The core EventMachine server instance that listens for IRC
# connections and maps them to IRCD instances.
module Server
# Public: start the server
#
# bind_address - what address to bind to
# port - what port to listen on
# options - an optional hash of additional configuration
# :log_level - defaults to 'info'
# :log_to - log to filename (string), IO. defaults to STDOUT
# :ssl - use ssl for client connections, defaults to false
# :ssl_private_key - if using ssl, private key file to use, defaults to self-signed
# :ssl_cert - if using ssl, cert file to use, defaults to self-signed
# :ssl_verify_peer - if using ssl, verify client certificates, defaults to false
# :daemon - if camper_van should daemonize itself
# :pid - the path of the PID file to use.
def self.run(bind_address="localhost", port=6667, options={})
initialize_logging options
EM.run do
logger = Logging.logger[self.name]
logger.info "starting server on #{bind_address}:#{port}"
EM.start_server bind_address, port, self, options
if options[:daemon]
daemonize(logger, options[:pid])
end
trap("INT") do
logger.info "SIGINT, shutting down"
EM.stop
end
end
end
# Turns the current process into a daemon.
#
# logger - The logger to use
# pid - The path to the PID file
#
def self.daemonize(logger, pid)
if !File.writable?(File.dirname(pid))
logger.error "The PID file #{pid} is not writable"
abort
end
logger.info "Daemonizing camper_van using PID #{pid}"
Process.daemon
File.open(pid, 'w') do |handle|
handle.write(Process.pid.to_s)
end
Logging.reopen
end
# Initialize the logging system
#
# opts - Hash of logging options
# - :log_level (default :info)
# - :log_to - where to log to (default STDOUT), can be IO or
# String for log filename
def self.initialize_logging(opts={})
Logging.consolidate("CamperVan")
Logging.logger.root.level = opts[:log_level] || :info
appender = case opts[:log_to]
when String
Logging.appenders.file(opts[:log_to])
when IO
Logging.appenders.io(opts[:log_to])
when nil
Logging.appenders.stdout
end
# YYYY-MM-DDTHH:MM:SS 12345 LEVEL LoggerName : The Log message
appender.layout = Logging::Layouts::Pattern.new(:pattern => "%d %5p %5l %c : %m\n")
Logging.logger.root.add_appenders appender
end
# Using a line-based protocol
include EM::Protocols::LineText2
include Logger
# Public: returns the instance of the ircd for this connection
attr_reader :ircd
# Public: returns connection options
attr_reader :options
def initialize(options={})
@options = options
end
# Public callback once a server connection is established.
#
# Initializes an IRCD instance for this connection.
def post_init(*args)
logger.info "got connection from #{remote_ip}"
# initialize the line-based protocol: IRC is \r\n
@lt2_delimiter = "\r\n"
# start up the IRCD for this connection
@ircd = IRCD.new(self, options)
if options[:ssl]
logger.info "starting TLS for #{remote_ip}"
start_tls(:cert_chain_file => options[:ssl_cert], :private_key_file => options[:ssl_private_key], :verify_peer => options[:ssl_verify_peer])
end
end
# Public: callback for when a line of the protocol has been
# received. Delegates the received line to the ircd instance.
#
# line - the line received
def receive_line(line)
logger.debug "irc -> #{line.strip}"
ircd.receive_line(line)
end
# Public: send a line to the connected client.
#
# line - the line to send, sans \r\n delimiter.
def send_line(line)
logger.debug "irc <- #{line}"
send_data line + "\r\n"
end
# Public: callback when a client disconnects
def unbind
logger.info "closed connection from #{remote_ip}"
end
# Public: return the remote ip address of the connected client
#
# Returns an IP address string
def remote_ip
@remote_ip ||= get_peername[4,4].unpack("C4").map { |q| q.to_s }.join(".")
end
end
end
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/lib/camper_van/command_parser.rb | lib/camper_van/command_parser.rb | module CamperVan
# simplistic IRC command parser
module CommandParser
# returns hash, e.g.
#
# malformed # => nil
# NICK joe # => # { :nick => ["joe"] }
# LIST # => # { :list => [] }
# PRIVMSG #foo :test # => { :privmsg => ['#foo', 'test'] }
#
def parse(line)
line = line.dup
match = /^([A-Z]+)(\b|$)/.match(line)
cmd = match && match[0]
return nil unless cmd
# strip off the command and any whitespace
line.sub! /^#{cmd}\s*/, ""
args = []
until line.empty? do
line =~ /^(\S+)(\s|$)/
if $1
if $1.start_with?(":")
args << line[1..-1]
break
else
args << $1
line = line[$1.size..-1]
line = line.sub(/^\s+/,"")
end
else
break
end
end
return {cmd.downcase.to_sym => args }
end
end
end
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
zerowidth/camper_van | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/lib/camper_van/user.rb | lib/camper_van/user.rb | module CamperVan
class User
# IRC normalization from names
include Utils
# Public: the user's campfire id
attr_reader :id
# Public: the user's campfire name
attr_reader :name
# Public: the user's irc nick
attr_reader :nick
# Public: the user's unix account name for user@host pairs in irc,
# mapped from the user's email address
attr_reader :account
# Public: the user's unix server name for user@host pairs in irc,
# mapped from the user's email address
attr_reader :server
# Public: whether the user is idle or not. Updated by campfire
# Idle/Unidle messages
def idle?
@idle
end
# Public: set the user's idle state.
#
# is_idle - true/false
attr_writer :idle
# Public: whether or not the user is an admin
def admin?
@admin
end
# Public: set the user's admin state
#
# admin - true/false
attr_writer :admin
# Public: create a new user from a campfire user definition.
#
# Initializes the user's fields based on the campfire user info.
def initialize(user)
@id = user.id
@name = user.name
if user.email_address
@account, @server = user.email_address.split("@")
else
@account = @server = "unknown"
end
@nick = irc_name user.name
@idle = false
@admin = user.admin
end
end
end
| ruby | MIT | 984351a3b472e936a451f1d1cd987ca27d981d23 | 2026-01-04T17:51:28.743412Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/gems.rb | gems.rb | source "https://rubygems.org"
gemspec name: "fiber_scheduler"
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/spec/spec_helper.rb | spec/spec_helper.rb | require_relative "../lib/fiber_scheduler"
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
# will be the default in rspec 4
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
# will be the default in rspec 4
mocks.verify_partial_doubles = true
end
# will be the default in rspec 4
config.shared_context_metadata_behavior = :apply_to_host_groups
config.filter_run_when_matching :focus
config.example_status_persistence_file_path = "spec/examples.txt"
config.disable_monkey_patching!
if config.files_to_run.one?
config.default_formatter = "doc"
end
config.order = :random
Kernel.srand config.seed
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/spec/fiber_scheduler/nested_fiber_scheduler_spec.rb | spec/fiber_scheduler/nested_fiber_scheduler_spec.rb | require "fiber_scheduler_spec/context"
RSpec.describe FiberScheduler do
describe "nested FiberScheduler" do
shared_examples :nested_fiber_scheduler do
include_context FiberSchedulerSpec::Context
let(:order) { [] }
context "with default arguments" do
context "with no non-blocking operations" do
def operations
FiberScheduler do
order << 1
FiberScheduler do
order << 2
end
order << 3
end
end
it "behaves sync" do
setup
expect(order).to eq [1, 2, 3]
end
end
context "with non-blocking operations" do
def operations
FiberScheduler do
order << 1
sleep 0
order << 3
FiberScheduler do
order << 4
sleep 0
order << 6
end
order << 5
end
order << 2
end
it "behaves asynchronous" do
setup
expect(order).to eq (1..6).to_a
end
end
end
context "with :waiting arg" do
context "with non-blocking operations" do
def operations
FiberScheduler :waiting do
order << 1
sleep 0
order << 2
end
order << 3
end
it "behaves sync" do
setup
expect(order).to eq (1..3).to_a
end
end
end
context "with :volatile arg" do
context "with non-blocking operations" do
def operations
FiberScheduler :volatile do
order << 1
sleep 1
order << :this_line_never_runs
end
order << 2
end
it "never finishes" do
setup
expect(order).to eq (1..2).to_a
end
end
context "with no non-blocking operations" do
def fibonacci(n)
return n if [0, 1].include? n
fibonacci(n - 1) + fibonacci(n - 2)
end
def operations
FiberScheduler :volatile do
order << 1
fibonacci(10)
order << 2
end
order << 3
end
it "finishes" do
setup
expect(order).to eq (1..3).to_a
end
end
end
end
context "with default setup" do
include_examples :nested_fiber_scheduler
end
context "with block setup" do
def setup
FiberScheduler do
operations
end
end
include_examples :nested_fiber_scheduler
end
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/spec/fiber_scheduler/timeouts_spec.rb | spec/fiber_scheduler/timeouts_spec.rb | require "fiber_scheduler_spec/context"
RSpec.describe FiberScheduler::Timeouts do
describe "#call" do
include_context FiberSchedulerSpec::Context
let(:order) { [] }
let(:scheduler_class) { FiberScheduler }
let(:indices) { (-10..10).to_a }
context "with timeouts added randomly" do
def operations
indices.shuffle.each do |index|
Fiber.schedule do
Fiber.scheduler.timeout_after(index.fdiv(100)) do
# Sleep will timeout and add to 'order'
sleep
rescue FiberScheduler::Timeout::Error
order << index
end
end
end
end
it "runs timeouts in order" do
setup
sleep 0.11
expect(order).to eq indices
end
end
context "when timeouts are disabled" do
def operations
indices.each do |index|
Fiber.schedule do
Fiber.scheduler.timeout_after(index.fdiv(100)) do
# Even index timeouts will timeout and add to 'order'.
# Odd index timeouts are disabled and will not add to 'order'.
sleep if (index % 2).zero?
rescue FiberScheduler::Timeout::Error
order << index
end
end
end
end
it "does not run disabled timeouts" do
setup
sleep 0.11
expect(order).to eq(-10.step(10, 2).to_a)
end
end
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/spec/fiber_scheduler/nested_fiber_schedule_spec.rb | spec/fiber_scheduler/nested_fiber_schedule_spec.rb | require "fiber_scheduler_spec/context"
RSpec.describe FiberScheduler do
describe "nested Fiber.schedule" do
shared_examples :nested_fiber_schedule do
include_context FiberSchedulerSpec::Context
let(:order) { [] }
context "with only sync operations" do
def operations
Fiber.schedule do
order << 1
Fiber.schedule do
order << 2
end
order << 3
end
end
it "behaves sync" do
setup
expect(order).to eq [1, 2, 3]
end
end
context "with async operations" do
def operations
Fiber.schedule do
order << 1
Fiber.schedule do
order << 2
sleep 0
order << 7
end
order << 6
end
order << 3
Fiber.schedule do
order << 4
end
order << 5
end
it "behaves async" do
setup
expect(order).to eq (1..7).to_a
end
end
end
context "with default setup" do
include_examples :nested_fiber_schedule
end
context "with block setup" do
def setup
FiberScheduler do
operations
end
end
include_examples :nested_fiber_schedule
end
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/spec/fiber_scheduler/fiber_scheduler_spec.rb | spec/fiber_scheduler/fiber_scheduler_spec.rb | require "fiber_scheduler_spec"
RSpec.describe FiberScheduler do
context "with default setup" do
include_examples FiberSchedulerSpec
end
context "with block setup" do
def setup
FiberScheduler do
operations
end
end
include_examples FiberSchedulerSpec
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/spec/fiber_scheduler/blocking_fiber_spec.rb | spec/fiber_scheduler/blocking_fiber_spec.rb | require "fiber_scheduler_spec/context"
RSpec.describe FiberScheduler do
describe "blocking fiber" do
include_context FiberSchedulerSpec::Context
shared_examples :blocking_fiber_schedule do
let(:order) { [] }
context "when scheduled in a top-level fiber" do
def operations
Fiber.schedule do
order << 1
sleep 0.01
order << 6
end
order << 2
Fiber.schedule(:blocking) do
order << 3
sleep 0.01
order << 4
end
order << 5
end
it "stops all other fibers" do
setup
expect(order).to eq (1..6).to_a
end
end
context "when scheduled in a nested fiber" do
def operations
Fiber.schedule do
order << 1
sleep 0.01
order << 8
end
order << 2
Fiber.schedule do
order << 3
Fiber.schedule(:blocking) do
order << 4
sleep 0.01
order << 5
end
order << 6
end
order << 7
end
it "stops all other fibers" do
setup
expect(order).to eq (1..8).to_a
end
end
context "when scheduled in a nested waiting fiber" do
def operations
Fiber.schedule do
order << 1
sleep 0.01
order << 8
end
order << 2
Fiber.schedule(:waiting) do
order << 3
Fiber.schedule(:blocking) do
order << 4
sleep 0.01
order << 5
end
order << 6
end
order << 7
end
it "stops all other fibers" do
setup
expect(order).to eq (1..8).to_a
end
end
end
context "with default setup" do
include_examples :blocking_fiber_schedule
end
context "with block setup" do
def setup
FiberScheduler do
operations
end
end
include_examples :blocking_fiber_schedule
end
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/spec/fiber_scheduler/volatile_fiber_spec.rb | spec/fiber_scheduler/volatile_fiber_spec.rb | require "fiber_scheduler_spec/context"
RSpec.describe FiberScheduler do
describe "volatile fiber" do
include_context FiberSchedulerSpec::Context
shared_examples :volatile_fiber_schedule do
let(:order) { [] }
context "when scheduled in a top-level fiber" do
def operations
Fiber.schedule do
order << 1
sleep 0.001
order << 5
end
order << 2
Fiber.schedule(:volatile) do
order << 3
sleep
order << :this_line_never_runs
end
order << 4
end
it "never finishes" do
setup
expect(order).to eq (1..5).to_a
end
end
context "when scheduled in a nested fiber" do
def operations
Fiber.schedule do
order << 1
sleep 0.001
order << 7
end
order << 2
Fiber.schedule do
order << 3
Fiber.schedule(:volatile) do
order << 4
sleep
order << :this_line_never_runs
end
order << 6
end
order << 5
end
it "never finishes" do
setup
expect(order).to eq (1..7).to_a
end
end
context "when scheduled in a nested waiting fiber" do
def operations
Fiber.schedule do
order << 1
sleep 0.001
order << 7
end
order << 2
Fiber.schedule(:waiting) do
order << 3
Fiber.schedule(:volatile) do
order << 4
sleep
order << :this_line_never_runs
end
order << 5
end
order << 6
end
it "never finishes" do
setup
expect(order).to eq (1..7).to_a
end
end
context "when a volatile fiber ends fast" do
def operations
Fiber.schedule do
order << 1
sleep 0.01
order << 6
end
order << 2
Fiber.schedule(:volatile) do
order << 3
sleep 0.001
order << 5
end
order << 4
end
it "finishes" do
setup
expect(order).to eq (1..6).to_a
end
end
end
context "with default setup" do
include_examples :volatile_fiber_schedule
end
context "with block setup" do
def setup
FiberScheduler do
operations
end
end
include_examples :volatile_fiber_schedule
end
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/spec/fiber_scheduler/async_compatibility_spec.rb | spec/fiber_scheduler/async_compatibility_spec.rb | require "async"
require "fiber_scheduler_spec/context"
RSpec.describe FiberScheduler do
describe "async compatibility" do
include_context FiberSchedulerSpec::Context
let(:order) { [] }
context "with Async block" do
context "without FiberScheduler options" do
it "behaves asynchronous" do
Async do |task|
task.async do
order << 1
sleep 0.001
order << 9
end
order << 2
FiberScheduler do
order << 3
Fiber.schedule do
order << 4
sleep 0.001
order << 10
end
order << 6
Fiber.schedule do
order << 7
sleep 0.001
order << 11
end
order << 8
sleep 0.02
order << 12
end
order << 5
end
expect(order).to eq (1..12).to_a
end
end
context "with a blocking FiberScheduler" do
it "blocks all other async tasks" do
Async do |task|
order << 1
task.async do
order << 2
sleep 0.01
order << 8
end
order << 3
FiberScheduler :blocking do
order << 4
Fiber.schedule do
order << 5
sleep 0.01
order << 9
end
sleep 0.02
order << 6
end
order << 7
end
expect(order).to eq (1..9).to_a
end
end
context "with a waiting FiberScheduler" do
it "behaves sync" do
Async do |task|
order << 1
task.async do
order << 2
sleep 0.01
order << 7
end
order << 3
FiberScheduler :waiting do
order << 4
Fiber.schedule do
order << 5
sleep 0.01
order << 8
end
order << 6
sleep 0.02
order << 9
end
order << 10
end
expect(order).to eq (1..10).to_a
end
end
context "with a volatile FiberScheduler" do
it "behaves sync" do
Async do |task|
order << 1
task.async do
order << 2
sleep 0.01
order << 8
end
order << 3
FiberScheduler :volatile do
order << 4
Fiber.schedule do
order << 5
sleep 0.01
order << 9
end
order << 7
sleep 5
order << :this_line_never_runs
end
order << 6
end
expect(order).to eq (1..9).to_a
end
end
context "with waiting Fiber.schedule" do
it "waits on the fiber" do
Async do |task|
task.async do
order << 1
sleep 0.001
order << 8
end
order << 2
FiberScheduler do
order << 3
Fiber.schedule do
order << 4
sleep 0.002
order << 9
end
order << 6
Fiber.schedule(:waiting) do
order << 7
sleep 0.003
order << 10
end
order << 11
sleep 0.001
order << 12
end
order << 5
end
expect(order).to eq (1..12).to_a
end
end
context "with blocking Fiber.schedule" do
it "waits on the fiber" do
Async do |task|
task.async do
order << 1
sleep 0.001
order << 10
end
order << 2
FiberScheduler do
order << 3
Fiber.schedule do
order << 4
sleep 0.002
order << 11
end
order << 6
Fiber.schedule(:blocking) do
order << 7
sleep 0.003
order << 8
end
order << 9
sleep 0.001
order << 12
end
order << 5
end
expect(order).to eq (1..12).to_a
end
end
context "with blocking FiberScheduler and blocking Fiber.schedule" do
it "waits on the fiber" do
Async do |task|
task.async do
order << 1
sleep 0.001
order << 11
end
order << 2
FiberScheduler :blocking do
order << 3
Fiber.schedule do
order << 4
sleep 0.002
order << 12
end
order << 5
Fiber.schedule(:blocking) do
order << 6
sleep 0.003
order << 7
end
order << 8
sleep 0.001
order << 9
end
order << 10
end
expect(order).to eq (1..12).to_a
end
end
context "with volatile Fiber.schedule" do
context "when volatile fiber contains a blocking operation" do
it "never finishes" do
Async do |task|
task.async do
order << 1
sleep 0.001
order << 9
end
order << 2
FiberScheduler do
order << 3
Fiber.schedule do
order << 4
sleep 0.002
order << 11
end
order << 6
Fiber.schedule(:volatile) do
order << 7
sleep 5
order << :this_line_never_runs
end
order << 8
sleep 0.001
order << 10
end
order << 5
end
expect(order).to eq (1..11).to_a
end
end
context "when volatile fiber contains no blocking operations" do
it "never finishes" do
Async do |task|
task.async do
order << 1
sleep 0.001
order << 9
end
order << 2
FiberScheduler do
order << 3
Fiber.schedule do
order << 4
sleep 0.002
order << 11
end
order << 6
Fiber.schedule(:volatile) do
order << 7
end
order << 8
sleep 0.001
order << 10
end
order << 5
end
expect(order).to eq (1..11).to_a
end
end
end
end
context "with Async::Scheduler" do
context "without FiberScheduler options" do
it "behaves asynchronous" do
scheduler = Async::Scheduler.new
Fiber.set_scheduler scheduler
Fiber.schedule do
order << 1
sleep 0.001
order << 9
end
order << 2
FiberScheduler do
order << 3
Fiber.schedule do
order << 4
sleep 0.001
order << 10
end
order << 6
Fiber.schedule do
order << 7
sleep 0.001
order << 11
end
order << 8
sleep 0.02
order << 12
end
order << 5
scheduler.run
order << 13
expect(order).to eq (1..13).to_a
end
end
context "with a blocking FiberScheduler" do
it "blocks all other async tasks" do
scheduler = Async::Scheduler.new
Fiber.set_scheduler scheduler
order << 1
Fiber.schedule do
order << 2
sleep 0.01
order << 8
end
order << 3
FiberScheduler :blocking do
order << 4
Fiber.schedule do
order << 5
sleep 0.01
order << 9
end
sleep 0.02
order << 7
end
order << 6
scheduler.run
expect(order).to eq (1..9).to_a
end
end
context "with a waiting FiberScheduler" do
it "behaves sync" do
scheduler = Async::Scheduler.new
Fiber.set_scheduler scheduler
order << 1
Fiber.schedule do
order << 2
sleep 0.01
order << 7
end
order << 3
FiberScheduler :waiting do
order << 4
Fiber.schedule do
order << 5
sleep 0.01
order << 8
end
order << 6
sleep 0.02
order << 9
end
order << 10
scheduler.run
expect(order).to eq (1..10).to_a
end
end
end
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/spec/fiber_scheduler/waiting_fiber_spec.rb | spec/fiber_scheduler/waiting_fiber_spec.rb | require "fiber_scheduler_spec/context"
RSpec.describe FiberScheduler do
describe "waiting fiber" do
include_context FiberSchedulerSpec::Context
shared_examples :waiting_fiber_schedule do
let(:order) { [] }
context "when scheduled in a top-level fiber" do
def operations
Fiber.schedule do
order << 1
sleep 0.01
order << 4
end
order << 2
Fiber.schedule(:waiting) do
order << 3
sleep 0.01
order << 5
end
order << 6
Fiber.schedule do
order << 7
sleep 0.01
order << 9
end
order << 8
end
it "stops the parent fiber until the child finishes" do
setup
expect(order).to eq (1..9).to_a
end
end
context "when scheduled in a nested non-waiting fiber" do
def operations
Fiber.schedule do
order << 1
sleep 0.01
order << 8
end
order << 2
Fiber.schedule do
order << 3
Fiber.schedule(:waiting) do
order << 4
sleep 0.01
order << 9
end
order << 10
end
order << 5
Fiber.schedule do
order << 6
sleep 0.01
order << 11
end
order << 7
end
it "stops the parent fiber until the child finishes" do
setup
expect(order).to eq (1..11).to_a
end
end
context "when scheduled in a nested waiting fiber" do
def operations
Fiber.schedule do
order << 1
sleep 0.01
order << 5
end
order << 2
Fiber.schedule(:waiting) do
order << 3
Fiber.schedule(:waiting) do
order << 4
sleep 0.01
order << 6
end
order << 7
end
order << 8
Fiber.schedule do
order << 9
sleep 0.01
order << 11
end
order << 10
end
it "stops the parent fiber until the child finishes" do
setup
expect(order).to eq (1..11).to_a
end
end
end
context "with default setup" do
include_examples :waiting_fiber_schedule
end
context "with block setup" do
def setup
FiberScheduler do
operations
end
end
include_examples :waiting_fiber_schedule
end
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/examples/performance.rb | examples/performance.rb | require "async"
require "benchmark"
require_relative "../lib/fiber_scheduler"
Benchmark.bmbm do |x|
# Max thread count is often 2048
iterations = 2_000
x.report("Async") do
Async do |task|
iterations.times do
task.async { sleep 0 }
end
end
end
x.report("Thread.new") do
iterations.times.map {
Thread.new { sleep 0 }
}.each(&:join)
end
FiberScheduler do
x.report("FiberScheduler") do
FiberScheduler do
iterations.times do
Fiber.schedule { sleep 0 }
end
end
end
end
end
# Rehearsal --------------------------------------------------
# Async 0.087607 0.042180 0.129787 ( 0.262384)
# Thread.new 0.046044 0.206628 0.252672 ( 0.148690)
# FiberScheduler 0.057139 0.017577 0.074716 ( 0.078964)
# ----------------------------------------- total: 0.457175sec
#
# user system total real
# Async 0.062762 0.008537 0.071299 ( 0.097750)
# Thread.new 0.035221 0.189419 0.224640 ( 0.126426)
# FiberScheduler 0.020268 0.000317 0.020585 ( 0.020838)
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/examples/volatile.rb | examples/volatile.rb | require_relative "../lib/fiber_scheduler"
FiberScheduler do
Fiber.schedule(:volatile) do
sleep 1000
end
Fiber.schedule do
sleep 2
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/examples/advanced.rb | examples/advanced.rb | require "httparty"
require "open-uri"
require "redis"
require "sequel"
require_relative "../lib/fiber_scheduler"
DB = Sequel.postgres
Sequel.extension(:fiber_concurrency)
FiberScheduler do
Fiber.schedule do
URI.open("https://httpbin.org/delay/2")
end
Fiber.schedule do
HTTParty.get("https://httpbin.org/delay/2")
end
Fiber.schedule do
Redis.new.blpop("abc123", 2)
end
Fiber.schedule do
DB.run("SELECT pg_sleep(2)")
end
Fiber.schedule do
sleep 2
end
Fiber.schedule do
`sleep 2`
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/examples/nesting.rb | examples/nesting.rb | require_relative "../lib/fiber_scheduler"
FiberScheduler do
Fiber.schedule do
Fiber.schedule do
sleep 2
end
Fiber.schedule do
sleep 2
end
sleep 2
end
Fiber.schedule do
sleep 2
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/examples/blocking.rb | examples/blocking.rb | require_relative "../lib/fiber_scheduler"
FiberScheduler do
Fiber.schedule do
Fiber.schedule(:blocking) do
sleep 2
end
end
Fiber.schedule do
sleep 2
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/examples/basic.rb | examples/basic.rb | require "open-uri"
require_relative "../lib/fiber_scheduler"
FiberScheduler do
Fiber.schedule do
URI.open("https://httpbin.org/delay/2")
end
Fiber.schedule do
URI.open("https://httpbin.org/delay/2")
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/examples/waiting.rb | examples/waiting.rb | require_relative "../lib/fiber_scheduler"
FiberScheduler do
Fiber.schedule do
Fiber.schedule(:waiting) do
sleep 2
end
sleep 2
end
Fiber.schedule do
sleep 2
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/examples/scaling.rb | examples/scaling.rb | require_relative "../lib/fiber_scheduler"
FiberScheduler do
10_000.times do
Fiber.schedule do
sleep 2
end
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/lib/fiber_scheduler.rb | lib/fiber_scheduler.rb | require "resolv"
require_relative "fiber_scheduler/compatibility"
require_relative "fiber_scheduler/selector"
require_relative "fiber_scheduler/timeouts"
begin
# Use io/event selector if available
require "io/event"
rescue LoadError
end
module Kernel
def FiberScheduler(type = nil, &block)
if Fiber.scheduler.nil?
Fiber.set_scheduler(FiberScheduler.new)
begin
yield
ensure
Fiber.set_scheduler(nil)
end
else
scheduler = Fiber.scheduler
# Fiber.scheduler already set, just schedule a fiber.
if scheduler.is_a?(FiberScheduler)
# The default waiting is 'true' as that is the most intuitive behavior
# for a nested FiberScheduler call.
Fiber.schedule(type, &block)
# Unknown fiber scheduler class; can't just pass options to
# Fiber.schedule, handle each option separately.
else
scheduler.singleton_class.prepend(FiberScheduler::Compatibility)
case type
when :blocking
fiber = Fiber.new(blocking: true) do
FiberScheduler::Compatibility.set_internal!
yield
end
fiber.tap(&:resume)
when :waiting
parent = Fiber.current
finished = false # prevents races
blocking = false # prevents #unblock-ing a fiber that never blocked
fiber = Fiber.schedule do
FiberScheduler::Compatibility.set_internal!
yield
ensure
finished = true
scheduler.unblock(nil, parent) if blocking
end
if Fiber.blocking?
# In a blocking fiber, which is potentially also a loop fiber so
# there's nothing we can transfer to. Run other fibers (or just
# block) until waiting fiber finishes.
until finished
scheduler.run_once
end
elsif !finished
blocking = true
scheduler.block(nil, nil)
end
fiber
when :volatile
scheduler.unblock(nil, Fiber.current)
fiber = Fiber.new(blocking: false) do
FiberScheduler::Compatibility.set_internal!
yield
rescue FiberScheduler::Compatibility::Close
# Fiber scheduler is closing.
ensure
scheduler._volatile.delete(Fiber.current)
end
scheduler._volatile[fiber] = nil
fiber.tap(&:transfer)
when nil
Fiber.schedule do
FiberScheduler::Compatibility.set_internal!
yield
end
else
raise "Unknown type"
end
end
end
end
end
class FiberScheduler
def initialize
@fiber = Fiber.current
@selector =
if defined?(IO::Event)
IO::Event::Selector.new(@fiber)
else
Selector.new(@fiber)
end
@timeouts = Timeouts.new
@count = 0
@nested = []
end
def run
while @count > 0
run_once
end
end
def run_once
if @nested.empty?
@selector.select(@timeouts.interval)
@timeouts.call
else
while @nested.any?
fiber = @nested.pop
fiber.transfer
end
end
end
# Fiber::SchedulerInterface methods below
def close
return unless @selector
begin
run
ensure
@selector.close
@selector = nil
end
end
def block(blocker, duration = nil)
return @selector.transfer unless duration
@timeouts.timeout(duration, method: :transfer) do
@selector.transfer
end
end
def unblock(blocker, fiber)
@selector.push(fiber)
end
def kernel_sleep(duration = nil)
return @selector.transfer unless duration
block(:sleep, duration)
end
def address_resolve(hostname)
Resolv.getaddresses(hostname)
end
def io_wait(io, events, duration = nil)
return @selector.io_wait(Fiber.current, io, events) unless duration
@timeouts.timeout(duration, method: :transfer) do
@selector.io_wait(Fiber.current, io, events)
end
end
def io_read(io, buffer, length, offset = 0)
@selector.io_read(Fiber.current, io, buffer, length, offset)
end
def io_write(io, buffer, length, offset = 0)
@selector.io_write(Fiber.current, io, buffer, length, offset)
end
def process_wait(pid, flags)
@selector.process_wait(Fiber.current, pid, flags)
end
def timeout_after(duration, exception = Timeout::Error, message = "timeout", &block)
@timeouts.timeout(duration, exception, message, &block)
end
def fiber(type = nil, &block)
current = Fiber.current
case type
when :blocking
Fiber.new(blocking: true, &block).tap(&:resume)
when :waiting
finished = false # prevents races
fiber = Fiber.new(blocking: false) do
@count += 1
block.call
ensure
@count -= 1
finished = true
# Resume waiting parent fiber
current.transfer
end
fiber.transfer
# Current fiber is waiting until waiting fiber finishes.
if current == @fiber
# In a top-level fiber, there's nothing we can transfer to, so run
# other fibers (or just block) until waiting fiber finishes.
until finished
run_once
end
elsif !finished
@selector.transfer
end
fiber
when :volatile
if current != @fiber
# nested Fiber.schedule
@nested << current
end
Fiber.new(blocking: false, &block).tap(&:transfer)
when nil
if current != @fiber
# nested Fiber.schedule
@nested << current
end
fiber = Fiber.new(blocking: false) do
@count += 1
block.call
ensure
@count -= 1
end
fiber.tap(&:transfer)
else
raise "Unknown type"
end
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/lib/fiber_scheduler/selector.rb | lib/fiber_scheduler/selector.rb | # Copyright, 2021, by Samuel G. D. Williams. <http://www.codeotaku.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# The code in this class has been taken from io-event gem. It has been cleaned
# up and appropriated for use in this gem.
class FiberScheduler
class Selector
EAGAIN = Errno::EAGAIN::Errno
class Waiter
def initialize(fiber, events, tail)
@fiber = fiber
@events = events
@tail = tail
end
def alive?
@fiber&.alive?
end
def transfer(events)
if (fiber = @fiber)
@fiber = nil
fiber.transfer(events & @events) if fiber.alive?
end
@tail&.transfer(events)
end
def invalidate
@fiber = nil
end
def each(&block)
if (fiber = @fiber)
yield fiber, @events
end
@tail&.each(&block)
end
end
def initialize(fiber)
@fiber = fiber
@waiting = {}.compare_by_identity
@ready = []
end
def close
@fiber = nil
@waiting = nil
@ready = nil
end
def transfer
@fiber.transfer
end
def push(fiber)
@ready.push(fiber)
end
def io_wait(fiber, io, events)
waiter = @waiting[io] = Waiter.new(fiber, events, @waiting[io])
@fiber.transfer
ensure
waiter&.invalidate
end
def io_read(fiber, io, buffer, length, offset = 0)
loop do
maximum_size = buffer.size - offset
result = Fiber.new(blocking: true) {
io.read_nonblock(maximum_size, exception: false)
}.resume
case result
when :wait_readable
if length > 0
io_wait(fiber, io, IO::READABLE)
else
return -EAGAIN
end
when :wait_writable
if length > 0
io_wait(fiber, io, IO::WRITABLE)
else
return -EAGAIN
end
when nil
break
else
buffer.set_string(result, offset)
size = result.bytesize
offset += size
break if size >= length
length -= size
end
end
offset
end
def io_write(fiber, io, buffer, length, offset = 0)
loop do
maximum_size = buffer.size - offset
chunk = buffer.get_string(offset, maximum_size)
result = Fiber.new(blocking: true) {
io.write_nonblock(chunk, exception: false)
}.resume
case result
when :wait_readable
if length > 0
io_wait(fiber, io, IO::READABLE)
else
return -EAGAIN
end
when :wait_writable
if length > 0
io_wait(fiber, io, IO::WRITABLE)
else
return -EAGAIN
end
else
offset += result
break if result >= length
length -= result
end
end
offset
end
def process_wait(fiber, pid, flags)
reader, writer = IO.pipe
thread = Thread.new do
Process::Status.wait(pid, flags)
ensure
writer.close
end
io_wait(fiber, reader, IO::READABLE)
thread.value
ensure
reader.close
writer.close
thread&.kill
end
def select(duration = nil)
if @ready.any?
# If we have popped items from the ready list, they may influence the
# duration calculation, so we don't delay the event loop:
duration = 0
count = @ready.size
count.times do
fiber = @ready.shift
fiber.transfer if fiber.alive?
end
end
readable = []
writable = []
@waiting.each do |io, waiter|
waiter.each do |fiber, events|
if (events & IO::READABLE) > 0
readable << io
end
if (events & IO::WRITABLE) > 0
writable << io
end
end
end
duration = 0 if @ready.any?
readable, writable, _ = IO.select(readable, writable, nil, duration)
ready = Hash.new(0)
readable&.each do |io|
ready[io] |= IO::READABLE
end
writable&.each do |io|
ready[io] |= IO::WRITABLE
end
ready.each do |io, events|
waiter = @waiting.delete(io)
waiter.transfer(events)
end
ready.size
end
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/lib/fiber_scheduler/version.rb | lib/fiber_scheduler/version.rb | class FiberScheduler
VERSION = "0.13.0".freeze
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/lib/fiber_scheduler/timeout.rb | lib/fiber_scheduler/timeout.rb | class FiberScheduler
Error = Class.new(RuntimeError)
class Timeout
include Comparable
Error = Class.new(FiberScheduler::Error)
attr_reader :time
def initialize(duration, fiber, method, *args)
@time = Process.clock_gettime(Process::CLOCK_MONOTONIC) + duration
@fiber = fiber
@method = method
@args = args
@disabled = nil
end
def <=>(other)
raise unless other.is_a?(self.class)
@time <=> other.time
end
def call
return unless @fiber.alive?
@fiber.public_send(@method, *@args)
end
def interval
@time - Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
def disable
@disabled = true
end
def disabled?
@disabled
end
def inspect
"#<#{self.class} time=#{@time}>"
end
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/lib/fiber_scheduler/timeouts.rb | lib/fiber_scheduler/timeouts.rb | require_relative "timeout"
class FiberScheduler
class Timeouts
attr_reader :timeouts
def initialize
# Array is sorted by Timeout#time
@timeouts = []
end
def call
now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
while @timeouts.any? && @timeouts.first.time <= now
timeout = @timeouts.shift
unless timeout.disabled?
timeout.call
end
end
end
def timeout(duration, *args, method: :raise, fiber: Fiber.current, &block)
timeout = Timeout.new(duration, fiber, method, *args)
if @timeouts.empty?
@timeouts << timeout
else
# binary search
min = 0
max = @timeouts.size - 1
while min <= max
index = (min + max) / 2
t = @timeouts[index]
if t > timeout
if index.zero? || @timeouts[index - 1] <= timeout
# found it
break
else
# @timeouts[index - 1] > timeout
max = index - 1
end
else
# t <= timeout
index += 1
min = index
end
end
@timeouts.insert(index, timeout)
end
begin
block.call
ensure
# Timeout is disabled if the block finishes earlier.
timeout.disable
end
end
def interval
# Prune disabled timeouts
while @timeouts.first&.disabled?
@timeouts.shift
end
return if @timeouts.empty?
interval = @timeouts.first.interval
interval >= 0 ? interval : 0
end
def inspect
@timeouts.inspect
end
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
bruno-/fiber_scheduler | https://github.com/bruno-/fiber_scheduler/blob/442188f8c752aa236eb3254d52b3dc762d75ac81/lib/fiber_scheduler/compatibility.rb | lib/fiber_scheduler/compatibility.rb | class FiberScheduler
module Compatibility
Close = Class.new(RuntimeError)
def fiber(*args, **opts, &block)
return super unless Compatibility.internal?
# This is `Fiber.schedule` call inside `FiberScheduler { ... }` block.
type = args.first
case type
when :blocking
Fiber.new(blocking: true) {
Compatibility.set_internal!
yield
}.tap(&:resume)
when :waiting
parent = Fiber.current
finished = false # prevents races
blocking = false # prevents #unblock-ing a fiber that never blocked
# Don't pass *args and **opts to an unknown fiber scheduler class.
fiber = super() do
Compatibility.set_internal!
yield
ensure
finished = true
unblock(nil, parent) if blocking
end
unless finished
blocking = true
block(nil, nil)
end
fiber
when :volatile
# Transfer to current fiber some time after a volatile fiber yields.
unblock(nil, Fiber.current)
# Alternative to #unblock: Fiber.scheduler.push(Fiber.current)
fiber = Fiber.new(blocking: false) do
Compatibility.set_internal!
yield
rescue Close
# Fiber scheduler is closing.
ensure
_volatile.delete(Fiber.current)
end
_volatile[fiber] = nil
fiber.tap(&:transfer)
when nil
# Don't pass *args and **opts to an unknown fiber scheduler class.
super() do
Compatibility.set_internal!
yield
end
else
raise "Unknown type"
end
end
# #close and #_volatile handle a complexity in Async::Scheduler#close, more
# specifically this line:
# https://github.com/socketry/async/blob/456df488d801572821eaf5ec2fda10e3b9744a5f/lib/async/scheduler.rb#L55
def close
super
rescue
if _volatile.empty?
Kernel.raise
else
# #dup is used because #_volatile is modified during iteration.
_volatile.dup.each do |fiber, _|
fiber.raise(Close)
end
super # retry
end
end
def _volatile
@_volatile ||= {}
end
def self.set_internal!
Thread.current[:_fiber_scheduler] = true # Sets a FIBER local var!
end
def self.internal?
Thread.current[:_fiber_scheduler]
end
end
end
| ruby | MIT | 442188f8c752aa236eb3254d52b3dc762d75ac81 | 2026-01-04T17:51:31.541762Z | false |
vinibaggio/discover-unused-partials | https://github.com/vinibaggio/discover-unused-partials/blob/ff574761f8b9bfc4e76868f7da3970efb7c05e59/spec/discover-unused-partials_spec.rb | spec/discover-unused-partials_spec.rb | # -*- coding: UTF-8 -*-
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "DiscoverUnusedPartials" do
it "fails" do
fail "hey buddy, you should probably rename this file and start specing for real"
end
end
| ruby | MIT | ff574761f8b9bfc4e76868f7da3970efb7c05e59 | 2026-01-04T17:51:26.104063Z | false |
vinibaggio/discover-unused-partials | https://github.com/vinibaggio/discover-unused-partials/blob/ff574761f8b9bfc4e76868f7da3970efb7c05e59/spec/spec_helper.rb | spec/spec_helper.rb | # -*- coding: UTF-8 -*-
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'discover-unused-partials'
require 'rspec'
RSpec.configure do |config|
end
| ruby | MIT | ff574761f8b9bfc4e76868f7da3970efb7c05e59 | 2026-01-04T17:51:26.104063Z | false |
vinibaggio/discover-unused-partials | https://github.com/vinibaggio/discover-unused-partials/blob/ff574761f8b9bfc4e76868f7da3970efb7c05e59/lib/discover-unused-partials.rb | lib/discover-unused-partials.rb | # -*- coding: UTF-8 -*-
module DiscoverUnusedPartials
def self.find options={}
worker = PartialWorker.new options
tree, dynamic = Dir.chdir(options[:root]){ worker.used_partials("app") }
tree.each do |idx, level|
indent = " " * idx*2
h_indent = idx == 1 ? "" : "\n" + " "*(idx-1)*2
if idx == 1
puts "#{h_indent}The following partials are not referenced directly by any code:"
else
puts "#{h_indent}The following partials are only referenced directly by the partials above:"
end
level[:unused].sort.each do |partial|
puts "#{indent}#{partial}"
end
end
unless dynamic.empty?
puts "\n\nSome of the partials above (at any level) might be referenced dynamically by the following lines of code:"
dynamic.sort.map do |file, lines|
lines.each do |line|
puts " #{file}:#{line}"
end
end
end
end
class PartialWorker
@@filename = /[a-zA-Z\d_\/]+?/
@@extension = /\.\w+/
@@partial = /:partial\s*=>\s*|partial:\s*/
@@render = /\brender\s*(?:\(\s*)?/
def initialize options
@options = options
end
def existent_partials root
partials = []
each_file(root) do |file|
if file =~ /^.*\/_.*$/
partials << file.strip
end
end
partials
end
def used_partials root
raise "#{Dir.pwd} does not have '#{root}' directory" unless File.directory? root
files = []
each_file(root) do |file|
files << file
end
tree = {}
level = 1
existent = existent_partials(root)
top_dynamic = nil
loop do
used, dynamic = process_partials(files)
break if level > 1 && used.size == tree[level-1][:used].size
tree[level] = {
used: used,
}
if level == 1
top_dynamic = dynamic
tree[level][:unused] = existent - used
else
tree[level][:unused] = tree[level-1][:used] - used
end
break unless (files - tree[level][:unused]).size < files.size
files -= tree[level][:unused]
level += 1
end
[tree, top_dynamic]
end
def process_partials(files)
partials = @options['keep'] || []
dynamic = {}
files.each do |file|
File.open(file) do |f|
f.each do |line|
line = line.
encode("UTF-8", "binary", invalid: :replace, undef: :replace, replace: "").
strip
if line =~ %r[(?:#@@partial|#@@render)(['"])/?(#@@filename)#@@extension*\1]
match = $2
if match.index("/")
path = match.split('/')[0...-1].join('/')
file_name = "_#{match.split('/')[-1]}"
full_path = "app/views/#{path}/#{file_name}"
else
if file =~ /app\/controllers\/(.*)_controller.rb/
full_path = "app/views/#{$1}/_#{match}"
else
full_path = "#{file.split('/')[0...-1].join('/')}/_#{match}"
end
end
partials << check_extension_path(full_path)
elsif line =~ /#@@partial|#@@render["']/
if @options["dynamic"] && @options["dynamic"][file]
partials += @options["dynamic"][file]
else
dynamic[file] ||= []
dynamic[file] << line
end
end
end
end
end
partials.uniq!
[partials, dynamic]
end
EXT = %w(.html.erb .text.erb .pdf.erb .erb .html.haml .text.haml .haml .rhtml .html.slim slim)
def check_extension_path(file)
"#{file}#{EXT.find{ |e| File.exist? file + e }}"
end
def each_file(root, &block)
files = Dir.glob("#{root}/*")
files.each do |file|
if File.directory? file
next if file =~ %r[^app/assets]
each_file(file) {|file| yield file}
else
yield file
end
end
end
end
end
| ruby | MIT | ff574761f8b9bfc4e76868f7da3970efb7c05e59 | 2026-01-04T17:51:26.104063Z | false |
vinibaggio/discover-unused-partials | https://github.com/vinibaggio/discover-unused-partials/blob/ff574761f8b9bfc4e76868f7da3970efb7c05e59/lib/discover-unused-partials/version.rb | lib/discover-unused-partials/version.rb | # frozen_string_literal: true
module DiscoverUnusedPartials
VERSION = "0.3.6"
end
| ruby | MIT | ff574761f8b9bfc4e76868f7da3970efb7c05e59 | 2026-01-04T17:51:26.104063Z | false |
erwinjunker/rimportor | https://github.com/erwinjunker/rimportor/blob/543bdd84a77e35365222901f4d00d6c02fd3acba/lib/rimportor.rb | lib/rimportor.rb | require 'rimportor/active_record/sql_builder'
require 'rimportor/active_record/import'
require 'rimportor/plugin'
require 'rimportor/error/bulk_validation'
require 'rimportor/error/invalid_adapter'
require 'rimportor/active_record/adapter/mysql2'
require 'rimportor/util/connection'
require 'generators/install_generator'
module Rimportor
class << self
attr_accessor :configuration
end
def self.configure
self.configuration ||= Configuration.new
yield(configuration) if block_given?
end
class Configuration
attr_accessor :threads
def initialize
@threads = 4
end
end
end
ActiveRecord::Base.send :include, Rimportor::Plugin | ruby | MIT | 543bdd84a77e35365222901f4d00d6c02fd3acba | 2026-01-04T17:51:28.468036Z | false |
erwinjunker/rimportor | https://github.com/erwinjunker/rimportor/blob/543bdd84a77e35365222901f4d00d6c02fd3acba/lib/generators/install_generator.rb | lib/generators/install_generator.rb | require 'rails/generators'
module Rimportor
class InstallGenerator < ::Rails::Generators::Base
source_root(File.expand_path(File.dirname(__FILE__)))
def copy_initializer
copy_file '../templates/rimportor.rb', 'config/initializers/rimportor.rb'
end
end
end | ruby | MIT | 543bdd84a77e35365222901f4d00d6c02fd3acba | 2026-01-04T17:51:28.468036Z | false |
erwinjunker/rimportor | https://github.com/erwinjunker/rimportor/blob/543bdd84a77e35365222901f4d00d6c02fd3acba/lib/rimportor/version.rb | lib/rimportor/version.rb | module Rimportor
VERSION = "0.3"
end
| ruby | MIT | 543bdd84a77e35365222901f4d00d6c02fd3acba | 2026-01-04T17:51:28.468036Z | false |
erwinjunker/rimportor | https://github.com/erwinjunker/rimportor/blob/543bdd84a77e35365222901f4d00d6c02fd3acba/lib/rimportor/plugin.rb | lib/rimportor/plugin.rb | module Rimportor
module Plugin
extend ActiveSupport::Concern
included do
end
module ClassMethods
def rimport(records, options = {})
::Rimportor::ActiveRecord::Import.new(records, self.current_adapter, options).exec_statement
end
def current_adapter
load_adapter(::ActiveRecord::Base.connection_config[:adapter])
end
def load_adapter(adapter_name)
begin
::Rimportor::ActiveRecord::Adapter.const_get(adapter_name.to_s.camelize).new
rescue => e
raise ::Rimportor::Error::InvalidAdapter.new("Invalid adapter. Reason #{e}")
end
end
end
end
end | ruby | MIT | 543bdd84a77e35365222901f4d00d6c02fd3acba | 2026-01-04T17:51:28.468036Z | false |
erwinjunker/rimportor | https://github.com/erwinjunker/rimportor/blob/543bdd84a77e35365222901f4d00d6c02fd3acba/lib/rimportor/util/connection.rb | lib/rimportor/util/connection.rb | module Rimportor
module Util
class Connection
def self.in_pool
::ActiveRecord::Base.connection_pool.with_connection do |connection|
yield(connection)
end
end
end
end
end | ruby | MIT | 543bdd84a77e35365222901f4d00d6c02fd3acba | 2026-01-04T17:51:28.468036Z | false |
erwinjunker/rimportor | https://github.com/erwinjunker/rimportor/blob/543bdd84a77e35365222901f4d00d6c02fd3acba/lib/rimportor/error/bulk_validation.rb | lib/rimportor/error/bulk_validation.rb | module Rimportor
module Error
class BulkValidation < StandardError
end
end
end | ruby | MIT | 543bdd84a77e35365222901f4d00d6c02fd3acba | 2026-01-04T17:51:28.468036Z | false |
erwinjunker/rimportor | https://github.com/erwinjunker/rimportor/blob/543bdd84a77e35365222901f4d00d6c02fd3acba/lib/rimportor/error/invalid_adapter.rb | lib/rimportor/error/invalid_adapter.rb | module Rimportor
module Error
class InvalidAdapter < StandardError
end
end
end | ruby | MIT | 543bdd84a77e35365222901f4d00d6c02fd3acba | 2026-01-04T17:51:28.468036Z | false |
erwinjunker/rimportor | https://github.com/erwinjunker/rimportor/blob/543bdd84a77e35365222901f4d00d6c02fd3acba/lib/rimportor/active_record/sql_builder.rb | lib/rimportor/active_record/sql_builder.rb | module Rimportor
module ActiveRecord
class SqlBuilder
def initialize(model)
@model = model
set_timestamps
end
def full_insert_statement
insert_manager.tap do |im|
im.insert(arel_for_create)
end.to_sql
end
def partial_insert_statement
insert_manager.insert(arel_for_create).to_sql
end
def arel_for_create
@model.send(:arel_attributes_with_values_for_create, @model.attribute_names)
end
def insert_manager
@model.class.arel_table.create_insert
end
def set_timestamps
set_created_at
set_updated_at
end
def set_created_at
@model.updated_at = Time.zone.now if @model.respond_to? :updated_at
end
def set_updated_at
@model.created_at = Time.zone.now if @model.respond_to? :created_at
end
end
end
end | ruby | MIT | 543bdd84a77e35365222901f4d00d6c02fd3acba | 2026-01-04T17:51:28.468036Z | false |
erwinjunker/rimportor | https://github.com/erwinjunker/rimportor/blob/543bdd84a77e35365222901f4d00d6c02fd3acba/lib/rimportor/active_record/import.rb | lib/rimportor/active_record/import.rb | require 'parallel'
module Rimportor
module ActiveRecord
class Import
def initialize(bulk, adapter, opts = {})
@bulk = bulk
@adapter = adapter
@before_callbacks = !!opts[:before_callbacks]
@after_callbacks = !!opts[:after_callbacks]
@validate_bulk = !!opts[:validate_bulk]
@batch_size = opts[:batch_size] ? opts[:batch_size] : 1000
@threads = Rimportor.configuration.threads
end
def run_before_callbacks
::Parallel.map(@bulk, in_threads: @threads) do |element|
execute_callbacks(element, :before)
end
end
def run_after_callbacks
::Parallel.map(@bulk, in_threads: @threads) do |element|
execute_callbacks(element, :after)
end
end
def run_validations
validation_result = ::Parallel.map(@bulk, in_threads: @threads) do |element|
element.valid?
end.all?
raise Rimportor::Error::BulkValidation.new("Your bulk is not valid") unless validation_result
end
def execute_callbacks(element, before_or_after)
case before_or_after
when :before
element.run_callbacks(:save) { false }
when :after
element.run_callbacks(:save) { true }
end
end
def import_statement(batch)
insert_statement = SqlBuilder.new(batch.first).full_insert_statement
result = ::Parallel.map(batch.drop(1), in_threads: @threads) do |element|
@adapter.exec_in_pool { SqlBuilder.new(element).partial_insert_statement.gsub('VALUES', '') }
end
[insert_statement, result]
end
def exec_statement
begin
run_validations if @validate_bulk
run_before_callbacks if @before_callbacks
@bulk.each_slice(@batch_size) do |batch|
@adapter.exec_insert(import_statement(batch))
end
run_after_callbacks if @after_callbacks
true
rescue => e
puts "Error importing the bulk. Reason #{e.message}"
false
end
end
end
end
end | ruby | MIT | 543bdd84a77e35365222901f4d00d6c02fd3acba | 2026-01-04T17:51:28.468036Z | false |
erwinjunker/rimportor | https://github.com/erwinjunker/rimportor/blob/543bdd84a77e35365222901f4d00d6c02fd3acba/lib/rimportor/active_record/adapter/mysql2.rb | lib/rimportor/active_record/adapter/mysql2.rb | module Rimportor
module ActiveRecord
module Adapter
class Mysql2
# Returns maximum number of bytes that the server will accept for a query
# @return [Fixnum] number of maximum allowed packet size
def max_allowed_packet
exec_in_pool do |connection|
result = connection.execute("SHOW VARIABLES like 'max_allowed_packet';")
val = result.respond_to?(:fetch_row) ? result.fetch_row[1] : result.first[1]
val.to_i
end
end
def exec_in_pool
::Rimportor::Util::Connection.in_pool do |connection|
yield(connection)
end
end
# Checks if the given statement is too big for the database insert
# @return [TrueClass, FalseClass] true if the statement size is too big for the database else false
def statement_too_big?(statement)
statement.size > max_allowed_packet
end
def exec_insert(import_statement)
insert_statement, value_statements = import_statement
if statement_too_big? ("#{insert_statement}, #{value_statements.join(',')}")
puts 'Statement too big'
else
exec_statement "#{insert_statement},#{value_statements.join(',')}"
end
end
def exec_statement(statement)
exec_in_pool { |connection| connection.execute statement }
end
end
end
end
end | ruby | MIT | 543bdd84a77e35365222901f4d00d6c02fd3acba | 2026-01-04T17:51:28.468036Z | false |
erwinjunker/rimportor | https://github.com/erwinjunker/rimportor/blob/543bdd84a77e35365222901f4d00d6c02fd3acba/lib/templates/rimportor.rb | lib/templates/rimportor.rb | Rimportor.configure do |config|
# Configure how many threads rimportor should use for importing.
# Consider that rimportor will use threads not only for building the statement
# but also for running validations for your bulk.
# The default value are 4 threads
# config.threads = 4
end | ruby | MIT | 543bdd84a77e35365222901f4d00d6c02fd3acba | 2026-01-04T17:51:28.468036Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..'))
require 'rubygems'
require 'rspec'
require 'timecop'
require 'notion_ruby_client'
Dir[File.join(File.dirname(__FILE__), 'support', '**/*.rb')].each do |file|
require file
end
Notion.configure do |config|
config.token = ENV['NOTION_API_TOKEN']
end
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = '.rspec_status'
end | ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/spec/support/vcr.rb | spec/support/vcr.rb | # frozen_string_literal: true
require 'vcr'
require 'webmock/rspec'
VCR.configure do |config|
config.cassette_library_dir = 'spec/fixtures/notion'
config.hook_into :webmock
# config.default_cassette_options = { record: :new_episodes }
config.configure_rspec_metadata!
config.before_record do |i|
if ENV.key?('NOTION_API_TOKEN')
i.request.headers['Authorization'].first.gsub!(ENV['NOTION_API_TOKEN'], '<NOTION_API_TOKEN>')
end
i.response.body.force_encoding('UTF-8')
end
end
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/spec/support/token.rb | spec/support/token.rb | # frozen_string_literal: true
RSpec.configure do |config|
config.before do
@old_token = Notion::Config.token
end
config.after do
Notion::Config.reset
Notion::Config.token = @old_token
end
end | ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/spec/notion/version_spec.rb | spec/notion/version_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Notion do
it 'has a version' do
expect(Notion::VERSION).not_to be nil
end
end | ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/spec/notion/config_spec.rb | spec/notion/config_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Notion::Config do
describe '#configure' do
before do
Notion.configure do |config|
config.token = 'a token'
end
end
it 'sets token' do
expect(Notion.config.token).to eq 'a token'
end
end
end | ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/spec/notion/api/endpoints/blocks_spec.rb | spec/notion/api/endpoints/blocks_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Notion::Api::Endpoints::Blocks do
let(:client) { Notion::Client.new }
let(:block_id) { '32af3324-ba02-4516-ae88-5728a4d569f4' }
let(:children) do
[
{
'object': 'block',
'type': 'paragraph',
'paragraph': {
'rich_text': [
{
'type': 'text',
'text': {
'content': 'Another children'
}
}
]
}
}
]
end
context 'blocks' do
it 'retrieves', vcr: { cassette_name: 'block' } do
response = client.block(block_id: block_id)
expect(response).not_to be_empty
end
it 'updates', vcr: { cassette_name: 'update_block' } do
to_do = {
'text': [
{
'text': { 'content': 'A todo' }
}
],
'checked': true
}
to_do_block_id = '6e842658-eb3d-4ea9-9bbf-e86104151729'
response = client.update_block(block_id: to_do_block_id, 'to_do' => to_do)
expect(response.id).to eql to_do_block_id
end
it 'deletes', vcr: { cassette_name: 'delete_block' } do
block_id = '77b5d405a5e840229c70b7766d1e8c4b'
response = client.delete_block(block_id: block_id)
expect(response).not_to be_empty
end
it 'children', vcr: { cassette_name: 'block_children' } do
response = client.block_children(block_id: block_id)
expect(response.results.length).to be >= 1
expect(response.results[0].paragraph.rich_text.first.plain_text).to eql 'The first child'
expect(response.results[1].paragraph.rich_text.first.plain_text).to eql 'The second child'
end
it 'paginated children', vcr: { cassette_name: 'paginated_block_children' } do
children = []
client.block_children(block_id: block_id, page_size: 1) do |page|
children.concat page.results
end
expect(children.size).to be >= 1
end
it 'appends', vcr: { cassette_name: 'block_append_children' } do
response = client.block_append_children(block_id: block_id, children: children)
expect(response.results.first.type).to eql 'paragraph'
end
end
end
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/spec/notion/api/endpoints/search_spec.rb | spec/notion/api/endpoints/search_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Notion::Api::Endpoints::Search do
let(:client) { Notion::Client.new }
context 'search' do
it 'searches', vcr: { cassette_name: 'search' } do
response = client.search
expect(response.results.size).to eq 2
end
it 'searches with a query', vcr: { cassette_name: 'search_with_query' } do
response = client.search(query: 'Nicolas')
expect(response.results.size).to eq 1
end
it 'paginated search', vcr: { cassette_name: 'paginated_search' } do
results = []
client.search(page_size: 2) do |page|
results.concat page.results
end
expect(results.size).to eq 2
end
end
end
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/spec/notion/api/endpoints/pages_spec.rb | spec/notion/api/endpoints/pages_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Notion::Api::Endpoints::Pages do
let(:client) { Notion::Client.new }
let(:database_id) { 'dd428e9d-d3fe-4171-870d-a7a1902c748b' }
let(:page_id) { 'c7fd1abe-8114-44ea-be77-9632ea33e581' }
let(:property_id) { '%5BIFC' }
let(:properties) do
{
"Name": {
"title": [
{
"text": {
"content": 'Another Notion page'
}
}
]
}
}
end
let(:children) do
[
{
"object": 'block',
"type": 'heading_2',
"heading_2": {
"text": [{ "type": 'text', "text": { "content": 'A heading' } }]
}
}
]
end
context 'pages' do
it 'retrieves', vcr: { cassette_name: 'page' } do
response = client.page(page_id: page_id)
expect(response.properties.Name.type).to eql 'title'
expect(response.properties.Name.title.first.plain_text).to eql 'Nicolas Goutay'
end
it 'creates', vcr: { cassette_name: 'create_page' } do
response = client.create_page(
parent: { database_id: database_id },
properties: properties,
children: children
)
expect(response.properties.Name.title.first.plain_text).to eql 'Another Notion page'
end
context 'when creating under parent page' do
let(:parent_page) { '0593a719-ff2e-44aa-a14a-2bf169429284' }
let(:properties) do
{
"title": [
{
"text": {
"content": 'Another Notion page'
}
}
]
}
end
let(:children) do
[
{
"object": 'block',
"type": 'heading_2',
"heading_2": {
rich_text: [
{
type: 'text',
text: { content: 'My Heading 2' }
}
]
}
}
]
end
it 'creates', vcr: { cassette_name: 'create_page_with_parent_page' } do
response = client.create_page(
parent: { page_id: parent_page },
properties: properties,
children: children
)
expect(response.parent.page_id).to eql parent_page
expect(response.properties.title.title.first.plain_text).to eql 'Another Notion page'
end
end
it 'updates', vcr: { cassette_name: 'update_page' } do
properties = {
"Name": [
{
"text": {
"content": 'Nicolas Goutay'
}
}
]
}
response = client.update_page(
page_id: page_id,
properties: properties
)
expect(response.properties.Name.title.first.plain_text).to eql 'Nicolas Goutay'
end
it 'retrieves a page property item', vcr: { cassette_name: 'page_property_item' } do
response = client.page_property_item(page_id: page_id, property_id: property_id)
expect(response.email).to eql 'nicolas@orbit.love'
end
end
end
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/spec/notion/api/endpoints/users_spec.rb | spec/notion/api/endpoints/users_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Notion::Api::Endpoints::Users do
let(:client) { Notion::Client.new }
context 'users' do
it 'me', vcr: { cassette_name: 'users_me' } do
response = client.me
expect(response.name).to eql 'Notion to Orbit'
end
it 'lists', vcr: { cassette_name: 'users_list' } do
response = client.users_list
expect(response.results.size).to be 1
end
it 'paginated list', vcr: { cassette_name: 'paginated_users_list' } do
members = []
client.users_list(page_size: 1) do |page|
members.concat page.results
end
expect(members.size).to eq 1
end
it 'retrieves', vcr: { cassette_name: 'users' } do
response = client.user(user_id: 'a8da8d30-c858-4c3d-87ad-3f2d477bd98d')
expect(response.name).to eql 'Nicolas Goutay'
end
end
end | ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/spec/notion/api/endpoints/comments_spec.rb | spec/notion/api/endpoints/comments_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Notion::Api::Endpoints::Comments do
let(:client) { Notion::Client.new }
let(:discussion_comment) do
{
discussion_id: 'ea116af4839c410bb4ac242a18dc4392',
rich_text: [
{
text: {
content: 'test comment'
}
}
]
}
end
let(:page_comment) do
{
parent: { page_id: '3e4bc91d36c74de595113b31c6fdb82c' },
rich_text: [
{
text: {
content: 'test comment'
}
}
]
}
end
describe '#retrieve_comments' do
it 'retrieves comments', vcr: { cassette_name: 'retrieve_comments' } do
response = client.retrieve_comments(block_id: '1a2f70ab26154dc7a838536a3f430af4')
expect(response.results.size).to eq 1
end
end
describe '#create_comment' do
it 'creates a comment on a page', vcr: { cassette_name: 'create_page_comment' } do
response = client.create_comment(page_comment)
expect(response.created_time).not_to be_empty
end
it 'creates a comment on a discussion', vcr: { cassette_name: 'create_discussion_comment' } do
response = client.create_comment(discussion_comment)
expect(response.created_time).not_to be_empty
end
end
end
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/spec/notion/api/endpoints/databases_spec.rb | spec/notion/api/endpoints/databases_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Notion::Api::Endpoints::Databases do
let(:client) { Notion::Client.new }
let(:database_id) { 'dd428e9dd3fe4171870da7a1902c748b' }
let(:page_id) { 'c7fd1abe811444eabe779632ea33e581' }
let(:title) do
[
{
"text": {
"content": 'Orbit 💜 Notion'
}
}
]
end
let(:properties) do
{
"Name": {
"title": {}
}
}
end
context 'databases' do
it 'queries', vcr: { cassette_name: 'database_query' } do
response = client.database_query(database_id: database_id)
expect(response.results.length).to be >= 1
end
it 'paginated queries', vcr: { cassette_name: 'paginated_database_query' } do
pages = []
client.database_query(database_id: database_id, page_size: 1) do |page|
pages.concat page.results
end
expect(pages.size).to be >= 1
end
it 'creates', vcr: { cassette_name: 'create_database' } do
response = client.create_database(
parent: { page_id: page_id },
title: title,
properties: properties
)
expect(response.title.first.plain_text).to eql 'Orbit 💜 Notion'
end
it 'updates', vcr: { cassette_name: 'update_database' } do
response = client.update_database(
database_id: database_id,
title: title
)
expect(response.title.first.plain_text).to eql 'Orbit 💜 Notion'
end
it 'retrieves', vcr: { cassette_name: 'database' } do
response = client.database(database_id: database_id)
expect(response.title.first.plain_text).to eql 'Orbit 💜 Notion'
end
end
end | ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/spec/notion/pagination/cursor_spec.rb | spec/notion/pagination/cursor_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Notion::Api::Pagination::Cursor do
let(:client) { Notion::Client.new }
context 'default cursor' do
let(:cursor) { described_class.new(client, 'users_list', {}) }
it 'provides a default page_size' do
expect(client).to receive(:users_list).with(page_size: 100)
cursor.first
end
it 'handles blank response metadata' do
expect(client).to receive(:users_list).once.and_return(Notion::Messages::Message.new)
cursor.to_a
end
it 'handles nil response metadata' do
expect(client).to(
receive(:users_list).once.and_return(Notion::Messages::Message.new(response: nil))
)
cursor.to_a
end
it 'paginates with a cursor inside response metadata' do
expect(client).to receive(:users_list).twice.and_return(
Notion::Messages::Message.new(has_more: true, next_cursor: 'next'),
Notion::Messages::Message.new
)
expect(cursor).not_to receive(:sleep)
cursor.to_a
end
context 'with rate limiting' do
let(:error) { Notion::Api::Errors::TooManyRequests.new({}) }
context 'with default max retries' do
it 'sleeps after a TooManyRequestsError' do
expect(client).to(
receive(:users_list)
.with(page_size: 100)
.ordered
.and_return(Notion::Messages::Message.new({ has_more: true, next_cursor: 'next' }))
)
expect(client).to(
receive(:users_list).with(page_size: 100, start_cursor: 'next').and_raise(error)
)
expect(cursor).to receive(:sleep).once.ordered.with(10)
expect(client).to(
receive(:users_list)
.with(page_size: 100, start_cursor: 'next')
.ordered
.and_return(Notion::Messages::Message.new)
)
cursor.to_a
end
end
context 'with a custom max_retries' do
let(:cursor) { described_class.new(client, 'users_list', max_retries: 4) }
it 'raises the error after hitting the max retries' do
expect(client).to(
receive(:users_list)
.with(page_size: 100)
.and_return(Notion::Messages::Message.new({ has_more: true, next_cursor: 'next' }))
)
expect(client).to(
receive(:users_list).with(page_size: 100, start_cursor: 'next').exactly(5).times.and_raise(error)
)
expect(cursor).to receive(:sleep).exactly(4).times.with(10)
expect { cursor.to_a }.to raise_error(error)
end
end
context 'with a custom retry_after' do
let(:cursor) { described_class.new(client, 'users_list', retry_after: 5) }
it 'sleeps for retry_after seconds after a TooManyRequestsError' do
expect(client).to(
receive(:users_list)
.with(page_size: 100)
.ordered
.and_return(Notion::Messages::Message.new({ has_more: true, next_cursor: 'next' }))
)
expect(client).to(
receive(:users_list).with(page_size: 100, start_cursor: 'next').ordered.and_raise(error)
)
expect(cursor).to receive(:sleep).once.ordered.with(5)
expect(client).to(
receive(:users_list)
.with(page_size: 100, start_cursor: 'next')
.ordered
.and_return(Notion::Messages::Message.new)
)
cursor.to_a
end
end
end
end
context 'with a custom page_size' do
let(:cursor) { described_class.new(client, 'users_list', page_size: 42) }
it 'overrides default page_size' do
expect(client).to receive(:users_list).with(page_size: 42)
cursor.first
end
end
context 'with a custom sleep_interval' do
let(:cursor) { described_class.new(client, 'users_list', sleep_interval: 3) }
it 'sleeps between requests' do
expect(client).to receive(:users_list).exactly(3).times.and_return(
Notion::Messages::Message.new(has_more: true, next_cursor: 'next_a'),
Notion::Messages::Message.new(has_more: true, next_cursor: 'next_b'),
Notion::Messages::Message.new
)
expect(cursor).to receive(:sleep).with(3).twice
cursor.to_a
end
end
end
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion.rb | lib/notion.rb | # frozen_string_literal: true
require 'notion-ruby-client' | ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion_ruby_client.rb | lib/notion_ruby_client.rb | # frozen_string_literal: true
require 'notion-ruby-client' | ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion-ruby-client.rb | lib/notion-ruby-client.rb | # frozen_string_literal: true
require 'faraday'
require 'faraday/mashify'
require 'faraday/multipart'
require 'json'
require 'logger'
require 'hashie'
require_relative 'notion/version'
require_relative 'notion/logger'
require_relative 'notion/config'
# Messages
require_relative 'notion/messages/message'
require_relative 'notion/config'
require_relative 'notion/api/errors/notion_error'
require_relative 'notion/api/error'
require_relative 'notion/api/errors'
require_relative 'notion/api/errors/internal_error'
require_relative 'notion/api/errors/too_many_requests'
require_relative 'notion/faraday/response/raise_error'
require_relative 'notion/faraday/response/wrap_error'
require_relative 'notion/faraday/connection'
require_relative 'notion/faraday/request'
require_relative 'notion/api/endpoints'
require_relative 'notion/pagination/cursor'
require_relative 'notion/client'
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/version.rb | lib/notion/version.rb | # frozen_string_literal: true
module Notion
VERSION = '1.2.2'
NOTION_REQUEST_VERSION = '2022-02-22'
end
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/logger.rb | lib/notion/logger.rb | # frozen_string_literal: true
require 'logger'
module Notion
class Logger < ::Logger
def self.default
return @default if @default
logger = new STDOUT
logger.level = Logger::WARN
@default = logger
end
end
end
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/client.rb | lib/notion/client.rb | # frozen_string_literal: true
module Notion
class Client
include Faraday::Connection
include Faraday::Request
include Api::Endpoints
attr_accessor(*Config::ATTRIBUTES)
def initialize(options = {})
Notion::Config::ATTRIBUTES.each do |key|
send("#{key}=", options.fetch(key, Notion.config.send(key)))
end
@logger ||= Notion::Config.logger || Notion::Logger.default
@token ||= Notion.config.token
end
class << self
def configure
block_given? ? yield(Config) : Config
end
def config
Config
end
end
end
end | ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/config.rb | lib/notion/config.rb | # frozen_string_literal: true
module Notion
module Config
extend self
ATTRIBUTES = %i[
proxy
user_agent
ca_path
ca_file
logger
endpoint
token
timeout
open_timeout
default_page_size
default_max_retries
default_retry_after
adapter
].freeze
attr_accessor(*Config::ATTRIBUTES)
def reset
self.endpoint = 'https://api.notion.com/v1'
self.user_agent = "Notion Ruby Client/#{Notion::VERSION}"
self.ca_path = nil
self.ca_file = nil
self.token = nil
self.proxy = nil
self.logger = nil
self.timeout = nil
self.open_timeout = nil
self.default_page_size = 100
self.default_max_retries = 100
self.default_retry_after = 10
self.adapter = ::Faraday.default_adapter
end
reset
end
class << self
def configure
block_given? ? yield(Config) : Config
end
def config
Config
end
end
end
Notion::Config.reset
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/messages/message.rb | lib/notion/messages/message.rb | # frozen_string_literal: true
module Notion
module Messages
class Message < Hashie::Mash
def to_s
keys.sort_by(&:to_s).map do |key|
"#{key}=#{self[key]}"
end.join(', ')
end
private
# see https://github.com/intridea/hashie/issues/394
def log_built_in_message(*); end
end
end
end | ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/api/errors.rb | lib/notion/api/errors.rb | # frozen_string_literal: true
module Notion
module Api
module Errors
class BadRequest < NotionError; end
class Forbidden < NotionError; end
class InternalError < NotionError; end
class InvalidRequest < NotionError; end
class ObjectNotFound < NotionError; end
class Unauthorized < NotionError; end
ERROR_CLASSES = {
'bad_request' => BadRequest,
'forbidden' => Forbidden,
'internal_error' => InternalError,
'invalid_request' => InvalidRequest,
'object_not_found' => ObjectNotFound,
'unauthorized' => Unauthorized
}.freeze
end
end
end | ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/api/endpoints.rb | lib/notion/api/endpoints.rb | # frozen_string_literal: true
require_relative 'endpoints/blocks'
require_relative 'endpoints/databases'
require_relative 'endpoints/pages'
require_relative 'endpoints/users'
require_relative 'endpoints/search'
require_relative 'endpoints/comments'
module Notion
module Api
module Endpoints
include Blocks
include Databases
include Pages
include Users
include Search
include Comments
end
end
end
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/api/error.rb | lib/notion/api/error.rb | # frozen_string_literal: true
module Notion
module Api
Error = Errors::NotionError
end
end | ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/api/errors/notion_error.rb | lib/notion/api/errors/notion_error.rb | # frozen_string_literal: true
module Notion
module Api
module Errors
class NotionError < ::Faraday::Error
attr_reader :response
def initialize(message, details, response = nil)
super("#{message} #{details}")
@response = response
end
end
end
end
end | ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/api/errors/too_many_requests.rb | lib/notion/api/errors/too_many_requests.rb | # frozen_string_literal: true
module Notion
module Api
module Errors
class TooManyRequests < ::Faraday::Error
attr_reader :response
def initialize(response)
@response = response
super 'Too many requests'
end
end
end
end
end
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/api/errors/internal_error.rb | lib/notion/api/errors/internal_error.rb | # frozen_string_literal: true
module Notion
module Api
module Errors
class ServerError < InternalError; end
class ParsingError < ServerError; end
class HttpRequestError < ServerError; end
class TimeoutError < HttpRequestError; end
class UnavailableError < HttpRequestError; end
end
end
end | ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/api/endpoints/users.rb | lib/notion/api/endpoints/users.rb | # frozen_string_literal: true
module Notion
module Api
module Endpoints
module Users
#
# Retrieves the bot User associated with the API token provided in
# the authorization header. The bot will have an `owner` field with
# information about the person who authorized the integration.
def me
get("users/me")
end
#
# Retrieves a User object using the ID specified in the request.
#
# @option options [id] :user_id
# User to get info on.
def user(options = {})
throw ArgumentError.new('Required arguments :user_id missing') if options[:user_id].nil?
get("users/#{options[:user_id]}")
end
#
# Returns a paginated list of User objects for the workspace.
#
# @option options [UUID] :start_cursor
# Paginate through collections of data by setting the cursor parameter
# to a start_cursor attribute returned by a previous request's next_cursor.
# Default value fetches the first "page" of the collection.
# See pagination for more detail.
#
# @option options [integer] :page_size
# The number of items from the full list desired in the response. Maximum: 100
def users_list(options = {})
if block_given?
Pagination::Cursor.new(self, :users_list, options).each do |page|
yield page
end
else
get("users", options)
end
end
end
end
end
end | ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/api/endpoints/comments.rb | lib/notion/api/endpoints/comments.rb | # frozen_string_literal: true
module Notion
module Api
module Endpoints
module Comments
#
# Retrieves a list of un-resolved Comment objects from a page or block.
#
# @option options [id] :block_id
# Block or page id to fetch comments for.
#
# @option options [start_cursor] :start_cursor
# If supplied, this endpoint will return a page
# of results starting after the cursor provided.
# If not supplied, this endpoint will return the
# first page of results.
#
# @option options [page_size] :page_size
# The number of items from the full list desired in the response.
# Maximum: 100
#
def retrieve_comments(options = {})
throw ArgumentError.new('Required arguments :block_id missing') if options[:block_id].nil?
if block_given?
Pagination::Cursor.new(self, :retrieve_comments, options).each do |page|
yield page
end
else
get('comments', options)
end
end
#
# Creates a comment in a page or existing discussion thread.
# There are two locations you can add a new comment to:
# - A page
# - An existing discussion thread
# If the intention is to add a new comment to a page, a parent object
# must be provided in the body params. Alternatively, if a new comment
# is being added to an existing discussion thread, the discussion_id string
# must be provided in the body params. Exactly one of these parameters must be provided.
#
# @option options [Object] :parent
# A page parent. Either this or a discussion_id is required (not both).
#
# @option options [UUID] :discussion_id
# A UUID identifier for a discussion thread. Either this or a parent object is required (not both).
#
# @option options [Object] :rich_text
# A rich text object.
def create_comment(options = {})
if options.dig(:parent, :page_id).nil? && options[:discussion_id].nil?
throw ArgumentError.new('Required argument :page_id or :discussion_id missing')
end
throw ArgumentError.new('Required argument :rich_text missing') if options[:rich_text].nil?
post('comments', options)
end
end
end
end
end
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/api/endpoints/blocks.rb | lib/notion/api/endpoints/blocks.rb | # frozen_string_literal: true
module Notion
module Api
module Endpoints
module Blocks
#
# Retrieves a Block object using the ID specified.
#
# @option options [id] :block_id
# Block to get children info on.
def block(options = {})
throw ArgumentError.new('Required arguments :block_id missing') if options[:block_id].nil?
get("blocks/#{options[:block_id]}")
end
#
# Updates the content for the specified block_id based on
# the block type. Supported fields based on the block object
# type (see Block object for available fields and the
# expected input for each field).
#
# @option options [id] :block_id
# Block to get children info on.
#
# @option options [string] {type}
# The block object type value with the properties to be
# updated. Currently only text (for supported block types)
# and checked (for to_do blocks) fields can be updated.
def update_block(options = {})
block_id = options.delete(:block_id)
throw ArgumentError.new('Required arguments :block_id missing') if block_id.nil?
patch("blocks/#{block_id}", options)
end
#
# Sets a Block object, including page blocks, to archived: true
# using the ID specified. Note: in the Notion UI application, this
# moves the block to the "Trash" where it can still be accessed and
# restored.
#
# To restore the block with the API, use the Update a block or
# Update page respectively.
#
# @option options [id] :block_id
# Block to get children info on.
def delete_block(options = {})
throw ArgumentError.new('Required arguments :block_id missing') if options[:block_id].nil?
delete("blocks/#{options[:block_id]}")
end
#
# Returns a paginated array of Block objects contained in the
# block of the requested path using the ID specified.
#
# Returns a 404 HTTP response if any of the following are true:
# - the ID does not exist
# - the bot doesn't have access to the block with the given ID
#
# Returns a 400 or 429 HTTP response if the request exceeds Notion's Request limits.
#
# @option options [id] :block_id
# Block to get children info on.
def block_children(options = {})
throw ArgumentError.new('Required arguments :block_id missing') if options[:block_id].nil?
if block_given?
Pagination::Cursor.new(self, :block_children, options).each do |page|
yield page
end
else
block_id = options.delete(:block_id)
get("blocks/#{block_id}/children", options)
end
end
#
# Creates and appends new children blocks to the parent block
# in the requested path using the ID specified. Returns the Block
# object being appended to.
#
# Returns a 404 HTTP response if any of the following are true:
# - the ID does not exist
# - the bot doesn't have access to the block with the given ID
#
# Returns a 400 or 429 HTTP response if the request exceeds Notion's Request limits.
#
# @option options [id] :block_id
# Block to append children to.
#
# @option options [[Object]] :children
# Children blocks to append
def block_append_children(options = {})
block_id = options.delete(:block_id)
throw ArgumentError.new('Required arguments :block_id missing') if block_id.nil?
patch("blocks/#{block_id}/children", options)
end
end
end
end
end
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/api/endpoints/databases.rb | lib/notion/api/endpoints/databases.rb | # frozen_string_literal: true
module Notion
module Api
module Endpoints
module Databases
#
# Gets a paginated array of Page object s contained in the requested database,
# filtered and ordered according to the filter and sort objects provided in the request.
#
# Filters are similar to the filters provided in the Notion UI. Filters operate
# on database properties and can be combined. If no filter is provided, all the
# pages in the database will be returned with pagination.
#
# Sorts are similar to the sorts provided in the Notion UI. Sorts operate on
# database properties and can be combined. The order of the sorts in the request
# matter, with earlier sorts taking precedence over later ones.
#
# @option options [id] :database_id
# Database to query.
#
# @option options [Object] :filter
# When supplied, limits which pages are returned based on the provided criteria.
#
# @option options [[Object]] :sorts
# When supplied, sorts the results based on the provided criteria.
#
# @option options [UUID] :start_cursor
# Paginate through collections of data by setting the cursor parameter
# to a start_cursor attribute returned by a previous request's next_cursor.
# Default value fetches the first "page" of the collection.
# See pagination for more detail.
#
# @option options [integer] :page_size
# The number of items from the full list desired in the response. Maximum: 100
def database_query(options = {})
throw ArgumentError.new('Required arguments :database_id missing') if options[:database_id].nil?
if block_given?
Pagination::Cursor.new(self, :database_query, options).each do |page|
yield page
end
else
database_id = options.delete(:database_id)
post("databases/#{database_id}/query", options)
end
end
#
# Creates a new database in the specified page.
#
# @option options [Object] :parent
# Parent of the database, which is always going to be a page.
#
# @option options [Object] :title
# Title of this database.
#
# @option options [Object] :properties
# Property schema of database.
# The keys are the names of properties as they appear in Notion and the values are
# property schema objects. Property Schema Object is a metadata that controls
# how a database property behaves, e.g. {"checkbox": {}}.
# Each database must have exactly one database property schema object of type "title".
def create_database(options = {})
throw ArgumentError.new('Required arguments :parent.page_id missing') if options.dig(:parent, :page_id).nil?
throw ArgumentError.new('Required arguments :title missing') if options.dig(:title).nil?
throw ArgumentError.new('Required arguments :properties missing') if options.dig(:properties).nil?
post('databases', options)
end
#
# Updates an existing database as specified by the parameters.
#
# @option options [id] :database_id
# Database to update.
#
# @option options [Object] :title
# Title of database as it appears in Notion. An array of rich text objects.
# If omitted, the database title will remain unchanged.
#
# @option options [Object] :properties
# Updates to the property schema of a database.
# If updating an existing property, the keys are the names or IDs
# of the properties as they appear in Notion and the values
# are property schema objects. If adding a new property, the key is
# the name of the database property and the value is a property schema object.
#
def update_database(options = {})
database_id = options.delete(:database_id)
throw ArgumentError.new('Required arguments :database_id missing') if database_id.nil?
patch("databases/#{database_id}", options)
end
#
# Retrieves a Database object using the ID specified in the request.
#
# Returns a 404 HTTP response if the database doesn't exist, or if the bot
# doesn't have access to the database. Returns a 429 HTTP response if the
# request exceeds Notion's Request limits.
#
# @option options [id] :database_id
# Database to get info on.
def database(options = {})
throw ArgumentError.new('Required arguments :database_id missing') if options[:database_id].nil?
get("databases/#{options[:database_id]}")
end
end
end
end
end | ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/api/endpoints/search.rb | lib/notion/api/endpoints/search.rb | # frozen_string_literal: true
module Notion
module Api
module Endpoints
module Search
#
# Searches all pages and child pages that are shared with the integration.
# The results may include databases.
#
# @option options [string] :query
# When supplied, limits which pages are returned by comparing the query to the page title.
#
# @option options [Object] :filter
# When supplied, filters the results based on the provided criteria.
#
# @option options [[Object]] :sorts
# When supplied, sorts the results based on the provided criteria.
# Limitation: Currently only a single sort is allowed and is limited to last_edited_time.
#
# @option options [UUID] :start_cursor
# Paginate through collections of data by setting the cursor parameter
# to a start_cursor attribute returned by a previous request's next_cursor.
# Default value fetches the first "page" of the collection.
# See pagination for more detail.
#
# @option options [integer] :page_size
# The number of items from the full list desired in the response. Maximum: 100
def search(options = {})
if block_given?
Pagination::Cursor.new(self, :search, options).each do |page|
yield page
end
else
post('search', options)
end
end
end
end
end
end
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/api/endpoints/pages.rb | lib/notion/api/endpoints/pages.rb | # frozen_string_literal: true
module Notion
module Api
module Endpoints
module Pages
#
# Retrieves a 📄Page object using the ID specified in the request path.
# Note that this version of the API only exposes page properties, not page content
#
# @option options [id] :page_id
# Page to get info on.
#
# @option options [bool] :archived
# Set to true to retrieve an archived page; must be false or omitted to
# retrieve a page that has not been archived. Defaults to false.
def page(options = {})
throw ArgumentError.new('Required argument :page_id missing') if options[:page_id].nil?
get("pages/#{options[:page_id]}")
end
#
# Creates a new page in the specified database.
# Later iterations of the API will support creating pages outside databases.
# Note that this iteration of the API will only expose page properties, not
# page content, as described in the data model.
#
# @option options [Object] :parent
# Parent of the page, which is always going to be a database in this version of the API.
#
# @option options [Object] :properties
# Properties of this page.
# The schema for the page's keys and values is described by the properties of
# the database this page belongs to. key string Name of a property as it
# appears in Notion, or property ID. value object Object containing a value
# specific to the property type, e.g. {"checkbox": true}.
#
# @option options [Object] :children
# An optional array of Block objects representing the Page’s content
def create_page(options = {})
if options.dig(:parent, :database_id).nil? && options.dig(:parent, :page_id).nil?
throw ArgumentError.new('Required argument :parent.database_id or :parent.page_id required')
end
post("pages", options)
end
#
# Updates a page by setting the values of any properties specified in the
# JSON body of the request. Properties that are not set via parameters will
# remain unchanged.
#
# Note that this iteration of the API will only expose page properties, not page
# content, as described in the data model.
#
# @option options [id] :page_id
# Page to get info on.
#
# @option options [Object] :properties
# Properties of this page.
# The schema for the page's keys and values is described by the properties of
# the database this page belongs to. key string Name of a property as it
# appears in Notion, or property ID. value object Object containing a value
# specific to the property type, e.g. {"checkbox": true}.
def update_page(options = {})
page_id = options.delete(:page_id)
throw ArgumentError.new('Required argument :page_id missing') if page_id.nil?
patch("pages/#{page_id}", options)
end
#
# Retrieves a `property_item` object for a given `page_id` and `property_id`.
# Depending on the property type, the object returned will either be a value
# or a paginated list of property item values.
#
# @option options [id] :page_id
# Page to get info on.
#
# @option options [id] :property_id
# Property to get info on.
#
def page_property_item(options = {})
throw ArgumentError.new('Required argument :page_id missing') if options[:page_id].nil?
throw ArgumentError.new('Required argument :property_id missing') if options[:property_id].nil?
get("pages/#{options[:page_id]}/properties/#{options[:property_id]}")
end
end
end
end
end
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/pagination/cursor.rb | lib/notion/pagination/cursor.rb | # frozen_string_literal: true
module Notion
module Api
module Pagination
class Cursor
include Enumerable
attr_reader :client
attr_reader :verb
attr_reader :sleep_interval
attr_reader :max_retries
attr_reader :retry_after
attr_reader :params
def initialize(client, verb, params = {})
@client = client
@verb = verb
@params = params.dup
@sleep_interval = @params.delete(:sleep_interval)
@max_retries = @params.delete(:max_retries) || client.default_max_retries
@retry_after = @params.delete(:retry_after) || client.default_retry_after
end
def each
next_cursor = nil
retry_count = 0
loop do
query = { page_size: client.default_page_size }.merge(params)
query = query.merge(start_cursor: next_cursor) unless next_cursor.nil?
begin
response = client.send(verb, query)
rescue Notion::Api::Errors::TooManyRequests => e
raise e if retry_count >= max_retries
client.logger.debug("#{self.class}##{__method__}") { e.to_s }
retry_count += 1
sleep(retry_after)
next
end
yield response
break unless response.has_more
next_cursor = response.next_cursor
break if next_cursor.nil? || next_cursor == ''
retry_count = 0
sleep(sleep_interval) if sleep_interval
end
end
end
end
end
end | ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/faraday/connection.rb | lib/notion/faraday/connection.rb | # frozen_string_literal: true
module Notion
module Faraday
module Connection
private
def connection
@connection ||=
begin
options = {
headers: { 'Accept' => 'application/json; charset=utf-8' }
}
options[:headers]['User-Agent'] = user_agent if user_agent
options[:proxy] = proxy if proxy
options[:ssl] = { ca_path: ca_path, ca_file: ca_file } if ca_path || ca_file
request_options = {}
request_options[:timeout] = timeout if timeout
request_options[:open_timeout] = open_timeout if open_timeout
options[:request] = request_options if request_options.any?
::Faraday::Connection.new(endpoint, options) do |connection|
connection.use ::Faraday::Multipart::Middleware
connection.use ::Faraday::Request::UrlEncoded
connection.use ::Notion::Faraday::Response::RaiseError
connection.use ::Faraday::Mashify::Middleware, mash_class: Notion::Messages::Message
connection.use ::Faraday::Response::Json
connection.use ::Notion::Faraday::Response::WrapError
connection.response :logger, logger if logger
connection.adapter adapter
end
end
end
end
end
end
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.