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
lewagon/foot_traffic
https://github.com/lewagon/foot_traffic/blob/a3e577c2f1d3222f2b8d279465823061584d4a60/examples/single_threaded.rb
examples/single_threaded.rb
require "foot_traffic" using FootTraffic FootTraffic::Session.start do |window| window.new_tab.goto "https://www.lewagon.com" window.new_tab.goto "https://www.lewagon.com/berlin" paris = window.new_tab paris.goto "https://www.lewagon.com/paris" paris.at_css('[href="/paris/apply"]').click paris.at_css("#apply_first_name").focus.type("Alan") paris.at_css("#apply_last_name").focus.type("Turing", :Tab) end
ruby
MIT
a3e577c2f1d3222f2b8d279465823061584d4a60
2026-01-04T17:48:16.406321Z
false
lewagon/foot_traffic
https://github.com/lewagon/foot_traffic/blob/a3e577c2f1d3222f2b8d279465823061584d4a60/examples/clones.rb
examples/clones.rb
require "foot_traffic" using FootTraffic opts = { headless: true, process_timeout: 10, timeout: 100, slowmo: 0.1, window_size: [1024, 768] } begin FootTraffic::Session.start(options: opts, quit: true, clones: 100) do |window, pool| pool << window.tab_thread { |tab| tab.goto "https://www.lewagon.com" } pool << window.tab_thread { |tab| tab.goto "https://www.lewagon.com/berlin" } pool << window.tab_thread { |paris| paris.goto "https://www.lewagon.com/paris" paris.at_css('[href="/paris/apply"]').click paris.at_css("#apply_first_name").focus.type("Alan") paris.at_css("#apply_last_name").focus.type("Turing", :Tab) } pool.wait end rescue FootTraffic::ResourceOverloadError puts "Oops..." exit(1) end
ruby
MIT
a3e577c2f1d3222f2b8d279465823061584d4a60
2026-01-04T17:48:16.406321Z
false
lewagon/foot_traffic
https://github.com/lewagon/foot_traffic/blob/a3e577c2f1d3222f2b8d279465823061584d4a60/examples/simple.rb
examples/simple.rb
require "foot_traffic" using FootTraffic FootTraffic::Session.start do |window| window.tab_thread { |tab| tab.goto "https://www.lewagon.com" } window.tab_thread { |tab| tab.goto "https://www.lewagon.com/berlin" } window.tab_thread { |tab| tab.goto "https://www.lewagon.com/paris" } end
ruby
MIT
a3e577c2f1d3222f2b8d279465823061584d4a60
2026-01-04T17:48:16.406321Z
false
lewagon/foot_traffic
https://github.com/lewagon/foot_traffic/blob/a3e577c2f1d3222f2b8d279465823061584d4a60/examples/multi_threaded_pool.rb
examples/multi_threaded_pool.rb
require "foot_traffic" using FootTraffic FootTraffic::Session.start(quit: true) do |window, pool| pool << window.tab_thread { |tab| tab.goto "https://www.lewagon.com" } pool << window.tab_thread { |tab| tab.goto "https://www.lewagon.com/berlin" } pool << window.tab_thread { |paris| paris.goto "https://www.lewagon.com/paris" paris.at_css('[href="/paris/apply"]').click paris.at_css("#apply_first_name").focus.type("Alan") paris.at_css("#apply_last_name").focus.type("Turing", :Tab) } pool.wait end
ruby
MIT
a3e577c2f1d3222f2b8d279465823061584d4a60
2026-01-04T17:48:16.406321Z
false
lewagon/foot_traffic
https://github.com/lewagon/foot_traffic/blob/a3e577c2f1d3222f2b8d279465823061584d4a60/lib/foot_traffic.rb
lib/foot_traffic.rb
require "foot_traffic/version" require "foot_traffic/session" module FootTraffic class ResourceOverloadError < StandardError; end end
ruby
MIT
a3e577c2f1d3222f2b8d279465823061584d4a60
2026-01-04T17:48:16.406321Z
false
lewagon/foot_traffic
https://github.com/lewagon/foot_traffic/blob/a3e577c2f1d3222f2b8d279465823061584d4a60/lib/foot_traffic/refinements.rb
lib/foot_traffic/refinements.rb
require "ferrum" module FootTraffic refine Ferrum::Context do def new_tab create_page end def in_thread(&block) Thread.new do block.call(create_page) rescue ThreadError, RuntimeError, Errno::EMFILE, Errno::ECONNRESET raise ResourceOverloadError end end alias_method :with_tab, :in_thread alias_method :tab_thread, :in_thread end end
ruby
MIT
a3e577c2f1d3222f2b8d279465823061584d4a60
2026-01-04T17:48:16.406321Z
false
lewagon/foot_traffic
https://github.com/lewagon/foot_traffic/blob/a3e577c2f1d3222f2b8d279465823061584d4a60/lib/foot_traffic/session.rb
lib/foot_traffic/session.rb
require_relative "refinements" require "ferrum" module FootTraffic class ThreadPool def initialize @threads = [] end def <<(thread) @threads << thread end def wait @threads.map(&:join) end end class Session def self.start(options: {}, duration: nil, clones: 1, quit: false, &block) new(options).start(duration: duration, clones: clones, quit: quit, &block) end def initialize(opts) opts[:headless] ||= false @browser ||= Ferrum::Browser.new(opts) end def start(duration: nil, clones: 1, quit: false, &block) main = Thread.new { threads = [] clones.times do threads << Thread.new { window = @browser.contexts.create block.call(window, ThreadPool.new) } end threads.map(&:join) } # A sleeping thread to keep Ferrum open for a given period of time unless quit wait = Thread.new { duration.nil? ? sleep : sleep(duration) } wait.join end main.join @browser.quit rescue ThreadError, RuntimeError, Errno::EMFILE, Errno::ECONNRESET raise ResourceOverloadError end end end
ruby
MIT
a3e577c2f1d3222f2b8d279465823061584d4a60
2026-01-04T17:48:16.406321Z
false
lewagon/foot_traffic
https://github.com/lewagon/foot_traffic/blob/a3e577c2f1d3222f2b8d279465823061584d4a60/lib/foot_traffic/version.rb
lib/foot_traffic/version.rb
module FootTraffic VERSION = "0.1.0" end
ruby
MIT
a3e577c2f1d3222f2b8d279465823061584d4a60
2026-01-04T17:48:16.406321Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/test/test_helper.rb
test/test_helper.rb
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'web3/eth' require 'minitest/autorun'
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/test/web3/eth_test.rb
test/web3/eth_test.rb
require 'test_helper' class Web3::EthTest < Minitest::Test def test_that_it_has_a_version_number refute_nil ::Web3::Eth::VERSION end def test_it_does_something_useful assert false end end
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/lib/web3/eth.rb
lib/web3/eth.rb
require "web3/eth/version" require "web3/eth/abi/abi_coder" require "web3/eth/utility" require "web3/eth/block" require "web3/eth/transaction" require "web3/eth/contract" require "web3/eth/call_trace" require "web3/eth/log" require "web3/eth/transaction_receipt" require "web3/eth/eth_module" require "web3/eth/trace_module" require "web3/eth/etherscan" require "web3/eth/rpc"
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/lib/web3/eth/trace_module.rb
lib/web3/eth/trace_module.rb
module Web3 module Eth class TraceModule include Web3::Eth::Utility PREFIX = 'trace_' def initialize web3_rpc @web3_rpc = web3_rpc end def method_missing m, *args @web3_rpc.request "#{PREFIX}#{m}", args[0] end def internalCallsByHash tx_hash @web3_rpc.request("#{PREFIX}transaction", [tx_hash]).select{|t| t['traceAddress']!=[]}.collect{|t| CallTrace.new t } end end end end
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/lib/web3/eth/eth_module.rb
lib/web3/eth/eth_module.rb
module Web3 module Eth class EthModule include Web3::Eth::Utility PREFIX = 'eth_' def initialize web3_rpc @web3_rpc = web3_rpc end def getBalance address, block = 'latest', convert_to_eth = true wei = @web3_rpc.request("#{PREFIX}#{__method__}", [address, block]).to_i 16 convert_to_eth ? wei_to_ether(wei) : wei end def getBlockByNumber block, full = true, convert_to_object = true resp = @web3_rpc.request("#{PREFIX}#{__method__}", [hex(block), full]) convert_to_object ? Block.new(resp) : resp end def blockNumber from_hex @web3_rpc.request("#{PREFIX}#{__method__}") end def getTransactionByHash tx_hash Transaction.new @web3_rpc.request("#{PREFIX}#{__method__}", [tx_hash]) end def getTransactionReceipt tx_hash TransactionReceipt.new @web3_rpc.request("#{PREFIX}#{__method__}", [tx_hash]) end def contract abi Web3::Eth::Contract.new abi, @web3_rpc end def load_contract etherscan_api, contract_address contract(etherscan_api.contract_getabi address: contract_address).at contract_address end def method_missing m, *args @web3_rpc.request "#{PREFIX}#{m}", args[0] end end end end
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/lib/web3/eth/version.rb
lib/web3/eth/version.rb
module Web3 module Eth VERSION = "0.2.16" end end
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/lib/web3/eth/contract.rb
lib/web3/eth/contract.rb
module Web3 module Eth class Contract class ContractInstance def initialize contract, address @contract = contract @address = address end def method_missing m, *args @contract.call_contract @address, m.to_s, args end def __contract__ @contract end def __address__ @address end end class ContractMethod include Abi::AbiCoder include Abi::Utils include Utility attr_reader :abi, :signature, :name, :signature_hash, :input_types, :output_types, :constant def initialize abi @abi = abi @name = abi['name'] @constant = !!abi['constant'] @input_types = abi['inputs'].map{|a| a['type']} @output_types = abi['outputs'].map{|a| a['type']} if abi['outputs'] @signature = Abi::Utils.function_signature @name, @input_types @signature_hash = Abi::Utils.signature_hash @signature, (abi['type']=='event' ? 64 : 8) end def parse_event_args log log_data = remove_0x_head log.raw_data['data'] indexed_types = abi['inputs'].select{|a| a['indexed']}.collect{|a| a['type']} not_indexed_types = abi['inputs'].select{|a| !a['indexed']}.collect{|a| a['type']} indexed_args = log.indexed_args if indexed_args.size==indexed_types.size indexed_values = [indexed_types, indexed_args].transpose.collect{|arg| decode_typed_data( arg.first, [arg.second].pack('H*') ) } not_indexed_values = not_indexed_types.empty? ? [] : decode_abi(not_indexed_types, [log_data].pack('H*') ) i = j = 0 abi['inputs'].collect{|input| input['indexed'] ? (i+=1; indexed_values[i-1]) : (j+=1;not_indexed_values[j-1]) } elsif !indexed_args.empty? || !log_data.empty? all_types = abi['inputs'].collect{|a| a['type']} [all_types[0...indexed_args.size], indexed_args].transpose.collect{|arg| decode_typed_data( arg.first, [arg.second].pack('H*') ) } + decode_abi(all_types[indexed_args.size..-1], [log_data].pack('H*') ) else [] end end def parse_method_args transaction d = transaction.call_input_data (!d || d.empty?) ? [] : decode_abi(input_types, [d].pack('H*')) end def do_call web3_rpc, contract_address, args data = '0x' + signature_hash + encode_hex(encode_abi(input_types, args) ) response = web3_rpc.request "eth_call", [{ to: contract_address, data: data}, 'latest'] string_data = [remove_0x_head(response)].pack('H*') return nil if string_data.empty? result = decode_abi output_types, string_data result.length==1 ? result.first : result end end attr_reader :web3_rpc, :abi, :functions, :events, :constructor, :functions_by_hash, :events_by_hash def initialize abi, web_rpc = nil @web3_rpc = web_rpc @abi = abi.kind_of?(String) ? JSON.parse(abi) : abi parse_abi @abi end def at address ContractInstance.new self, address end def call_contract contract_address, method_name, args function = functions[method_name] raise "No method found in ABI: #{method_name}" unless function raise "Function #{method_name} is not constant: #{method_name}, requires to sign transaction" unless function.constant function.do_call web3_rpc, contract_address, args end def find_event_by_hash method_hash @events_by_hash[method_hash] end def find_function_by_hash method_hash @functions_by_hash[method_hash] end def parse_log_args log event = find_event_by_hash log.method_hash raise "No event found by hash #{log.method_hash}, probably ABI is not related to log event" unless event event.parse_event_args log end def parse_call_args transaction function = find_function_by_hash transaction.method_hash raise "No function found by hash #{transaction.method_hash}, probably ABI is not related to call" unless function function.parse_method_args transaction end def parse_constructor_args transaction constructor ? constructor.parse_method_args(transaction) : [] end private def parse_abi abi @functions = {} @events = {} @functions_by_hash = {} @events_by_hash = {} abi.each{|a| case a['type'] when 'function' method = ContractMethod.new(a) @functions[method.name] = method @functions_by_hash[method.signature_hash] = method when 'event' method = ContractMethod.new(a) @events[method.name] = method @events_by_hash[method.signature_hash] = method when 'constructor' method = ContractMethod.new(a) @constructor = method end } end end end end
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/lib/web3/eth/rpc.rb
lib/web3/eth/rpc.rb
module Web3 module Eth class Rpc require 'json' require 'net/http' JSON_RPC_VERSION = '2.0' DEFAULT_CONNECT_OPTIONS = { use_ssl: false, open_timeout: 10, read_timeout: 70 } DEFAULT_HOST = 'localhost' DEFAULT_PORT = 8545 attr_reader :eth, :trace def initialize host: DEFAULT_HOST, port: DEFAULT_PORT, connect_options: DEFAULT_CONNECT_OPTIONS @client_id = Random.rand 10000000 @uri = URI((connect_options[:use_ssl] ? 'https' : 'http')+ "://#{host}:#{port}#{connect_options[:rpc_path]}") @connect_options = connect_options @eth = EthModule.new self @trace = TraceModule.new self end def request method, params = nil Net::HTTP.start(@uri.host, @uri.port, @connect_options) do |http| request = Net::HTTP::Post.new @uri, {"Content-Type" => "application/json"} request.body = {:jsonrpc => JSON_RPC_VERSION, method: method, params: params, id: @client_id}.compact.to_json response = http.request request raise "Error code #{response.code} on request #{@uri.to_s} #{request.body}" unless response.kind_of? Net::HTTPOK body = JSON.parse(response.body) if body['result'] body['result'] elsif body['error'] raise "Error #{@uri.to_s} #{body['error']} on request #{@uri.to_s} #{request.body}" else raise "No response on request #{@uri.to_s} #{request.body}" end end end end end end unless Hash.method_defined?(:compact) class Hash def compact self.reject{ |_k, v| v.nil? } end end end
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/lib/web3/eth/utility.rb
lib/web3/eth/utility.rb
module Web3 module Eth module Utility def hex num '0x' + num.to_s(16) end def wei_to_ether(wei) 1.0 * wei / 10**18 end def from_hex h h.to_i 16 end def remove_0x_head(s) s[0,2] == '0x' ? s[2..-1] : s end end end end
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/lib/web3/eth/log.rb
lib/web3/eth/log.rb
module Web3 module Eth class Log attr_reader :raw_data def initialize log @raw_data = log log.each do |k, v| self.instance_variable_set("@#{k}", v) self.class.send(:define_method, k, proc {self.instance_variable_get("@#{k}")}) end end def has_topics? !!topics.first end def method_hash topics.first && topics.first[2..65] end def indexed_args topics[1...topics.size].collect{|x| x[2..65]} end end end end
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/lib/web3/eth/transaction.rb
lib/web3/eth/transaction.rb
module Web3 module Eth class Transaction include Web3::Eth::Utility attr_reader :raw_data def initialize transaction_data @raw_data = transaction_data transaction_data.each do |k, v| self.instance_variable_set("@#{k}", v) self.class.send(:define_method, k, proc {self.instance_variable_get("@#{k}")}) end end def method_hash if input && input.length>=10 input[2...10] else nil end end # suffix # 0xa1 0x65 'b' 'z' 'z' 'r' '0' 0x58 0x20 <32 bytes swarm hash> 0x00 0x29 # look http://solidity.readthedocs.io/en/latest/metadata.html for details def call_input_data if raw_data['creates'] && input fetch_constructor_data input elsif input && input.length>10 input[10..input.length] else [] end end def block_number # if transaction is less than 12 seconds old, blockNumber will be nil # :. nil check before calling `to_hex` to avoid argument error blockNumber && from_hex(blockNumber) end def value_wei from_hex value end def value_eth wei_to_ether from_hex value end def gas_limit from_hex gas end def gasPrice_eth wei_to_ether from_hex gasPrice end private CONSTRUCTOR_SEQ = /a165627a7a72305820\w{64}0029(\w*)$/ def fetch_constructor_data input data = input[CONSTRUCTOR_SEQ,1] while data && (d = data[CONSTRUCTOR_SEQ,1]) data = d end data end end end end
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/lib/web3/eth/transaction_receipt.rb
lib/web3/eth/transaction_receipt.rb
module Web3 module Eth class TransactionReceipt include Web3::Eth::Utility attr_reader :raw_data def initialize transaction_data @raw_data = transaction_data transaction_data.each do |k, v| self.instance_variable_set("@#{k}", v) self.class.send(:define_method, k, proc {self.instance_variable_get("@#{k}")}) end @logs = @logs.collect {|log| Web3::Eth::Log.new log } end def block_number from_hex blockNumber end def success? status==1 || status=='0x1' || status.nil? end def gas_used from_hex gasUsed end def cumulative_gas_used from_hex cumulativeGasUsed end end end end
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/lib/web3/eth/etherscan.rb
lib/web3/eth/etherscan.rb
module Web3 module Eth class Etherscan DEFAULT_CONNECT_OPTIONS = { open_timeout: 10, read_timeout: 70, parse_result: true, url: 'https://api.etherscan.io/api' } attr_reader :api_key, :connect_options def initialize api_key, connect_options: DEFAULT_CONNECT_OPTIONS @api_key = api_key @connect_options = connect_options end def method_missing m, *args api_module, action = m.to_s.split '_', 2 raise "Calling method must be in form <module>_<action>" unless action arguments = args[0].kind_of?(String) ? { address: args[0] } : args[0] result = request api_module, action, arguments if connect_options[:parse_result] begin JSON.parse result rescue result end else result end end private def request api_module, action, args = {} uri = URI connect_options[:url] uri.query = URI.encode_www_form({ module: api_module, action: action, apikey: api_key }.merge(args)) Net::HTTP.start(uri.host, uri.port, connect_options.merge(use_ssl: uri.scheme=='https' )) do |http| request = Net::HTTP::Get.new uri response = http.request request raise "Error code #{response.code} on request #{uri.to_s} #{request.body}" unless response.kind_of? Net::HTTPOK json = JSON.parse(response.body) raise "Response #{json['message']} on request #{uri.to_s}" unless json['status']=='1' json['result'] end end end end end
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/lib/web3/eth/call_trace.rb
lib/web3/eth/call_trace.rb
module Web3 module Eth class CallTrace include Web3::Eth::Utility attr_reader :raw_data def initialize trace_data @raw_data = trace_data trace_data.each do |k, v| self.instance_variable_set("@#{k}", v) self.class.send(:define_method, k, proc {self.instance_variable_get("@#{k}")}) end end def value_wei from_hex action['value'] end def value_eth wei_to_ether from_hex action['value'] end def from action['from'] end def to action['to'] end def input action['input'] || action['init'] end def output result && result['output'] end def gas_used result && from_hex(result['gasUsed']) end def method_hash if input && input.length>=10 input[2...10] else nil end end def creates action && result && action['init'] && result['address'] end # suffix # 0xa1 0x65 'b' 'z' 'z' 'r' '0' 0x58 0x20 <32 bytes swarm hash> 0x00 0x29 # look http://solidity.readthedocs.io/en/latest/metadata.html for details def call_input_data if creates && input input[/a165627a7a72305820\w{64}0029(\w*)/,1] elsif input && input.length>10 input[10..input.length] else [] end end def suicide? type=='suicide' end def balance_ether wei_to_ether action['balance'].to_i(16) end def success? !raw_data['error'] end end end end
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/lib/web3/eth/block.rb
lib/web3/eth/block.rb
module Web3 module Eth class Block include Web3::Eth::Utility attr_reader :raw_data def initialize block_data @raw_data = block_data block_data.each do |k, v| self.instance_variable_set("@#{k}", v) self.class.send(:define_method, k, proc {self.instance_variable_get("@#{k}")}) end @transactions = @transactions.collect {|t| Web3::Eth::Transaction.new t } end def timestamp_time Time.at from_hex timestamp end def block_number from_hex number end end end end
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/lib/web3/eth/abi/exceptions.rb
lib/web3/eth/abi/exceptions.rb
# -*- encoding : ascii-8bit -*- module Web3::Eth::Abi class DeprecatedError < StandardError; end class ChecksumError < StandardError; end class FormatError < StandardError; end class ValidationError < StandardError; end class ValueError < StandardError; end class AssertError < StandardError; end class UnknownParentError < StandardError; end class InvalidBlock < ValidationError; end class InvalidUncles < ValidationError; end class InvalidTransaction < ValidationError; end class UnsignedTransactionError < InvalidTransaction; end class InvalidNonce < InvalidTransaction; end class InsufficientStartGas < InvalidTransaction; end class InsufficientBalance < InvalidTransaction; end class BlockGasLimitReached < InvalidTransaction; end class InvalidSPVProof < ValidationError; end class ContractCreationFailed < StandardError; end class TransactionFailed < StandardError; end end
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/lib/web3/eth/abi/type.rb
lib/web3/eth/abi/type.rb
# -*- encoding : ascii-8bit -*- module Web3::Eth::Abi class Type class ParseError < StandardError; end class <<self ## # Crazy regexp to seperate out base type component (eg. uint), size (eg. # 256, 128x128, nil), array component (eg. [], [45], nil) # def parse(type) _, base, sub, dimension = /([a-z]*)([0-9]*x?[0-9]*)((\[[0-9]*\])*)/.match(type).to_a dims = dimension.scan(/\[[0-9]*\]/) raise ParseError, "Unknown characters found in array declaration" if dims.join != dimension case base when '' return parse 'address' when 'string' raise ParseError, "String type must have no suffix or numerical suffix" unless sub.empty? when 'bytes' raise ParseError, "Maximum 32 bytes for fixed-length string or bytes" unless sub.empty? || sub.to_i <= 32 when 'uint', 'int' raise ParseError, "Integer type must have numerical suffix" unless sub =~ /\A[0-9]+\z/ size = sub.to_i raise ParseError, "Integer size out of bounds" unless size >= 8 && size <= 256 raise ParseError, "Integer size must be multiple of 8" unless size % 8 == 0 when 'fixed', 'ufixed' raise ParseError, "Fixed type must have suffix of form <high>x<low>, e.g. 128x128" unless sub =~ /\A[0-9]+x[0-9]+\z/ high, low = sub.split('x').map(&:to_i) total = high + low raise ParseError, "Fixed size out of bounds (max 32 bytes)" unless total >= 8 && total <= 256 raise ParseError, "Fixed high/low sizes must be multiples of 8" unless high % 8 == 0 && low % 8 == 0 when 'hash' raise ParseError, "Hash type must have numerical suffix" unless sub =~ /\A[0-9]+\z/ when 'address' raise ParseError, "Address cannot have suffix" unless sub.empty? when 'bool' raise ParseError, "Bool cannot have suffix" unless sub.empty? else raise ParseError, "Unrecognized type base: #{base}" end new(base, sub, dims.map {|x| x[1...-1].to_i}) end def size_type @size_type ||= new('uint', 256, []) end end attr :base, :sub, :dims ## # @param base [String] base name of type, e.g. uint for uint256[4] # @param sub [String] subscript of type, e.g. 256 for uint256[4] # @param dims [Array[Integer]] dimensions of array type, e.g. [1,2,0] # for uint256[1][2][], [] for non-array type # def initialize(base, sub, dims) @base = base @sub = sub @dims = dims end def ==(another_type) base == another_type.base && sub == another_type.sub && dims == another_type.dims end ## # Get the static size of a type, or nil if dynamic. # # @return [Integer, NilClass] size of static type, or nil for dynamic # type # def size @size ||= if dims.empty? if %w(string bytes).include?(base) && sub.empty? nil else 32 end else if dims.last == 0 # 0 for dynamic array [] nil else subtype.dynamic? ? nil : dims.last * subtype.size end end end def dynamic? size.nil? end ## # Type with one dimension lesser. # # @example # Type.parse("uint256[2][]").subtype # => Type.new('uint', 256, [2]) # # @return [Ethereum::ABI::Type] # def subtype @subtype ||= self.class.new(base, sub, dims[0...-1]) end end end
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/lib/web3/eth/abi/utils.rb
lib/web3/eth/abi/utils.rb
# -*- encoding : ascii-8bit -*- require 'digest' require 'digest/sha3' require 'openssl' require 'rlp' module Web3::Eth::Abi module Utils extend self include Constant ## # Not the keccak in sha3, although it's underlying lib named SHA3 # def keccak256(x) Digest::SHA3.new(256).digest(x) end def keccak512(x) Digest::SHA3.new(512).digest(x) end def keccak256_rlp(x) keccak256 RLP.encode(x) end def sha256(x) Digest::SHA256.digest x end def double_sha256(x) sha256 sha256(x) end def ripemd160(x) Digest::RMD160.digest x end def hash160(x) ripemd160 sha256(x) end def hash160_hex(x) encode_hex hash160(x) end def mod_exp(x, y, n) x.to_bn.mod_exp(y, n).to_i end def mod_mul(x, y, n) x.to_bn.mod_mul(y, n).to_i end def to_signed(i) i > Constant::INT_MAX ? (i-Constant::TT256) : i end def base58_check_to_bytes(s) leadingzbytes = s.match(/\A1*/)[0] data = Constant::BYTE_ZERO * leadingzbytes.size + BaseConvert.convert(s, 58, 256) raise ChecksumError, "double sha256 checksum doesn't match" unless double_sha256(data[0...-4])[0,4] == data[-4..-1] data[1...-4] end def bytes_to_base58_check(bytes, magicbyte=0) bs = "#{magicbyte.chr}#{bytes}" leadingzbytes = bs.match(/\A#{Constant::BYTE_ZERO}*/)[0] checksum = double_sha256(bs)[0,4] '1'*leadingzbytes.size + BaseConvert.convert("#{bs}#{checksum}", 256, 58) end def ceil32(x) x % 32 == 0 ? x : (x + 32 - x%32) end def encode_hex(b) RLP::Utils.encode_hex b end def decode_hex(s) RLP::Utils.decode_hex s end def big_endian_to_int(s) RLP::Sedes.big_endian_int.deserialize s.sub(/\A(\x00)+/, '') end def int_to_big_endian(n) RLP::Sedes.big_endian_int.serialize n end def lpad(x, symbol, l) return x if x.size >= l symbol * (l - x.size) + x end def rpad(x, symbol, l) return x if x.size >= l x + symbol * (l - x.size) end def zpad(x, l) lpad x, BYTE_ZERO, l end def zunpad(x) x.sub /\A\x00+/, '' end def zpad_int(n, l=32) zpad encode_int(n), l end def zpad_hex(s, l=32) zpad decode_hex(s), l end def int_to_addr(x) zpad_int x, 20 end def encode_int(n) raise ArgumentError, "Integer invalid or out of range: #{n}" unless n.is_a?(Integer) && n >= 0 && n <= UINT_MAX int_to_big_endian n end def decode_int(v) raise ArgumentError, "No leading zero bytes allowed for integers" if v.size > 0 && (v[0] == Constant::BYTE_ZERO || v[0] == 0) big_endian_to_int v end def bytearray_to_int(arr) o = 0 arr.each {|x| o = (o << 8) + x } o end def int_array_to_bytes(arr) arr.pack('C*') end def bytes_to_int_array(bytes) bytes.unpack('C*') end def coerce_to_int(x) if x.is_a?(Numeric) x elsif x.size == 40 big_endian_to_int decode_hex(x) else big_endian_to_int x end end def coerce_to_bytes(x) if x.is_a?(Numeric) int_to_big_endian x elsif x.size == 40 decode_hex(x) else x end end def coerce_addr_to_hex(x) if x.is_a?(Numeric) encode_hex zpad(int_to_big_endian(x), 20) elsif x.size == 40 || x.size == 0 x else encode_hex zpad(x, 20)[-20..-1] end end def normalize_address(x, allow_blank: false) address = Address.new(x) raise ValueError, "address is blank" if !allow_blank && address.blank? address.to_bytes end def mk_contract_address(sender, nonce) keccak256_rlp([normalize_address(sender), nonce])[12..-1] end def mk_metropolis_contract_address(sender, initcode) keccak256(normalize_address(sender) + initcode)[12..-1] end def parse_int_or_hex(s) if s.is_a?(Numeric) s elsif s[0,2] == '0x' big_endian_to_int decode_hex(normalize_hex_without_prefix(s)) else s.to_i end end def normalize_hex_without_prefix(s) if s[0,2] == '0x' (s.size % 2 == 1 ? '0' : '') + s[2..-1] else s end end def function_signature method_name, arg_types "#{method_name}(#{arg_types.join(',')})" end def signature_hash signature, length=64 encode_hex(keccak256(signature))[0...length] end end end
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/lib/web3/eth/abi/abi_coder.rb
lib/web3/eth/abi/abi_coder.rb
# -*- encoding : ascii-8bit -*- require 'web3/eth/abi/type' require 'web3/eth/abi/constant' require 'web3/eth/abi/exceptions' require 'web3/eth/abi/utils' module Web3::Eth::Abi ## # Contract ABI encoding and decoding. # # @see https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI # module AbiCoder extend self include Constant class EncodingError < StandardError; end class DecodingError < StandardError; end class ValueOutOfBounds < ValueError; end ## # Encodes multiple arguments using the head/tail mechanism. # def encode_abi(types, args) parsed_types = types.map {|t| Type.parse(t) } head_size = (0...args.size) .map {|i| parsed_types[i].size || 32 } .reduce(0, &:+) head, tail = '', '' args.each_with_index do |arg, i| if parsed_types[i].dynamic? head += encode_type(Type.size_type, head_size + tail.size) tail += encode_type(parsed_types[i], arg) else head += encode_type(parsed_types[i], arg) end end "#{head}#{tail}" end alias :encode :encode_abi ## # Encodes a single value (static or dynamic). # # @param type [Ethereum::ABI::Type] value type # @param arg [Object] value # # @return [String] encoded bytes # def encode_type(type, arg) if %w(string bytes).include?(type.base) && type.sub.empty? encode_primitive_type type, arg elsif type.dynamic? raise ArgumentError, "arg must be an array" unless arg.instance_of?(Array) head, tail = '', '' if type.dims.last == 0 head += encode_type(Type.size_type, arg.size) else raise ArgumentError, "Wrong array size: found #{arg.size}, expecting #{type.dims.last}" unless arg.size == type.dims.last end sub_type = type.subtype sub_size = type.subtype.size arg.size.times do |i| if sub_size.nil? head += encode_type(Type.size_type, 32*arg.size + tail.size) tail += encode_type(sub_type, arg[i]) else head += encode_type(sub_type, arg[i]) end end "#{head}#{tail}" else # static type if type.dims.empty? encode_primitive_type type, arg else arg.map {|x| encode_type(type.subtype, x) }.join end end end def encode_primitive_type(type, arg) case type.base when 'uint' begin real_size = type.sub.to_i i = get_uint arg raise ValueOutOfBounds, arg unless i >= 0 && i < 2**real_size Utils.zpad_int i rescue EncodingError raise ValueOutOfBounds, arg end when 'bool' raise ArgumentError, "arg is not bool: #{arg}" unless arg.instance_of?(TrueClass) || arg.instance_of?(FalseClass) Utils.zpad_int(arg ? 1 : 0) when 'int' begin real_size = type.sub.to_i i = get_int arg raise ValueOutOfBounds, arg unless i >= -2**(real_size-1) && i < 2**(real_size-1) Utils.zpad_int(i % 2**type.sub.to_i) rescue EncodingError raise ValueOutOfBounds, arg end when 'ufixed' high, low = type.sub.split('x').map(&:to_i) raise ValueOutOfBounds, arg unless arg >= 0 && arg < 2**high Utils.zpad_int((arg * 2**low).to_i) when 'fixed' high, low = type.sub.split('x').map(&:to_i) raise ValueOutOfBounds, arg unless arg >= -2**(high - 1) && arg < 2**(high - 1) i = (arg * 2**low).to_i Utils.zpad_int(i % 2**(high+low)) when 'string' if arg.encoding.name == 'UTF-8' arg = arg.b else begin arg.unpack('U*') rescue ArgumentError raise ValueError, "string must be UTF-8 encoded" end end if type.sub.empty? # variable length type raise ValueOutOfBounds, "Integer invalid or out of range: #{arg.size}" if arg.size >= TT256 size = Utils.zpad_int arg.size value = Utils.rpad arg, BYTE_ZERO, Utils.ceil32(arg.size) "#{size}#{value}" else # fixed length type sub = type.sub.to_i raise ValueOutOfBounds, "invalid string length #{sub}" if arg.size > sub raise ValueOutOfBounds, "invalid string length #{sub}" if sub < 0 || sub > 32 Utils.rpad(arg, BYTE_ZERO, 32) end when 'bytes' raise EncodingError, "Expecting string: #{arg}" unless arg.instance_of?(String) arg = arg.b if type.sub.empty? # variable length type raise ValueOutOfBounds, "Integer invalid or out of range: #{arg.size}" if arg.size >= TT256 size = Utils.zpad_int arg.size value = Utils.rpad arg, BYTE_ZERO, Utils.ceil32(arg.size) "#{size}#{value}" else # fixed length type sub = type.sub.to_i raise ValueOutOfBounds, "invalid bytes length #{sub}" if arg.size > sub raise ValueOutOfBounds, "invalid bytes length #{sub}" if sub < 0 || sub > 32 Utils.rpad(arg, BYTE_ZERO, 32) end when 'hash' size = type.sub.to_i raise EncodingError, "too long: #{arg}" unless size > 0 && size <= 32 if arg.is_a?(Integer) Utils.zpad_int(arg) elsif arg.size == size Utils.zpad arg, 32 elsif arg.size == size * 2 Utils.zpad_hex arg else raise EncodingError, "Could not parse hash: #{arg}" end when 'address' if arg.is_a?(Integer) Utils.zpad_int arg elsif arg.size == 20 Utils.zpad arg, 32 elsif arg.size == 40 Utils.zpad_hex arg elsif arg.size == 42 && arg[0,2] == '0x' Utils.zpad_hex arg[2..-1] else raise EncodingError, "Could not parse address: #{arg}" end else raise EncodingError, "Unhandled type: #{type.base} #{type.sub}" end end ## # Decodes multiple arguments using the head/tail mechanism. # def decode_abi(types, data) parsed_types = types.map {|t| Type.parse(t) } outputs = [nil] * types.size start_positions = [nil] * types.size + [data.size] # TODO: refactor, a reverse iteration will be better pos = 0 parsed_types.each_with_index do |t, i| # If a type is static, grab the data directly, otherwise record its # start position if t.dynamic? start_positions[i] = Utils.big_endian_to_int(data[pos, 32]) j = i - 1 while j >= 0 && start_positions[j].nil? start_positions[j] = start_positions[i] j -= 1 end pos += 32 else outputs[i] = data[pos, t.size] pos += t.size end end # We add a start position equal to the length of the entire data for # convenience. j = types.size - 1 while j >= 0 && start_positions[j].nil? start_positions[j] = start_positions[types.size] j -= 1 end # raise DecodingError, "Not enough data for head" unless pos <= data.size parsed_types.each_with_index do |t, i| if t.dynamic? offset, next_offset = start_positions[i, 2] outputs[i] = data[offset...next_offset] end end parsed_types.zip(outputs).map {|(type, out)| decode_type(type, out) } end alias :decode :decode_abi def decode_typed_data type_name, data decode_primitive_type Type.parse(type_name), data end def decode_type(type, arg) if %w(string bytes).include?(type.base) && type.sub.empty? l = Utils.big_endian_to_int arg[0,32] data = arg[32..-1] data[0, l] elsif type.dynamic? l = Utils.big_endian_to_int arg[0,32] subtype = type.subtype if subtype.dynamic? raise DecodingError, "Not enough data for head" unless arg.size >= 32 + 32*l start_positions = (1..l).map {|i| Utils.big_endian_to_int arg[32*i, 32] } start_positions.push arg.size outputs = (0...l).map {|i| arg[start_positions[i]...start_positions[i+1]] } outputs.map {|out| decode_type(subtype, out) } else (0...l).map {|i| decode_type(subtype, arg[32 + subtype.size*i, subtype.size]) } end elsif !type.dims.empty? # static-sized arrays l = type.dims.last subtype = type.subtype (0...l).map {|i| decode_type(subtype, arg[subtype.size*i, subtype.size]) } else decode_primitive_type type, arg end end def decode_primitive_type(type, data) case type.base when 'address' Utils.encode_hex data[12..-1] when 'string', 'bytes' if type.sub.empty? # dynamic if data.length==32 data[0..32] else size = Utils.big_endian_to_int data[0,32] data[32..-1][0,size] end else # fixed data[0, type.sub.to_i] end when 'hash' data[(32 - type.sub.to_i), type.sub.to_i] when 'uint' Utils.big_endian_to_int data when 'int' u = Utils.big_endian_to_int data u >= 2**(type.sub.to_i-1) ? (u - 2**type.sub.to_i) : u when 'ufixed' high, low = type.sub.split('x').map(&:to_i) Utils.big_endian_to_int(data) * 1.0 / 2**low when 'fixed' high, low = type.sub.split('x').map(&:to_i) u = Utils.big_endian_to_int data i = u >= 2**(high+low-1) ? (u - 2**(high+low)) : u i * 1.0 / 2**low when 'bool' data[-1] == BYTE_ONE else raise DecodingError, "Unknown primitive type: #{type.base}" end end private def get_uint(n) case n when Integer raise EncodingError, "Number out of range: #{n}" if n > UINT_MAX || n < UINT_MIN n when String i = if n.size == 40 Utils.decode_hex(n) elsif n.size <= 32 n else raise EncodingError, "String too long: #{n}" end i = Utils.big_endian_to_int i raise EncodingError, "Number out of range: #{i}" if i > UINT_MAX || i < UINT_MIN i when true 1 when false, nil 0 else raise EncodingError, "Cannot decode uint: #{n}" end end def get_int(n) case n when Integer raise EncodingError, "Number out of range: #{n}" if n > INT_MAX || n < INT_MIN n when String i = if n.size == 40 Utils.decode_hex(n) elsif n.size <= 32 n else raise EncodingError, "String too long: #{n}" end i = Utils.big_endian_to_int i i = i > INT_MAX ? (i-TT256) : i raise EncodingError, "Number out of range: #{i}" if i > INT_MAX || i < INT_MIN i when true 1 when false, nil 0 else raise EncodingError, "Cannot decode int: #{n}" end end end end
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
izetex/web3-eth
https://github.com/izetex/web3-eth/blob/11f02a0683f30bca5a2e9be90824378394dcdf9a/lib/web3/eth/abi/constant.rb
lib/web3/eth/abi/constant.rb
# -*- encoding : ascii-8bit -*- module Web3::Eth::Abi module Constant BYTE_EMPTY = "".freeze BYTE_ZERO = "\x00".freeze BYTE_ONE = "\x01".freeze TT32 = 2**32 TT40 = 2**40 TT160 = 2**160 TT256 = 2**256 TT64M1 = 2**64 - 1 UINT_MAX = 2**256 - 1 UINT_MIN = 0 INT_MAX = 2**255 - 1 INT_MIN = -2**255 HASH_ZERO = ("\x00"*32).freeze PUBKEY_ZERO = ("\x00"*32).freeze PRIVKEY_ZERO = ("\x00"*32).freeze PRIVKEY_ZERO_HEX = ('0'*64).freeze CONTRACT_CODE_SIZE_LIMIT = 0x6000 end end
ruby
MIT
11f02a0683f30bca5a2e9be90824378394dcdf9a
2026-01-04T17:48:36.828969Z
false
bibendi/schked
https://github.com/bibendi/schked/blob/860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58/spec/rails_helper.rb
spec/rails_helper.rb
# frozen_string_literal: true ENV["RAILS_ENV"] = "test" require "bundler/setup" require "logger" require "combustion" Combustion.initialize! require "spec_helper"
ruby
MIT
860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58
2026-01-04T17:48:41.942530Z
false
bibendi/schked
https://github.com/bibendi/schked/blob/860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true ENV["RACK_ENV"] = "test" require "bundler/setup" require "schked" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" config.expect_with :rspec do |c| c.syntax = :expect end config.filter_run_when_matching :focus redis = RedisClient.new(url: ENV["REDIS_URL"]) config.before(:each) do redis.call("FLUSHDB") end end
ruby
MIT
860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58
2026-01-04T17:48:41.942530Z
false
bibendi/schked
https://github.com/bibendi/schked/blob/860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58/spec/rails/railtie_spec.rb
spec/rails/railtie_spec.rb
# frozen_string_literal: true require "rails_helper" describe Schked::Railtie do describe "schked.config" do let(:config) { Schked::Config.new } before do allow(Schked).to receive(:config).and_return(config) end context "when by default root schedule doesn't exist" do it { expect(config.paths).to be_empty } end context "when a root schedule exists" do let(:schedule_path) { Rails.root.join("config/schedule.rb").to_s } let(:initializer) { Schked::Railtie::PathsConfig } before do File.write(schedule_path, "") end after do File.unlink(schedule_path) config.paths.delete(schedule_path) end it "adds to paths" do initializer.call(double("app", root: Rails.root)) expect(config.paths).to match_array([schedule_path]) end context "when path is already added" do before { config.paths << schedule_path } it "does not add it twice" do initializer.call(double("app", root: Rails.root)) expect(config.paths).to match_array([schedule_path]) end end context "when passed do_not_load_root_schedule config option" do before { config.do_not_load_root_schedule = true } it "doesn't add root schedule to paths" do expect(config.paths).to be_empty end end end end end
ruby
MIT
860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58
2026-01-04T17:48:41.942530Z
false
bibendi/schked
https://github.com/bibendi/schked/blob/860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58/spec/lib/schked_spec.rb
spec/lib/schked_spec.rb
# frozen_string_literal: true require "spec_helper" describe Schked do it { expect(described_class.config).to be_a(Schked::Config) } it { expect(described_class.worker).to be_a(Schked::Worker) } end
ruby
MIT
860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58
2026-01-04T17:48:41.942530Z
false
bibendi/schked
https://github.com/bibendi/schked/blob/860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58/spec/lib/schked/worker_spec.rb
spec/lib/schked/worker_spec.rb
# frozen_string_literal: true require "spec_helper" require "tempfile" describe Schked::Worker do subject(:worker) { described_class.new(config: config) } let(:config) { Schked::Config.new } let(:logger) { instance_double(Logger).as_null_object } before do @taoe = Thread.abort_on_exception Thread.abort_on_exception = false config.logger = logger end after do Thread.abort_on_exception = @taoe worker.stop end describe "schedule" do it "loads schedules" do Tempfile.open("foo") do |foo| foo.write "every('100d') { puts 'foo' }" foo.flush config.paths << foo.path Tempfile.open("bar") do |bar| bar.write "every('200d') { puts 'bar' }" bar.flush config.paths << bar.path config.paths << bar.path # add duplicate path to ensure it will be ignored" expect(worker.schedule).to eq "every('100d') { puts 'foo' }\nevery('200d') { puts 'bar' }" end end end end describe "start" do it "starts rufus scheduler" do expect_any_instance_of(Rufus::Scheduler).to receive(:join) expect(Schked::RedisLocker).not_to receive(:new) expect_any_instance_of(described_class).not_to receive(:define_extend_lock) worker.wait end end describe "callbacks" do specify do counter = 0 config.register_callback(:on_error) { counter += 1 } expect_any_instance_of(Schked::Worker) .to receive(:schedule) .and_return("self.in('0s', as: :test_task) { raise 'Boom' }") worker sleep 0.5 expect(counter).to eq 1 expect(logger).to have_received(:info).with(/Started task: test_task/) expect(logger).to have_received(:fatal).with(/Task test_task failed with error: Boom/) expect(logger).to have_received(:error) expect(logger).to have_received(:info).with(/Finished task: test_task/) end context "when there are no registered callbacks" do specify do allow_any_instance_of(Rufus::Scheduler).to receive(:logger).and_return(logger) expect_any_instance_of(Schked::Worker) .to receive(:schedule) .and_return("self.in('0s', as: :test_task) { logger.info('inside job') }") expect(logger).to receive(:info).with(/Started task: test_task/).ordered expect(logger).to receive(:info).with(/inside job/).ordered expect(logger).to receive(:info).with(/Finished task: test_task/).ordered worker sleep 0.5 end end context "when there are registered around_job callbacks" do specify "single callback" do counter = 0 config.register_callback(:around_job) do |_job, &block| logger.info("callback before") counter += 1 block.call counter += 1 logger.info("callback after") end allow_any_instance_of(Rufus::Scheduler).to receive(:logger).and_return(logger) expect_any_instance_of(Schked::Worker) .to receive(:schedule) .and_return("self.in('0s', as: :test_task) { logger.info('inside job') }") expect(logger).to receive(:info).with(/Started task: test_task/).ordered expect(logger).to receive(:info).with(/callback before/).ordered expect(logger).to receive(:info).with(/inside job/).ordered expect(logger).to receive(:info).with(/callback after/).ordered expect(logger).to receive(:info).with(/Finished task: test_task/).ordered worker sleep 0.5 expect(counter).to eq 2 end specify "multiple callbacks" do counter = 0 config.register_callback(:around_job) do |_job, &block| logger.info("callback 1 before") counter += 1 block.call counter += 1 logger.info("callback 1 after") end config.register_callback(:around_job) do |_job, &block| logger.info("callback 2 before") counter += 1 block.call counter += 1 logger.info("callback 2 after") end allow_any_instance_of(Rufus::Scheduler).to receive(:logger).and_return(logger) expect_any_instance_of(Schked::Worker) .to receive(:schedule) .and_return("self.in('0s', as: :test_task) { logger.info('inside job') }") expect(logger).to receive(:info).with(/Started task: test_task/).ordered expect(logger).to receive(:info).with(/callback 1 before/).ordered expect(logger).to receive(:info).with(/callback 2 before/).ordered expect(logger).to receive(:info).with(/inside job/).ordered expect(logger).to receive(:info).with(/callback 2 after/).ordered expect(logger).to receive(:info).with(/callback 1 after/).ordered expect(logger).to receive(:info).with(/Finished task: test_task/).ordered worker sleep 0.5 expect(counter).to eq 4 end end context "when there are multiple around_job callbacks" do it "persists callbacks between jobs" do counter = 0 config.register_callback(:around_job) do |job, &block| logger.info("callback before - #{job.opts[:as]}") counter += 1 block.call counter += 1 logger.info("callback after - #{job.opts[:as]}") end allow_any_instance_of(Rufus::Scheduler).to receive(:logger).and_return(logger) expect_any_instance_of(Schked::Worker) .to receive(:schedule) .and_return( "self.in('0s', as: :test_task_1) { logger.info('inside job 1') };" \ "self.in('0.1s', as: :test_task_2) { logger.info('inside job 2') }" ) expect(logger).to receive(:info).with(/Started task: test_task_1/).ordered expect(logger).to receive(:info).with(/callback before - test_task_1/).ordered expect(logger).to receive(:info).with(/inside job 1/).ordered expect(logger).to receive(:info).with(/callback after - test_task_1/).ordered expect(logger).to receive(:info).with(/Finished task: test_task_1/).ordered expect(logger).to receive(:info).with(/Started task: test_task_2/).ordered expect(logger).to receive(:info).with(/callback before - test_task_2/).ordered expect(logger).to receive(:info).with(/inside job 2/).ordered expect(logger).to receive(:info).with(/callback after - test_task_2/).ordered expect(logger).to receive(:info).with(/Finished task: test_task_2/).ordered worker sleep 0.5 expect(counter).to eq 4 end end end describe "when is not standalone" do let(:config) { Schked::Config.new.tap { |x| x.standalone = false } } it "starts rufus scheduler" do expect_any_instance_of(Rufus::Scheduler).to receive(:join) expect(Schked::RedisLocker).to receive(:new).and_call_original expect_any_instance_of(described_class).to receive(:define_extend_lock).and_call_original worker.wait end end end
ruby
MIT
860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58
2026-01-04T17:48:41.942530Z
false
bibendi/schked
https://github.com/bibendi/schked/blob/860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58/spec/lib/schked/redis_locker_spec.rb
spec/lib/schked/redis_locker_spec.rb
# frozen_string_literal: true require "spec_helper" describe Schked::RedisLocker do let(:redis_conf) { {url: ENV["REDIS_URL"]} } subject { described_class.new(redis_conf) } describe "#lock" do it "locks" do expect(subject.lock).to be true end context "when is locked by someone else" do before do described_class.new(redis_conf).lock end it "fails to lock" do expect(subject.lock).to be false end end context "when is locked by us" do before do subject.lock end it "keeps locking" do expect(subject.lock).to be true end end end describe "#unlock" do context "when is locked by us" do before do subject.lock end it "unlocks" do expect { subject.unlock }.to change { subject.valid_lock? }.from(true).to(false) end end context "when is locked by someone else" do before do described_class.new(redis_conf).lock end it "fails to unlock" do expect { subject.unlock }.not_to change { subject.valid_lock? }.from(false) end end end describe "#extend_lock" do subject { described_class.new(redis_conf, lock_ttl: 1000) } context "when is locked by us" do it "extends lock" do subject.lock sleep 0.5 expect(subject.extend_lock).to be true sleep 0.7 expect(subject.valid_lock?).to be true sleep 0.5 expect(subject.valid_lock?).to be false end end context "when is locked by someone else" do before do described_class.new(redis_conf, lock_ttl: 1000).lock end it "fails to extend" do expect(subject.extend_lock).to be false end end end end
ruby
MIT
860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58
2026-01-04T17:48:41.942530Z
false
bibendi/schked
https://github.com/bibendi/schked/blob/860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58/spec/lib/schked/config_spec.rb
spec/lib/schked/config_spec.rb
# frozen_string_literal: true require "spec_helper" describe Schked::Config do subject(:config) { described_class.new } describe "#paths" do it "appends files" do config.paths << "foo" config.paths << "bar" expect(config.paths).to eq %w[foo bar] end end it { expect(config.logger).to be_a(Logger) } it { expect(config).to be_standalone } context "when RACK_ENV=production" do it "is not standalone" do old_val = ENV["RACK_ENV"] ENV["RACK_ENV"] = "production" expect(config).not_to be_standalone ENV["RACK_ENV"] = old_val end end end
ruby
MIT
860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58
2026-01-04T17:48:41.942530Z
false
bibendi/schked
https://github.com/bibendi/schked/blob/860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58/lib/schked.rb
lib/schked.rb
# frozen_string_literal: true require "connection_pool" require "redlock" require "schked/version" require "schked/config" require "schked/worker" require "schked/redis_locker" require "schked/redis_client_factory" require "schked/railtie" if defined?(Rails) module Schked module_function def config @config ||= Config.new end def worker @worker ||= Worker.new(config: config) end end
ruby
MIT
860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58
2026-01-04T17:48:41.942530Z
false
bibendi/schked
https://github.com/bibendi/schked/blob/860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58/lib/schked/version.rb
lib/schked/version.rb
# frozen_string_literal: true module Schked VERSION = "1.3.1" end
ruby
MIT
860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58
2026-01-04T17:48:41.942530Z
false
bibendi/schked
https://github.com/bibendi/schked/blob/860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58/lib/schked/redis_locker.rb
lib/schked/redis_locker.rb
# frozen_string_literal: true module Schked class RedisLocker attr_reader :lock_manager, :lock_id, :lock_ttl, :logger LOCK_KEY = "schked:redis_locker" LOCK_TTL = 60_000 # ms def initialize(redis_conf, lock_ttl: LOCK_TTL, logger: Logger.new($stdout)) @lock_manager = Redlock::Client.new([redis_client(redis_conf)], retry_count: 0) @lock_ttl = lock_ttl @logger = logger end def lock valid_lock? || !!try_lock rescue => e logger.error("Failed to acquire a lock with error: #{e.message}") false end def unlock lock_manager.unlock(lock_id) if valid_lock? rescue => e logger.error("Failed to release the lock with error: #{e.message}") false end def extend_lock return false unless valid_lock? @lock_id = lock_manager.lock(LOCK_KEY, lock_ttl, extend: lock_id, extend_only_if_locked: true) !!@lock_id rescue => e logger.error("Failed to extend the lock with error: #{e.message}") false end def valid_lock? return false unless lock_id lock_manager.valid_lock?(lock_id) end private def redis_client(redis_conf) if Gem::Version.new(Redlock::VERSION) >= Gem::Version.new("2.0.0") ConnectionPool::Wrapper.new { RedisClientFactory.build(redis_conf) } else ConnectionPool::Wrapper.new { Redis.new(**redis_conf) } end end def try_lock @lock_id = lock_manager.lock(LOCK_KEY, lock_ttl) end end end
ruby
MIT
860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58
2026-01-04T17:48:41.942530Z
false
bibendi/schked
https://github.com/bibendi/schked/blob/860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58/lib/schked/railtie.rb
lib/schked/railtie.rb
# frozen_string_literal: true require "rails/railtie" module Schked class Railtie < Rails::Railtie class PathsConfig def self.call(app) return if Schked.config.do_not_load_root_schedule? root_schedule = app.root.join("config", "schedule.rb") if root_schedule.exist? path = root_schedule.to_s Schked.config.paths << path unless Schked.config.paths.include?(path) end end end initializer("schked.paths", &PathsConfig.method(:call)) config.to_prepare do Schked.config.logger = ::Rails.logger unless Schked.config.logger? end end end
ruby
MIT
860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58
2026-01-04T17:48:41.942530Z
false
bibendi/schked
https://github.com/bibendi/schked/blob/860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58/lib/schked/redis_client_factory.rb
lib/schked/redis_client_factory.rb
# frozen_string_literal: true require "redis-client" module Schked module RedisClientFactory def self.build(options) unless options.key?(:reconnect_attempts) options[:reconnect_attempts] = 3 end if options.key?(:sentinels) if (url = options.delete(:url)) uri = URI.parse(url) if !options.key?(:name) && uri.host options[:name] = uri.host end if !options.key?(:password) && uri.password && !uri.password.empty? options[:password] = uri.password end if !options.key?(:username) && uri.user && !uri.user.empty? options[:username] = uri.user end end RedisClient.sentinel(**options).new_client else RedisClient.config(**options).new_client end end end end
ruby
MIT
860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58
2026-01-04T17:48:41.942530Z
false
bibendi/schked
https://github.com/bibendi/schked/blob/860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58/lib/schked/cli.rb
lib/schked/cli.rb
# frozen_string_literal: true require "thor" require "shellwords" module Schked class CLI < Thor def self.start(argv) if File.exist?(".schked") argv += File .read(".schked") .split("\n") .join(" ") .strip .shellsplit end super(argv) end def self.exit_on_failure? true end default_command :start desc "start", "Start scheduler" option :require, type: :array def start load_requires Schked.worker.wait end desc "show", "Output schedule to stdout" option :require, type: :array def show load_requires puts "=====" puts Schked.worker.schedule puts "=====" end private def load_requires options[:require].each { |file| load(File.join(Dir.pwd, file)) } if options[:require]&.any? # We have to load Schked at here, because of Rails and our railtie. require "schked" end end end
ruby
MIT
860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58
2026-01-04T17:48:41.942530Z
false
bibendi/schked
https://github.com/bibendi/schked/blob/860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58/lib/schked/worker.rb
lib/schked/worker.rb
# frozen_string_literal: true require "rufus/scheduler" module Schked class Worker def initialize(config:) @config = config @locker = RedisLocker.new(config.redis, lock_ttl: 40_000, logger: config.logger) unless config.standalone? @scheduler = Rufus::Scheduler.new(trigger_lock: locker) watch_signals define_callbacks define_extend_lock unless config.standalone? load_schedule end def job(as) scheduler.jobs.find { |job| job.opts[:as] == as } end def pause scheduler.pause end def wait scheduler.join end def stop scheduler.stop end def schedule config .paths .map { |path| File.expand_path(path) } .uniq .map { |path| File.read(path) } .join("\n") end private attr_reader :config, :scheduler, :locker def define_callbacks cfg = config scheduler.define_singleton_method(:extract_job_name) do |job| if job job.opts[:as] || job.job_id else "unknown" end end scheduler.define_singleton_method(:on_error) do |job, error| cfg.logger.fatal("Task #{extract_job_name(job)} failed with error: #{error.message}") cfg.logger.error(error.backtrace.join("\n")) if error.backtrace cfg.fire_callback(:on_error, job, error) end scheduler.define_singleton_method(:on_pre_trigger) do |job, time| cfg.logger.info("Started task: #{extract_job_name(job)}") cfg.fire_callback(:before_start, job, time) end scheduler.define_singleton_method(:around_trigger) do |job, &block| cfg.fire_around_callback(:around_job, job, &block) end scheduler.define_singleton_method(:on_post_trigger) do |job, time| cfg.logger.info("Finished task: #{extract_job_name(job)}") cfg.fire_callback(:after_finish, job, time) end end def watch_signals Signal.trap("TERM") do config.logger.info("Going to shut down...") @shutdown = true end Signal.trap("INT") do config.logger.info("Going to shut down...") @shutdown = true end Thread.new do loop do scheduler.shutdown(wait: 5) if @shutdown sleep 1 end end end def define_extend_lock scheduler.every("10s", as: "Schked::Worker#extend_lock", timeout: "5s", overlap: false) do locker.extend_lock end end def load_schedule scheduler.instance_eval(schedule) end end end
ruby
MIT
860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58
2026-01-04T17:48:41.942530Z
false
bibendi/schked
https://github.com/bibendi/schked/blob/860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58/lib/schked/config.rb
lib/schked/config.rb
# frozen_string_literal: true require "logger" module Schked class Config attr_writer :logger, :do_not_load_root_schedule, :redis, :standalone def paths @paths ||= [] end def logger? !!@logger end def logger @logger ||= Logger.new($stdout).tap { |l| l.level = Logger::INFO } end def do_not_load_root_schedule? !!@do_not_load_root_schedule end def register_callback(name, &block) callbacks[name] << block end def fire_callback(name, *args) callbacks[name].each do |callback| callback.call(*args) end end def fire_around_callback(name, job, calls = callbacks[name], &block) return yield if calls.none? calls.first.call(job) do calls = calls.drop(1) if calls.any? fire_around_callback(name, job, calls, &block) else yield end end end def redis @redis ||= {url: ENV.fetch("REDIS_URL", "redis://127.0.0.1:6379")} end def redis_servers=(val) val = val.first if val.is_a?(String) self.redis = {url: val} elsif val.respond_to?(:_client) conf = val._client.config self.redis = {url: conf.server_url, username: conf.username, password: conf.password} else raise ArgumentError, "Schked `redis_servers=` config option is deprecated. Please use `redis=` with a Hash" end warn "🔥 Schked `redis_servers=` config option is deprecated. Please use `redis=` with a Hash. Called from #{caller(1..1).first}" end def standalone? @standalone = ENV["RAILS_ENV"] == "test" || ENV["RACK_ENV"] == "test" if @standalone.nil? !!@standalone end private def callbacks @callbacks ||= Hash.new { |hsh, key| hsh[key] = [] } end end end
ruby
MIT
860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58
2026-01-04T17:48:41.942530Z
false
bibendi/schked
https://github.com/bibendi/schked/blob/860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58/.danger/merge_commits.rb
.danger/merge_commits.rb
# frozen_string_literal: true # Check for merge commits if git.commits.any? { |c| c.message =~ /^Merge branch 'master'/ } warn "Please rebase to get rid of the merge commits in this PR" end
ruby
MIT
860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58
2026-01-04T17:48:41.942530Z
false
bibendi/schked
https://github.com/bibendi/schked/blob/860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58/.danger/missing_tests.rb
.danger/missing_tests.rb
# frozen_string_literal: true # Check that there are both app and test code changes for the main app changed_files = CHANGED_FILES.select { |path| path =~ /^(exe|lib)/ } if changed_files.any? changed_test_files = CHANGED_FILES.select { |path| path =~ /^spec/ } if changed_test_files.empty? warn "Are you sure we don't need to add/update tests for the main app?" end end
ruby
MIT
860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58
2026-01-04T17:48:41.942530Z
false
bibendi/schked
https://github.com/bibendi/schked/blob/860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58/.danger/missing_labels.rb
.danger/missing_labels.rb
# frozen_string_literal: true # Check for labels presence (ignoring "wip" label) non_wip_labels = github.pr_labels - %w[wip] failure "Please add labels to this PR" if non_wip_labels.empty?
ruby
MIT
860cd20b61fa5a98eb098d7cd0e95dd4f55c5f58
2026-01-04T17:48:41.942530Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/decorators/summary_decorator.rb
app/decorators/summary_decorator.rb
class SummaryDecorator < Draper::Decorator delegate_all include DecorateSerializer attr :id, :title, :description, :path # rubocop:disable Lint/DuplicateMethods def id object._id.to_s end # rubocop:enable Lint/DuplicateMethods def path h.summary_path(self) end def description_html return '' unless object.description safe_html = h.html_escape(object.description.to_s) h.simple_format(safe_html) rescue StandardError => e Rails.logger.error "#{e.inspect} - #{e.backtrace}" object.description.to_s end def messages MessageDecorator.decorate_collection(object.sorted_messages) end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/decorators/user_decorator.rb
app/decorators/user_decorator.rb
class UserDecorator < Draper::Decorator delegate_all include DecorateSerializer attr :id, :uid, :name, :display_name, :avatar_url, :is_admin, :url # rubocop:disable Lint/DuplicateMethods def id object._id.to_s end def display_name name_or_display_name end # rubocop:enable Lint/DuplicateMethods def url h.user_path(object) end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/decorators/message_decorator.rb
app/decorators/message_decorator.rb
require 'gemoji' class MessageDecorator < Draper::Decorator delegate_all include DecorateSerializer attr :id, :username, :channel, :channel_name, :text, :format_text, :avatar_url, :me?, :created_at, :created_time, :permalink, :attachment_items, :is_bot, :reactions # rubocop:disable Lint/DuplicateMethods def id object._id.to_s end # rubocop:enable Lint/DuplicateMethods def channel_name object.channel_name || object.channel end def created_time I18n.l(object.created_at) end # rubocop:disable Naming/PredicateName def is_bot return true unless object.owner !!object.owner.try(:is_bot) end # rubocop:enable Naming/PredicateName def avatar_url icons = object['icons'] return object.owner.try(:avatar_url) unless icons return icons.values.first unless icons['emoji'] return icons['image_64'] if icons['image_64'] name = icons['emoji'].gsub(':', '') self.class.emoji[name] end def permalink "https://#{ENV.fetch('SLACK_TEAM_NAME', nil)}.slack.com/archives/#{channel}/p#{object['ts'].to_s.gsub('.', '')}" end def format_text @format_text ||= self.class.processor.call(object.text, self.class.context)[:output].to_s.html_safe end def attachment_items @attachment_items ||= begin items = [] items += (object['files'] || []).map do |file| convert_file(file) end items += (object['attachments'] || []).map do |attachment| convert_attachment(attachment) end items.compact end end def convert_file(file) { fallback: file['name'], title: file['title'], title_link: file['thumb_360'] || file['url_private'] } end def convert_attachment(attachment) case attachment['service_name'] when 'twitter' attachment else # 未知のサービスすべて(URL展開など) if attachment[:title] || attachment[:text] attachment elsif attachment[:image_url] attachment[:service_name] = 'togelack-image' attachment end end end def image object['file'] if object['file'] && object['file']['mimetype'].include?('image') end def reactions return [] if object['reactions'].blank? object['reactions'].map do |reaction| name = reaction['name'].to_s { name: name, count: reaction['count'].to_i, emoji_url: self.class.emoji[name], emoji_raw: Emoji.find_by_alias(name)&.raw }.with_indifferent_access end end class << self def processor @processor ||= begin processor = SlackMarkdown::Processor.new( asset_root: '/assets', cushion_link: ENV.fetch('CUSHION_LINK', nil) ) processor.filters.push(::PipelineFilters::ReplaceEmojiFilter) processor.filters.push(::PipelineFilters::AddRelToLinkFilter) processor end end def context @context ||= { original_emoji_set: emoji.list, on_slack_user_id: method(:on_slack_user_id), on_slack_user_name: method(:on_slack_user_name), on_slack_channel_id: method(:on_slack_channel_id) } end def on_slack_user_id(uid) Rails.cache.fetch("user_data_#{uid}", expires_in: 1.hour) do user = User.find_or_fetch(slack_client, uid) user ? { text: user.name, url: "/@#{user.name}" } : nil end end def on_slack_user_name(name) Rails.cache.fetch("user_data_#{name}", expires_in: 1.hour) do user = User.where(name: name).first user ? { text: user.name, url: "/@#{user.name}" } : nil end end def on_slack_channel_id(uid) Rails.cache.fetch("channel_data_#{uid}", expires_in: 1.hour) do resp = slack_client.conversations_info(channel: uid) if resp['ok'] name = resp['channel']['name'] { text: name, url: "https://#{ENV.fetch('SLACK_TEAM_NAME', nil)}.slack.com/archives/#{uid}" } else { text: uid, url: '#' } end end end def emoji @emoji ||= SlackSupport::Emoji.new(slack_client) end def slack_client @slack_client ||= SlackSupport::Client.create end end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/helpers/summaries_helper.rb
app/helpers/summaries_helper.rb
module SummariesHelper def messages_json(summary) summary.sorted_messages.to_a.map { |n| MessageDecorator.new(n) }.to_json(root: false) end def attachment_text_format(text) MessageDecorator.new(OpenStruct.new(text: text)).format_text end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/controllers/summaries_controller.rb
app/controllers/summaries_controller.rb
class SummariesController < ApplicationController before_action :do_check_login, only: [:new, :create, :edit, :update, :destroy] before_action :set_summary, only: [:show, :edit, :update, :destroy] def index page = (params[:page] || 1).to_i source = Summary.newest.page(page) @summaries = SummaryDecorator.decorate_collection(source) end def list page = (params[:page] || 1).to_i source = Summary.newest.page(page).per(25) source = source.match_text(params[:keyword]) if params[:keyword] @summaries = SummaryDecorator.decorate_collection(source) end def show end def new @summary = SummaryDecorator.decorate(Summary.new) end def edit end def create @summary = Summary.new(summary_params) raise 'error' unless @summary.save if ENV['SLACK_CHANNEL'].present? EM.defer do client = SlackSupport::Client.create poster = SlackSupport::Poster.new(client, ENV['SLACK_CHANNEL']) poster.post(@current_user, summary_url(@summary), @summary.title, @summary.description) end end render json: { result: @summary.decorate }, root: nil end def update raise 'permission error' unless @summary.user == @current_user raise 'error' unless @summary.update(summary_params) render json: { result: @summary.decorate }, root: nil end def destroy raise 'permission error' unless @summary.user == @current_user || @current_user.admin? @summary.destroy redirect_to '/' end private def set_summary @summary = Summary.find(params[:id]).decorate end def summary_params Rails.logger.info '---------' Rails.logger.info params.inspect Rails.logger.info '---------' n = params.permit(:title, :description, messages: []) n[:user] = @current_user n[:messages] = n[:messages].uniq.reject(&:empty?).map { |id| Message.find(id) } n end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/controllers/users_controller.rb
app/controllers/users_controller.rb
class UsersController < ApplicationController before_action :set_user def show page = (params[:page] || 1).to_i source = @user.summaries.newest.page(page) @summaries = SummaryDecorator.decorate_collection(source) end private def set_user @user = User.find_by(name: params[:name]) rescue StandardError => e Rails.logger.debug e.backtrace.inspect raise e end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/controllers/proxies_controller.rb
app/controllers/proxies_controller.rb
require 'net/http' require 'digest/md5' class ProxiesController < ApplicationController def show raise 'invalid' unless params[:url] data = fetch(params[:url]) raise '404' unless data send_data data[:body], type: data[:content_type], disposition: 'inline' end IMAGE_MAX_SIZE = 1024 IMAGE_CONTENT_TYPE = %w[ image/gif image/jpeg image/x-png image/png ].freeze private def fetch(url) Rails.cache.fetch("proxies#show__#{Digest::MD5.hexdigest(url)}", expires_in: 1.hour) do url = URI.parse(url) resp = Net::HTTP.get_response(url) if resp.code =~ /\A2\d+\z/ && resp.size < IMAGE_MAX_SIZE && IMAGE_CONTENT_TYPE.include?(resp.content_type) { content_type: resp.content_type, body: resp.body } end end end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/controllers/sessions_controller.rb
app/controllers/sessions_controller.rb
class SessionsController < ApplicationController skip_before_action :require_login_in_private # GET /auth/slack/callback def create auth = request.env['omniauth.auth'] unless valid_auth?(auth) redirect_to '/' return end user = create_or_update_user(auth) session[:user_id] = user.uid session[:token] = auth.credentials.token redirect_to '/' end # DELETE /logout def destroy session[:user_id] = nil session[:token] = nil redirect_to '/' end private def valid_auth?(auth) return false unless auth return false unless auth['provider'] == 'slack' return false unless auth['info']['team_id'] == ENV['SLACK_TEAM_ID'] true end def create_or_update_user(auth) client = ::SlackSupport::Client.create user = ::User.fetch(client, auth['uid']) user.is_admin = auth.extra.user_info['user']['is_admin'] user.save! user end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/controllers/application_controller.rb
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :do_login, :assign_global_alert, :require_login_in_private private def assign_global_alert @global_alert = ENV['GLOBAL_ALERT'].to_s end def require_login_in_private redirect_to '/auth/slack' if ENV['PRIVATE_MODE'] == 'true' && !@current_user end def do_login return unless session['user_id'] @current_user = User.where(uid: session['user_id']).first session['user_id'] = nil unless @current_user end def do_check_login raise unless @current_user end rescue_from Exception, with: :render_500 unless Rails.env.development? rescue_from Mongoid::Errors::DocumentNotFound, with: :render_404 rescue_from ActionController::RoutingError, with: :render_404 def render_error(status, message = '') @status = status @message = message respond_to do |format| format.html { render '/errors/common', status: @status } format.json { render json: {}, status: @status, message: @message } end end def render_404 render_error(404, 'Not Found') end def render_500(e = nil) Rails.logger.error "#{e.message}\n#{e.backtrace.join("\n")}" if e render_error(500, 'Internal Server Error') end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/controllers/api/histories_controller.rb
app/controllers/api/histories_controller.rb
require 'slack' module API class HistoriesController < ApplicationController before_action :do_check_login # 暫定 # GET /api/histories.json?url=http://〜 def index client = SlackSupport::Client.create(session[:token]) chs = Services::CacheHistoryService.new(client) messages = chs.cache(params[:url]) render json: { result: MessageDecorator.decorate_collection(messages) }, root: nil end end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/models/message.rb
app/models/message.rb
class Message include Mongoid::Document include Mongoid::Attributes::Dynamic field :channel, type: String field :channel_name, type: String field :ts, type: String index({ channel: 1, ts: 1 }, { unique: true }) def username case self['username'] when nil owner.try(:name_or_display_name) when /<@[^|]+|([^>]+)>/ self['username'].match(/\|([^>]+)/)[1].to_s else self['username'] end end def owner return User.find_by(uid: self['user']) if self['user'] nil end def me? self['subtype'] == 'me_message' end def created_at Time.zone.at(ts.to_i) end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/models/summary.rb
app/models/summary.rb
class Summary include Mongoid::Document paginates_per 5 field :title, type: String field :description, type: String belongs_to :user has_and_belongs_to_many :messages scope :newest, -> { order(id: :desc) } validates :title, length: 1..64 validates :description, length: 0..1048 validates :messages, length: 1..1000 after_initialize :set_default_params def sorted_messages ms = messages.to_a message_ids.map do |id| ms.select { |n| n.id == id }.first end end def self.match_text(text) message_ids = Message.any_of({ text: /.*#{text}.*/ }).only(:_id).map do |v| { message_ids: v } end any_of({ title: /.*#{text}.*/ }, message_ids) end private def set_default_params self.title ||= '' self.description ||= '' end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/models/user.rb
app/models/user.rb
class User include Mongoid::Document field :uid, type: String field :name, type: String field :display_name, type: String field :avatar_url, type: String field :is_admin, type: Boolean field :is_bot, type: Boolean field :last_fetched_at, type: DateTime has_many :summaries, dependent: :restrict_with_exception index({ uid: 1 }, {}) index({ name: 1 }, {}) def name_or_display_name (display_name.presence || name) end def self.find_or_fetch(client, uid) user = where(uid: uid).first if user user.fetch(client) unless user.last_fetched_at && user.last_fetched_at > 24.hours.ago user else fetch(client, uid) end end def self.fetch(client, uid) raw = client.users_info(user: uid)['user'] return nil unless raw User.find_or_create_by(uid: raw['id']).update_by_raw(raw) end def fetch(client) raw = client.users_info(user: uid)['user'] return unless raw update_by_raw(raw) end def admin? !!is_admin end def to_param name end def update_by_raw(raw) update( name: raw['name'], display_name: raw['profile']['display_name'], avatar_url: raw['profile']['image_192'], is_admin: raw['is_admin'], is_bot: (raw['is_bot'] || raw['is_app_user']), last_fetched_at: Time.zone.now ) self end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/models/services/cache_history_service.rb
app/models/services/cache_history_service.rb
module Services class CacheHistoryService def initialize(client) @client = client @cache_users = {} @cache_bots = {} end def cache(url) archive_url = SlackSupport::ArchiveURL.new(url) raise 'invalid url' unless archive_url.valid? c_id, = detect_channel_id_and_name(archive_url) raise 'not found channels' unless c_id if archive_url.thread_ts fetch_replies(archive_url) else fetch_histories(archive_url).reverse end end private def resolver @resolver ||= SlackSupport::ChannelResolver.new(@client) end def detect_channel_id_and_name(archive_url) [ archive_url.channel, resolver.resolve_by_id(archive_url.channel) ] end def fetch_histories(archive_url) c_id, = detect_channel_id_and_name(archive_url) params = { channel: c_id, oldest: archive_url.ts, inclusive: true, limit: 30 } resp = @client.conversations_history(params)['messages'] resp ? resp.map { |n| convert_and_store_message(n, archive_url) } : [] end def fetch_replies(archive_url) c_id, = detect_channel_id_and_name(archive_url) params = { channel: c_id, ts: archive_url.thread_ts, oldest: archive_url.ts, inclusive: false, limit: 30 } resp = @client.conversations_replies(params)['messages'] resp ? resp.map { |n| convert_and_store_message(n, archive_url) } : [] end def convert_and_store_message(raw, archive_url) _, channel_name = detect_channel_id_and_name(archive_url) # bot raw['user'] = fetch_bot_user_id(raw['bot_id']) if !raw['user'] && raw['bot_id'] # user prefetch_user(raw['user']) if raw['user'] # message message = Message.find_or_initialize_by( channel: archive_url.channel, ts: raw['ts'] ) message['channel_name'] = channel_name raw.each { |k, v| message[k] = v } message.save message end def prefetch_user(user_id) return if @cache_users.key?(user_id) @cache_users[user_id] = User.find_or_fetch(@client, user_id) end def fetch_bot_user_id(bot_id) @cache_bots[bot_id] = @client.bots_info(bot: bot_id) unless @cache_bots[bot_id] @cache_bots[bot_id]['ok'] ? @cache_bots[bot_id]['bot']['user_id'] : nil end end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/models/slack_support/poster.rb
app/models/slack_support/poster.rb
require 'erb' module SlackSupport class Poster def initialize(client, channel_name) @client = client @channel_name = channel_name end def post(user, url, title, description) @client.chat_postMessage({ channel: channel_id, username: 'togelack', text: "<@#{user.uid}> が『<#{url}|#{ERB::Util.html_escape title}>』についてまとめました。\n<#{ERB::Util.html_escape url}>", parse: 'none', unfurl_links: true, icon_url: icon.match(/\Ahttp/) ? icon : nil, icon_emoji: icon.match(/\A:.+:\z/) ? icon : nil, attachments: [ { fallback: title, author_name: "@#{user.name}", author_icon: user.avatar_url, color: '#7CD197', title: title, title_link: url, text: description } ].to_json }.delete_if { |_, v| v.nil? }) end private def channel_id @channel_id ||= ChannelResolver.new(@client).resolve_by_name(@channel_name) end def icon (ENV['SLACK_ICON'] || ':slack:').to_s end end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/models/slack_support/emoji.rb
app/models/slack_support/emoji.rb
module SlackSupport class Emoji def initialize(client) @client = client end def get(name) list[name] end alias [] get def list @list ||= Rails.cache.fetch('slack_support__emoji#list', expires_in: 30.minutes) do resp = @client.emoji_list return {} unless resp['ok'] resp['emoji'].tap do |list| list.map do |key, value| list[key] = list[Regexp.last_match(1)] if value =~ /\Aalias:(.+)\z/ end end end end end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/models/slack_support/archive_url.rb
app/models/slack_support/archive_url.rb
module SlackSupport # SlackのArchiveページのURLを扱う class ArchiveURL # init # @param [String] url def initialize(url) @url = url.to_s.strip extract_from_url end attr_reader :url, :team, :channel, :ts, :thread_ts def valid? channel end private def extract_from_url uri_object = URI.parse(@url) extract_team(uri_object) extract_channel_and_ts(uri_object) extract_thread_id(uri_object) end def extract_team(uri_object) match = uri_object.host.match(/\A([^.]+)\.slack\.com\z/) @team = match ? match[1] : '' end def extract_channel_and_ts(uri_object) match = uri_object.path.match(%r{\A/archives/(?<channel>[^/]+)/p(?<ts1>\d+)(?<ts2>\d{6})\z}) return unless match @channel = match['channel'] @ts = "#{match['ts1']}.#{match['ts2']}" end def extract_thread_id(uri_object) return if uri_object.query.blank? params = URI.decode_www_form(uri_object.query).to_h @thread_ts = params['thread_ts'] end end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/models/slack_support/channel_resolver.rb
app/models/slack_support/channel_resolver.rb
module SlackSupport class ChannelResolver def initialize(client) @client = client @cache = {} end def resolve_by_id(id) @cache[id] ||= begin response = @client.conversations_info({ channel: id }) response['ok'] ? response['channel']['name'] : id end end def resolve_by_name(name) name # :( end end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/models/slack_support/client.rb
app/models/slack_support/client.rb
require 'slack-ruby-client' module SlackSupport module Client def self.create(token = nil) Slack::Web::Client.new(token: (token || ENV.fetch('SLACK_TOKEN', nil))) end end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/lib/decorate_serializer.rb
app/lib/decorate_serializer.rb
module DecorateSerializer def self.included(base) base.extend ClassMethods base.class_eval do def serializable_hash(_options = nil) self.class.attr_lists.index_with { |n| public_send(n) } end end end module ClassMethods def attr(*args) @_args = args end def attr_lists @_args || [] end end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/lib/pipeline_filters/replace_emoji_filter.rb
app/lib/pipeline_filters/replace_emoji_filter.rb
require 'gemoji' module PipelineFilters class ReplaceEmojiFilter < ::HTML::Pipeline::Filter def call doc.search('img').each do |node| next unless node['class'] == 'emoji' next if node['src'].starts_with?('https://') name = node['title'].gsub(':', '') info = Emoji.find_by_alias(name) node.replace(info.raw) if info end doc end end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/app/lib/pipeline_filters/add_rel_to_link_filter.rb
app/lib/pipeline_filters/add_rel_to_link_filter.rb
module PipelineFilters class AddRelToLinkFilter < ::HTML::Pipeline::Filter def call doc.search('a').each do |node| next unless node['href'].starts_with?('http') next if node['rel'] node['target'] = '_blank' node['rel'] = 'noopener noreferrer' end doc end end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/db/seeds.rb
db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first)
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/application.rb
config/application.rb
require_relative 'boot' require 'rails' # Pick the frameworks you want: require 'active_model/railtie' require 'active_job/railtie' # require "active_record/railtie" # require "active_storage/engine" require 'action_controller/railtie' require 'action_mailer/railtie' # require "action_mailbox/engine" # require "action_text/engine" require 'action_view/railtie' # require "action_cable/engine" # require "sprockets/railtie" require 'rails/test_unit/railtie' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Togelack class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.0 # Configuration for the application, engines, and railties goes here. # # These settings can be overridden in specific environments using the files # in config/environments, which are processed later. # config.time_zone = 'Tokyo' config.i18n.default_locale = :ja # config.eager_load_paths << Rails.root.join("extras") end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/environment.rb
config/environment.rb
# Load the Rails application. require_relative 'application' # Initialize the Rails application. Rails.application.initialize!
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/puma.rb
config/puma.rb
max_threads_count = ENV.fetch('RAILS_MAX_THREADS', 5) min_threads_count = ENV.fetch('RAILS_MIN_THREADS') { max_threads_count } threads min_threads_count, max_threads_count worker_timeout 3600 if ENV.fetch('RAILS_ENV', 'development') == 'development' port ENV.fetch('PORT', 3000) environment ENV.fetch('RAILS_ENV', 'development') pidfile ENV.fetch('PIDFILE', 'tmp/pids/server.pid') workers ENV.fetch('WEB_CONCURRENCY', 2) preload_app! plugin :tmp_restart
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/routes.rb
config/routes.rb
Rails.application.routes.draw do root 'summaries#index' get '/auth/:provider/callback', to: 'sessions#create' resource :session, only: [:destroy] resources :summaries do collection do get 'list' end end namespace :api do resources :histories, only: [:index] end get '@:name', to: 'users#show', as: 'user' get 'image', to: 'proxies#show', as: 'image_proxy' # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/boot.rb
config/boot.rb
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) require 'bundler/setup' # Set up gems listed in the Gemfile. require 'bootsnap/setup' # Speed up boot time by caching expensive operations.
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/initializers/content_security_policy.rb
config/initializers/content_security_policy.rb
# Be sure to restart your server when you modify this file. # Define an application-wide content security policy # For further information see the following documentation # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy # Rails.application.config.content_security_policy do |policy| # policy.default_src :self, :https # policy.font_src :self, :https, :data # policy.img_src :self, :https, :data # policy.object_src :none # policy.script_src :self, :https # policy.style_src :self, :https # # If you are using webpack-dev-server then specify webpack-dev-server host # policy.connect_src :self, :https, "http://localhost:3035", "ws://localhost:3035" if Rails.env.development? # # Specify URI for violation reports # # policy.report_uri "/csp-violation-report-endpoint" # end # If you are using UJS then enable automatic nonce generation # Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) } # Set the nonce only to specific directives # Rails.application.config.content_security_policy_nonce_directives = %w(script-src) # Report CSP violations to a specified URI # For further information see the following documentation: # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only # Rails.application.config.content_security_policy_report_only = true
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/initializers/filter_parameter_logging.rb
config/initializers/filter_parameter_logging.rb
# Be sure to restart your server when you modify this file. # Configure sensitive parameters which will be filtered from the log file. Rails.application.config.filter_parameters += [ :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn ]
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/initializers/gemoji.rb
config/initializers/gemoji.rb
[ { target: 'thinking', aliases: ['thinking_face'] } ].each do |item| emoji = Emoji.find_by_alias(item[:target]) raise "emoji: #{item[:target]} is not defined" unless emoji Emoji.edit_emoji(emoji) do |char| item[:aliases].each do |alias_name| char.add_alias(alias_name) end end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/initializers/application_controller_renderer.rb
config/initializers/application_controller_renderer.rb
# Be sure to restart your server when you modify this file. # ActiveSupport::Reloader.to_prepare do # ApplicationController.renderer.defaults.merge!( # http_host: 'example.org', # https: false # ) # end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/initializers/session_store.rb
config/initializers/session_store.rb
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_togelack_session', expire_after: 30.days.to_i
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/initializers/mongoid.rb
config/initializers/mongoid.rb
require 'mongoid' # @see https://github.com/mongodb/mongoid/pull/4944 module Mongoid module Errors class MongoidError < StandardError def translate(key, options) ::I18n.t("#{BASE_KEY}.#{key}", **options) end end end end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/initializers/new_framework_defaults_6_0.rb
config/initializers/new_framework_defaults_6_0.rb
# Be sure to restart your server when you modify this file. # # This file contains migration options to ease your Rails 6.0 upgrade. # # Once upgraded flip defaults one by one to migrate to the new default. # # Read the Guide for Upgrading Ruby on Rails for more info on each option. # Don't force requests from old versions of IE to be UTF-8 encoded. # Rails.application.config.action_view.default_enforce_utf8 = false # Embed purpose and expiry metadata inside signed and encrypted # cookies for increased security. # # This option is not backwards compatible with earlier Rails versions. # It's best enabled when your entire app is migrated and stable on 6.0. # Rails.application.config.action_dispatch.use_cookies_with_metadata = true # Change the return value of `ActionDispatch::Response#content_type` to Content-Type header without modification. # Rails.application.config.action_dispatch.return_only_media_type_on_content_type = false # Return false instead of self when enqueuing is aborted from a callback. # Rails.application.config.active_job.return_false_on_aborted_enqueue = true # Send Active Storage analysis and purge jobs to dedicated queues. # Rails.application.config.active_storage.queues.analysis = :active_storage_analysis # Rails.application.config.active_storage.queues.purge = :active_storage_purge # When assigning to a collection of attachments declared via `has_many_attached`, replace existing # attachments instead of appending. Use #attach to add new attachments without replacing existing ones. # Rails.application.config.active_storage.replace_on_assign_to_many = true # Use ActionMailer::MailDeliveryJob for sending parameterized and normal mail. # # The default delivery jobs (ActionMailer::Parameterized::DeliveryJob, ActionMailer::DeliveryJob), # will be removed in Rails 6.1. This setting is not backwards compatible with earlier Rails versions. # If you send mail in the background, job workers need to have a copy of # MailDeliveryJob to ensure all delivery jobs are processed properly. # Make sure your entire app is migrated and stable on 6.0 before using this setting. # Rails.application.config.action_mailer.delivery_job = "ActionMailer::MailDeliveryJob" # Enable the same cache key to be reused when the object being cached of type # `ActiveRecord::Relation` changes by moving the volatile information (max updated at and count) # of the relation's cache key into the cache version to support recycling cache key. # Rails.application.config.active_record.collection_cache_versioning = true
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/initializers/wrap_parameters.rb
config/initializers/wrap_parameters.rb
# Be sure to restart your server when you modify this file. # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/initializers/omniauth.rb
config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do provider(:slack, ENV.fetch('SLACK_CLIENT_ID', nil), ENV.fetch('SLACK_CLIENT_SECRET', nil), scope: 'identify,read', team: ENV.fetch('SLACK_TEAM_ID', nil)) end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/initializers/inflections.rb
config/initializers/inflections.rb
# Be sure to restart your server when you modify this file. # Add new inflection rules using the following format. Inflections # are locale specific, and you may define rules for as many different # locales as you wish. All of these examples are active by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # inflect.uncountable %w( fish sheep ) # end # These inflection rules are supported but not enabled by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.acronym 'RESTful' # end ActiveSupport::Inflector.inflections(:en) do |inflect| inflect.acronym 'API' end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/initializers/cookies_serializer.rb
config/initializers/cookies_serializer.rb
# Be sure to restart your server when you modify this file. # Specify a serializer for the signed and encrypted cookie jars. # Valid options are :json, :marshal, and :hybrid. Rails.application.config.action_dispatch.cookies_serializer = :json
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/initializers/permissions_policy.rb
config/initializers/permissions_policy.rb
# Define an application-wide HTTP permissions policy. For further # information see https://developers.google.com/web/updates/2018/06/feature-policy # # Rails.application.config.permissions_policy do |f| # f.camera :none # f.gyroscope :none # f.microphone :none # f.usb :none # f.fullscreen :self # f.payment :self, "https://secure.example.com" # end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/initializers/backtrace_silencers.rb
config/initializers/backtrace_silencers.rb
# Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| /my_noisy_library/.match?(line) } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code # by setting BACKTRACE=1 before calling your invocation, like "BACKTRACE=1 ./bin/rails runner 'MyClass.perform'". Rails.backtrace_cleaner.remove_silencers! if ENV['BACKTRACE']
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/initializers/mime_types.rb
config/initializers/mime_types.rb
# Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/initializers/new_framework_defaults_6_1.rb
config/initializers/new_framework_defaults_6_1.rb
# Be sure to restart your server when you modify this file. # # This file contains migration options to ease your Rails 6.1 upgrade. # # Once upgraded flip defaults one by one to migrate to the new default. # # Read the Guide for Upgrading Ruby on Rails for more info on each option. # Support for inversing belongs_to -> has_many Active Record associations. # Rails.application.config.active_record.has_many_inversing = true # Track Active Storage variants in the database. # Rails.application.config.active_storage.track_variants = true # Apply random variation to the delay when retrying failed jobs. # Rails.application.config.active_job.retry_jitter = 0.15 # Stop executing `after_enqueue`/`after_perform` callbacks if # `before_enqueue`/`before_perform` respectively halts with `throw :abort`. # Rails.application.config.active_job.skip_after_callbacks_if_terminated = true # Specify cookies SameSite protection level: either :none, :lax, or :strict. # # This change is not backwards compatible with earlier Rails versions. # It's best enabled when your entire app is migrated and stable on 6.1. # Rails.application.config.action_dispatch.cookies_same_site_protection = :lax # Generate CSRF tokens that are encoded in URL-safe Base64. # # This change is not backwards compatible with earlier Rails versions. # It's best enabled when your entire app is migrated and stable on 6.1. # Rails.application.config.action_controller.urlsafe_csrf_tokens = true # Specify whether `ActiveSupport::TimeZone.utc_to_local` returns a time with an # UTC offset or a UTC time. # ActiveSupport.utc_to_local_returns_utc_offset_times = true # Change the default HTTP status code to `308` when redirecting non-GET/HEAD # requests to HTTPS in `ActionDispatch::SSL` middleware. # Rails.application.config.action_dispatch.ssl_default_redirect_status = 308 # Use new connection handling API. For most applications this won't have any # effect. For applications using multiple databases, this new API provides # support for granular connection swapping. # Rails.application.config.active_record.legacy_connection_handling = false # Make `form_with` generate non-remote forms by default. # Rails.application.config.action_view.form_with_generates_remote_forms = false # Set the default queue name for the analysis job to the queue adapter default. # Rails.application.config.active_storage.queues.analysis = nil # Set the default queue name for the purge job to the queue adapter default. # Rails.application.config.active_storage.queues.purge = nil # Set the default queue name for the incineration job to the queue adapter default. # Rails.application.config.action_mailbox.queues.incineration = nil # Set the default queue name for the routing job to the queue adapter default. # Rails.application.config.action_mailbox.queues.routing = nil # Set the default queue name for the mail deliver job to the queue adapter default. # Rails.application.config.action_mailer.deliver_later_queue_name = nil # Generate a `Link` header that gives a hint to modern browsers about # preloading assets when using `javascript_include_tag` and `stylesheet_link_tag`. # Rails.application.config.action_view.preload_links_header = true
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/initializers/draper.rb
config/initializers/draper.rb
Draper::CollectionDecorator.delegate :current_page, :total_pages, :limit_value, :total_count
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/environments/test.rb
config/environments/test.rb
require 'active_support/core_ext/integer/time' # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. config.cache_classes = true # Do not eager load code on boot. This avoids loading your whole application # just for the purpose of running a single test. If you are using a tool that # preloads Rails for running tests, you may have to set it to true. config.eager_load = false # Configure public file server for tests with Cache-Control for performance. config.public_file_server.enabled = true config.public_file_server.headers = { 'Cache-Control' => "public, max-age=#{1.hour.to_i}" } # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false config.cache_store = :null_store # Raise exceptions instead of rendering exception templates. config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false config.action_mailer.perform_caching = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr # Raise exceptions for disallowed deprecations. config.active_support.disallowed_deprecation = :raise # Tell Active Support which deprecation messages to disallow. config.active_support.disallowed_deprecation_warnings = [] # Raises error for missing translations. # config.i18n.raise_on_missing_translations = true # Annotate rendered view with file names. # config.action_view.annotate_rendered_view_with_filenames = true end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/environments/development.rb
config/environments/development.rb
require 'active_support/core_ext/integer/time' Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded any time # it changes. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. # Run rails dev:cache to toggle caching. if Rails.root.join('tmp/caching-dev.txt').exist? config.action_controller.perform_caching = true config.action_controller.enable_fragment_cache_logging = true config.cache_store = :memory_store config.public_file_server.headers = { 'Cache-Control' => "public, max-age=#{2.days.to_i}" } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise exceptions for disallowed deprecations. config.active_support.disallowed_deprecation = :raise # Tell Active Support which deprecation messages to disallow. config.active_support.disallowed_deprecation_warnings = [] # Raises error for missing translations. # config.i18n.raise_on_missing_translations = true # Annotate rendered view with file names. # config.action_view.annotate_rendered_view_with_filenames = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker # Uncomment if you wish to allow Action Cable access from any origin. # config.action_cable.disable_request_forgery_protection = true end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
rutan/togelack
https://github.com/rutan/togelack/blob/810cc078a805787a13b0b0751ae5bbebafa20405/config/environments/production.rb
config/environments/production.rb
require 'active_support/core_ext/integer/time' Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Include generic and useful information about system operation, but avoid logging too much # information to avoid inadvertent exposure of personally identifiable information (PII). config.log_level = :info # Prepend all log lines with the following tags. config.log_tags = [:request_id] # Use a different cache store in production. # config.cache_store = :mem_cache_store config.cache_store = :redis_cache_store, { url: ENV['REDIS_URL'] } if ENV['REDIS_URL'].present? # Use a real queuing backend for Active Job (and separate queues per environment). # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "togelack_production" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Log disallowed deprecations. config.active_support.disallowed_deprecation = :log # Tell Active Support which deprecation messages to disallow. config.active_support.disallowed_deprecation_warnings = [] # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = Logger::Formatter.new # Use a different logger for distributed setups. # require "syslog/logger" # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV['RAILS_LOG_TO_STDOUT'].present? logger = ActiveSupport::Logger.new($stdout) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Inserts middleware to perform automatic connection switching. # The `database_selector` hash is used to pass options to the DatabaseSelector # middleware. The `delay` is used to determine how long to wait after a write # to send a subsequent read to the primary. # # The `database_resolver` class is used by the middleware to determine which # database is appropriate to use based on the time delay. # # The `database_resolver_context` class is used by the middleware to set # timestamps for the last write to the primary. The resolver uses the context # class timestamps to determine how long to wait before reading from the # replica. # # By default Rails will store a last write timestamp in the session. The # DatabaseSelector middleware is designed as such you can define your own # strategy for connection switching and pass that into the middleware through # these configuration options. # config.active_record.database_selector = { delay: 2.seconds } # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session end
ruby
MIT
810cc078a805787a13b0b0751ae5bbebafa20405
2026-01-04T17:48:38.164574Z
false
goco-inc/legacy-graphql-activerecord
https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true require 'bundler/setup' Bundler.setup require 'pry' require 'graphql/activerecord' RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # This option will default to `:apply_to_host_groups` in RSpec 4 (and will # have no way to turn it off -- the option exists only for backwards # compatibility in RSpec 3). It causes shared context metadata to be # inherited by the metadata hash of host groups and examples, rather than # triggering implicit auto-inclusion in groups with matching metadata. config.shared_context_metadata_behavior = :apply_to_host_groups # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. # This allows you to limit a spec run to individual examples or groups # you care about by tagging them with `:focus` metadata. When nothing # is tagged with `:focus`, all examples get run. RSpec also provides # aliases for `it`, `describe`, and `context` that include `:focus` # metadata: `fit`, `fdescribe` and `fcontext`, respectively. config.filter_run_when_matching :focus # Allows RSpec to persist some state between runs in order to support # the `--only-failures` and `--next-failure` CLI options. We recommend # you configure your source control system to ignore this file. config.example_status_persistence_file_path = "spec/examples.txt" # Limits the available syntax to the non-monkey patched syntax that is # recommended. For more details, see: # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode config.disable_monkey_patching! # This setting enables warnings. It's recommended, but in some cases may # be too noisy due to issues in dependencies. config.warnings = true # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = 'doc' end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. config.profile_examples = 10 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed end
ruby
MIT
025be0879466ee2e6d7324f4dd59b6a306e0e211
2026-01-04T17:48:42.035378Z
false
goco-inc/legacy-graphql-activerecord
https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/spec/graphql/models/hash_combiner_spec.rb
spec/graphql/models/hash_combiner_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe GraphQL::Models::HashCombiner do describe '::combine' do it "groups items based on the most common value first" do input = [ { type: 'hello', id: 1 }, { type: 'hello', id: 2 }, { type: 'hello', id: 3 }, { type: 'hello', id: 4 }, { type: 'world', id: 11 }, { type: 'world', id: 21 }, { type: 'world', id: 31 }, { type: 'world', id: 41 }, ] output = [ { type: 'hello', id: [1, 2, 3, 4] }, { type: 'world', id: [11, 21, 31, 41] }, ] expect(GraphQL::Models::HashCombiner.combine(input)).to eq output end it "doesn't generate a separate group if all hashes have the same value for two keys" do input = [ { prop_1: 'hello', prop_2: 'world', id: 1 }, { prop_1: 'hello', prop_2: 'world', id: 2 }, { prop_1: 'hello', prop_2: 'world', id: 3 }, { prop_1: 'hello', prop_2: 'world', id: 4 }, ] output = [ { prop_1: 'hello', prop_2: 'world', id: [1, 2, 3, 4] }, ] expect(GraphQL::Models::HashCombiner.combine(input)).to eq output end it "can combine arrays together" do input = [ { prop_1: 'hello', prop_2: [1, 2, 3] }, { prop_1: 'hello', prop_2: [4, 5, 6] }, ] output = [ { prop_1: 'hello', prop_2: [1, 2, 3, 4, 5, 6] }, ] expect(GraphQL::Models::HashCombiner.combine(input)).to eq output end end end
ruby
MIT
025be0879466ee2e6d7324f4dd59b6a306e0e211
2026-01-04T17:48:42.035378Z
false
goco-inc/legacy-graphql-activerecord
https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/activerecord.rb
lib/graphql/activerecord.rb
# frozen_string_literal: true require 'active_support' require 'active_record' require 'graphql' require 'graphql/batch' require 'graphql/relay' require 'graphql/models/monkey_patches/graphql_query_context' require 'graphql/models/active_record_extension' require 'graphql/models/instrumentation' # Helpers require 'graphql/models/helpers' require 'graphql/models/hash_combiner' require 'graphql/models/definer' require 'graphql/models/association_load_request' require 'graphql/models/attribute_loader' require 'graphql/models/relation_loader' # Order matters... require 'graphql/models/promise_relation_connection' require 'graphql/models/relation_load_request' require 'graphql/models/database_types' require 'graphql/models/reflection' require 'graphql/models/definition_helpers' require 'graphql/models/definition_helpers/associations' require 'graphql/models/definition_helpers/attributes' require 'graphql/models/mutation_helpers/print_input_fields' require 'graphql/models/mutation_helpers/apply_changes' require 'graphql/models/mutation_helpers/authorization' require 'graphql/models/mutation_helpers/validation_error' require 'graphql/models/mutation_helpers/validation' require 'graphql/models/mutation_field_map' require 'graphql/models/backed_by_model' require 'graphql/models/mutator' module GraphQL module Models class << self attr_accessor :model_from_id, :authorize, :id_for_model, :model_to_graphql_type, :unknown_scalar attr_accessor :legacy_nulls end # Returns a promise that will traverse the associations and resolve to the model at the end of the path. # You can use this to access associated models inside custom field resolvers, without losing optimization # benefits. def self.load_association(starting_model, path, context) path = Array.wrap(path) GraphQL::Models::DefinitionHelpers.load_and_traverse(starting_model, path, context) end def self.load_relation(relation, fast_query: false) if fast_query request = AttributeLoader::Request.new(relation.where_values_hash, Helpers.orders_to_sql(relation.arel.orders)) AttributeLoader.for(relation.klass).load(request) else request = RelationLoadRequest.new(relation) request.load end end def self.field_info(graph_type, field_name) field_name = field_name.to_s meta = graph_type.instance_variable_get(:@field_metadata) return nil unless meta meta[field_name] end def self.authorize!(context, model, action) authorize.call(context, model, action) end def self.define_mutator(definer, model_type, null_behavior: :leave_unchanged, legacy_nulls: GraphQL::Models.legacy_nulls, &block) legacy_nulls ||= false # HACK: To get the name of the mutation, to avoid possible collisions with other type names prefix = definer.instance_variable_get(:@target).name mutator_definition = MutatorDefinition.new(model_type, null_behavior: null_behavior, legacy_nulls: legacy_nulls) mutator_definition.field_map.instance_exec(&block) MutationHelpers.print_input_fields(mutator_definition.field_map, definer, "#{prefix}Input") mutator_definition end def self.get_graphql_type(model_class) model_class = model_class.constantize if model_class.is_a?(String) if model_to_graphql_type model_to_graphql_type[model_class] else "#{model_class.name}Type".safe_constantize end end def self.get_graphql_type!(model_class) type = get_graphql_type(model_class) raise "Could not locate GraphQL type for model #{model_class}" if type.nil? type end end end GraphQL::ObjectType.accepts_definitions( backed_by_model: -> (graph_type, model_type, &block) do model_type = model_type.to_s.classify.constantize unless model_type.is_a?(Class) backer = GraphQL::Models::BackedByModel.new(graph_type, model_type) backer.instance_exec(&block) end )
ruby
MIT
025be0879466ee2e6d7324f4dd59b6a306e0e211
2026-01-04T17:48:42.035378Z
false
goco-inc/legacy-graphql-activerecord
https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/hash_combiner.rb
lib/graphql/models/hash_combiner.rb
# frozen_string_literal: true module GraphQL::Models::HashCombiner class << self # Takes a set of hashes that represent conditions, and combines them into the smallest number of hashes def combine(hashes) # Group the hashes by keys. If they are querying different columns, they can't be combined by_keys = hashes.group_by { |h| h.keys.sort } by_keys.map { |keys, values| combine_core(values, keys) }.flatten end private def combine_core(hashes, keys) return [] if keys.nil? || keys.empty? # If there's only one key in each of the hashes, then combine that into a single hash with an array if keys.length == 1 values = hashes.map { |h| h[keys[0]] } return [{ keys[0] => values.flatten.uniq }] end # Get the most commonly occuring value in the hash, and remove it from the keys. # Return one hash for each unique value. min_key = keys.min_by { |k| hashes.map { |h| h[k] }.flatten.uniq.count } inner_keys = keys.dup inner_keys.delete(min_key) # Group the hashes based on the value that they have for that key grouped = hashes.group_by { |h| h[min_key] } grouped = grouped.map do |key_value, inner_hashes| combined = combine_core(inner_hashes, inner_keys) merge_with = { min_key => key_value } combined.map { |reduced_hash| merge_with.merge(reduced_hash) } end grouped.flatten end end end
ruby
MIT
025be0879466ee2e6d7324f4dd59b6a306e0e211
2026-01-04T17:48:42.035378Z
false
goco-inc/legacy-graphql-activerecord
https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/version.rb
lib/graphql/models/version.rb
# frozen_string_literal: true module GraphQL module Models VERSION = "0.13.0" end end
ruby
MIT
025be0879466ee2e6d7324f4dd59b6a306e0e211
2026-01-04T17:48:42.035378Z
false
goco-inc/legacy-graphql-activerecord
https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/attribute_loader.rb
lib/graphql/models/attribute_loader.rb
# frozen_string_literal: true module GraphQL::Models # Simplified loader that can take a hash of attributes to match, combine them into a single query, and then fulfill # then individually. It can also ask the database to order them correctly. class AttributeLoader < GraphQL::Batch::Loader attr_reader :model_class def initialize(model_class) @model_class = model_class end class Request attr_accessor :attributes, :sorting def initialize(attributes, sorting) @attributes = attributes @sorting = sorting end end WHERE_STRIP = /\AWHERE / # @param requests An AttributeLoader::Request (or a simple hash) that describes the models to be loaded def perform(requests) # Combine the conditions together, into the minimal set of conditions needed conditions = HashCombiner.combine(requests.map { |r| r.is_a?(Request) ? r.attributes : r }) # Get the distinct list of sorting conditions that we need to ask for, also sorters = requests.map { |r| r.is_a?(Request) ? r.sorting : nil }.compact.reject(&:blank?).uniq # Start constructing the query that we'll execute to get the results table = model_class.arel_table # Start building the query, add in the where conditions conditions.map! { |cond| hash_to_condition(table, cond) } query = table.where(conditions.reduce { |memo, cond| memo.or(cond) }) # Convert the list of sorters into RANK() selections that we'll add to the selection order_selections = sorters.each_with_index.map { |s, idx| order_selection(s, idx) } # Add the projections to the query query = order_selections.reduce(query.project(:*)) { |memo, selection| memo.project(selection) } # Get the result set results = model_class.find_by_sql(query.to_sql) # De-multiplex the result set and fulfill the requests requests.each do |request| # Get the rows that match this request response = match_results(results, request) if response.size > 1 && request.is_a?(Request) && request.sorting idx = sorters.index(request.sorting) sort_by = "rank_#{idx}" response = response.sort_by { |row| row[sort_by] } end fulfill(request, response) end end private def order_selection(sorter, idx) arel = model_class.unscoped.order(sorter).arel order_sql = Helpers.orders_to_sql(arel.orders) %{ DENSE_RANK() OVER(ORDER BY #{order_sql}) AS rank_#{idx} } end # Converts a hash into arel conditions def hash_to_condition(table, hash) conditions = hash.map do |attr, value| if value.is_a?(Array) && value.size > 1 table[attr].in(value) elsif value.is_a?(Array) table[attr].eq(value[0]) else table[attr].eq(value) end end conditions.reduce { |memo, cond| memo.and(cond) } end def match_results(results, request) # Find all of the items in the results that match the request attributes = request.is_a?(Request) ? request.attributes : request results.select do |row| attributes.all? { |key, value| is_match(row.send(key), value) } end end def is_match(row_value, compare_value) compare_value.is_a?(Array) ? compare_value.include?(row_value) : compare_value == row_value end end end
ruby
MIT
025be0879466ee2e6d7324f4dd59b6a306e0e211
2026-01-04T17:48:42.035378Z
false
goco-inc/legacy-graphql-activerecord
https://github.com/goco-inc/legacy-graphql-activerecord/blob/025be0879466ee2e6d7324f4dd59b6a306e0e211/lib/graphql/models/mutator.rb
lib/graphql/models/mutator.rb
# frozen_string_literal: true module GraphQL::Models class Mutator attr_accessor :field_map, :root_model, :inputs, :context def initialize(field_map, root_model, inputs, context) @field_map = field_map @root_model = root_model @inputs = inputs @context = context end def apply_changes raise StandardError, "Called apply_changes twice for the same mutator" if @all_changes @all_changes = MutationHelpers.apply_changes(field_map, root_model, inputs, context) changed_models end def changed_models raise StandardError, "Need to call apply_changes before #{__method__}" unless @all_changes @all_changes.map { |c| c[:model_instance] }.uniq end def validate! raise StandardError, "Need to call apply_changes before #{__method__}" unless @all_changes MutationHelpers.validate_changes(inputs, field_map, root_model, context, @all_changes) end def authorize! raise StandardError, "Need to call apply_changes before #{__method__}" unless @all_changes MutationHelpers.authorize_changes(context, @all_changes) end def save! raise StandardError, "Need to call apply_changes before #{__method__}" unless @all_changes ActiveRecord::Base.transaction(requires_new: true) do changed_models.each do |model| next if model.destroyed? if model.marked_for_destruction? model.destroy else model.save! end end changed_models.reject(&:destroyed?) end end end class MutatorDefinition attr_accessor :field_map def initialize(model_type, null_behavior:, legacy_nulls:) @field_map = MutationFieldMap.new(model_type, find_by: nil, null_behavior: null_behavior, legacy_nulls: legacy_nulls) end def mutator(root_model, inputs, context) Mutator.new(field_map, root_model, inputs, context) end end end
ruby
MIT
025be0879466ee2e6d7324f4dd59b6a306e0e211
2026-01-04T17:48:42.035378Z
false