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
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/test/models/analyzer_test.rb
test/models/analyzer_test.rb
# frozen_string_literal: true require "test_helper" class AnalyzerTest < ActiveSupport::TestCase test "classes" do analyzer = Analyzer.new analyzer.analyze_code("test.rb", <<~RUBY) # comment1 # comment2 class Foo end RUBY assert_equal 1, analyzer.classes.length clazz = analyzer.classes.first assert_equal "Foo", clazz.name assert_equal 2, clazz.comments.length assert_equal 1, clazz.defined_files.length defined_file = clazz.defined_files.first assert_equal "test.rb", defined_file.path end test "classes with superclass" do analyzer = Analyzer.new analyzer.analyze_code("test.rb", <<~RUBY) class Foo < Bar end RUBY assert_equal 1, analyzer.classes.length clazz = analyzer.classes.first assert_not_nil clazz.superclass assert_equal "Bar", clazz.superclass.name end test "classes redefined" do analyzer = Analyzer.new analyzer.analyze_code("foo.rb", <<~RUBY) class Foo end RUBY analyzer.analyze_code("bar.rb", <<~RUBY) class Foo end RUBY assert_equal 1, analyzer.classes.length assert_equal 2, analyzer.classes.first.defined_files.length end test "classes with includes" do analyzer = Analyzer.new analyzer.analyze_code("test.rb", <<~RUBY) module Level1 module IncludeMe; end module Level2 module IncludeMe; end end end module Level1 module Level2::Level3 class Level4 include IncludeMe include NotFound extend IncludeMe end end end RUBY assert_equal 1, analyzer.classes.length clazz = analyzer.classes.first assert_equal 2, clazz.included_modules.length assert_equal "IncludeMe", clazz.included_modules.first.name assert_equal "Level1::IncludeMe", clazz.included_modules.first.qualified_name assert_equal 1, clazz.extended_modules.length assert_equal "IncludeMe", clazz.extended_modules.first.name assert_equal "Level1::IncludeMe", clazz.extended_modules.first.qualified_name end test "modules" do analyzer = Analyzer.new analyzer.analyze_code("test.rb", <<~RUBY) # comment1 # comment2 module Foo end RUBY assert_equal 1, analyzer.modules.length mod = analyzer.modules.first assert_equal "Foo", mod.name assert_equal 2, mod.comments.length assert_equal 1, mod.defined_files.length defined_file = mod.defined_files.first assert_equal "test.rb", defined_file.path end test "modules redefined" do analyzer = Analyzer.new analyzer.analyze_code("foo.rb", <<~RUBY) module Foo end RUBY analyzer.analyze_code("bar.rb", <<~RUBY) module Foo end RUBY assert_equal 1, analyzer.modules.length assert_equal 2, analyzer.modules.first.defined_files.length end test "instance methods" do analyzer = Analyzer.new analyzer.analyze_code("test.rb", <<~RUBY) # comment1 # comment2 def foo end RUBY assert_equal 1, analyzer.instance_methods.length instance_method = analyzer.instance_methods.first assert_equal "foo", instance_method.name assert_equal 2, instance_method.comments.length end test "class methods" do analyzer = Analyzer.new analyzer.analyze_code("test.rb", <<~RUBY) # comment1 # comment2 def self.foo end RUBY assert_equal 1, analyzer.class_methods.length class_method = analyzer.class_methods.first assert_equal "foo", class_method.name assert_equal 2, class_method.comments.length end test "constants" do analyzer = Analyzer.new analyzer.analyze_code("test.rb", <<~RUBY) # comment1 # comment2 FOO = 1 RUBY assert_equal 1, analyzer.consts.length assert_equal "FOO", analyzer.consts.first end end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/test/models/rbs/nilable_test.rb
test/models/rbs/nilable_test.rb
# frozen_string_literal: true require "test_helper" module RBS class NilableTest < ActiveSupport::TestCase def setup @gem = GemSpec.find("activerecord", "7.0.7") @module = @gem.find_class("ActiveRecord::ConnectionAdapters::PoolManager") @method = @module.find_method("pool_configs") end test "optional positional arguments as nilable type" do FactoryBot.create( :type_sample, gem_name: "activerecord", gem_version: "7.0.7", receiver: "ActiveRecord::ConnectionAdapters::PoolManager", method_name: "pool_configs", parameters: [ ["role", "opt", "NilClass"], ], return_value: nil, ) assert_equal "def pool_configs: (?nil role) -> untyped", @method.rbs_signature(@gem) @method.clear_sample_cache! FactoryBot.create( :type_sample, gem_name: "activerecord", gem_version: "7.0.7", receiver: "ActiveRecord::ConnectionAdapters::PoolManager", method_name: "pool_configs", parameters: [ ["role", "opt", "String"], ], return_value: nil, ) assert_equal "def pool_configs: (?String? role) -> untyped", @method.rbs_signature(@gem) end end end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/test/models/rbs/rbs_test.rb
test/models/rbs/rbs_test.rb
# frozen_string_literal: true require "test_helper" module RBS class RBSTest < ActiveSupport::TestCase def setup @gem = GemSpec.find("railties", "7.0.6") @module = @gem.find_module("Rails") @method = @module.find_method("env") end test "with no samples" do assert_nil @method.rbs_signature(@gem) assert_nil @method.rbs_signature(@gem, require_samples: true) assert_equal "def env: () -> untyped", @method.rbs_signature(@gem, require_samples: false) assert_nil @module.rbs_signature(@gem) assert_equal <<~RBS, @module.rbs_signature(@gem, require_samples: false) # sig/rails.rbs module Rails def self.gem_version: () -> untyped def self.version: () -> untyped def application: () -> untyped def autoloaders: () -> untyped def backtrace_cleaner: () -> untyped def configuration: () -> untyped def env: () -> untyped def env=: () -> untyped def error: () -> untyped def groups: () -> untyped def public_path: () -> untyped def root: () -> untyped end RBS end test "with one sample" do FactoryBot.create( :type_sample, gem_name: "railties", gem_version: "7.0.6", receiver: "Rails", method_name: "env", parameters: [], return_value: "String", ) assert_equal "def env: () -> String", @method.rbs_signature(@gem) assert_equal <<~RBS, @module.rbs_signature(@gem) # sig/rails.rbs module Rails def env: () -> String end RBS assert_equal <<~RBS, @module.rbs_signature(@gem, require_samples: false) # sig/rails.rbs module Rails def self.gem_version: () -> untyped def self.version: () -> untyped def application: () -> untyped def autoloaders: () -> untyped def backtrace_cleaner: () -> untyped def configuration: () -> untyped def env: () -> String def env=: () -> untyped def error: () -> untyped def groups: () -> untyped def public_path: () -> untyped def root: () -> untyped end RBS end end end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/test/models/rbs/constructor_test.rb
test/models/rbs/constructor_test.rb
# frozen_string_literal: true require "test_helper" module RBS class ConstructorTest < ActiveSupport::TestCase def setup @gem = GemSpec.find("nokogiri", "1.15.0") @class = @gem.find_class("Nokogiri::XML::Document") @method = @class.find_method("initialize") end test "initialize's return_value is void" do assert_nil @method.rbs_signature(@gem) assert_equal "def initialize: () -> void", @method.rbs_signature(@gem, require_samples: false) @method.clear_sample_cache! FactoryBot.create( :type_sample, gem_name: "nokogiri", gem_version: "1.15.0", receiver: "Nokogiri::XML::Document", method_name: "initialize", parameters: [], return_value: nil, ) @method = @class.find_method("initialize") assert_equal "def initialize: () -> void", @method.rbs_signature(@gem) assert_equal "def initialize: () -> void", @method.rbs_signature(@gem, require_samples: false) end end end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/test/models/rbs/parameters_test.rb
test/models/rbs/parameters_test.rb
# frozen_string_literal: true require "test_helper" module RBS class ParametersTest < ActiveSupport::TestCase def setup @gem = GemSpec.find("nokogiri", "1.15.0") @class = @gem.find_class("Nokogiri::XML::Document") @method = @class.find_method("parse") end test "positional arguments and optional positional arguments" do FactoryBot.create( :type_sample, gem_name: "nokogiri", gem_version: "1.15.0", receiver: "Nokogiri::XML::Document", method_name: "parse", parameters: [ ["string_or_io", "req", "String"], ["url", "opt", "NilClass"], ["encoding", "opt", "String"], ["options", "opt", "Integer"], ], return_value: "Nokogiri::XML::Document", ) assert_equal "def parse: (String string_or_io, ?nil url, ?String encoding, ?Integer options) -> Nokogiri::XML::Document", @method.rbs_signature(@gem) assert_equal <<~RBS, @class.rbs_signature(@gem) # sig/nokogiri/xml/document.rbs class Nokogiri::XML::Document < Nokogiri::XML::Nokogiri::XML::Node def parse: (String string_or_io, ?nil url, ?String encoding, ?Integer options) -> Nokogiri::XML::Document end RBS assert_equal <<~RBS, @class.rbs_signature(@gem, require_samples: false) # sig/nokogiri/xml/document.rbs class Nokogiri::XML::Document < Nokogiri::XML::Nokogiri::XML::Node def add_child: () -> untyped def collect_namespaces: () -> untyped def create_cdata: () -> untyped def create_comment: () -> untyped def create_element: () -> untyped def create_text_node: () -> untyped def deconstruct_keys: () -> untyped def decorate: () -> untyped def decorators: () -> untyped def document: () -> untyped def empty_doc?: () -> untyped def fragment: () -> untyped def initialize: () -> void def inspect_attributes: () -> untyped def name: () -> untyped def namespaces: () -> untyped def parse: (String string_or_io, ?nil url, ?String encoding, ?Integer options) -> Nokogiri::XML::Document def slop!: () -> untyped def validate: () -> untyped def xpath_doctype: () -> untyped end RBS end end end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/test/channels/application_cable/connection_test.rb
test/channels/application_cable/connection_test.rb
# frozen_string_literal: true require "test_helper" module ApplicationCable class ConnectionTest < ActionCable::Connection::TestCase # test "connects with cookies" do # cookies.signed[:user_id] = 42 # # connect # # assert_equal connection.user_id, "42" # end end end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/application.rb
config/application.rb
# frozen_string_literal: true require_relative "boot" require "rails/all" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Gemsh class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 7.1 # Please, add to the `ignore` list any other `lib` subdirectories that do # not contain `.rb` files, or that should not be reloaded or eager loaded. # Common ones are `templates`, `generators`, or `middleware`, for example. config.autoload_lib(ignore: ["assets", "tasks"]) # 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 = "Central Time (US & Canada)" # config.eager_load_paths << Rails.root.join("extras") end end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/environment.rb
config/environment.rb
# frozen_string_literal: true # Load the Rails application. require_relative "application" # Initialize the Rails application. Rails.application.initialize!
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/puma.rb
config/puma.rb
# frozen_string_literal: true # This configuration file will be evaluated by Puma. The top-level methods that # are invoked here are part of Puma's configuration DSL. For more information # about methods provided by the DSL, see https://puma.io/puma/Puma/DSL.html. # Puma can serve each request in a thread from an internal thread pool. # The `threads` method setting takes two numbers: a minimum and maximum. # Any libraries that use thread pools should be configured to match # the maximum value specified for Puma. Default is set to 5 threads for minimum # and maximum; this matches the default thread size of Active Record. # 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 # Specifies that the worker count should equal the number of processors in production. if ENV["RAILS_ENV"] == "production" require "concurrent-ruby" worker_count = Integer(ENV.fetch("WEB_CONCURRENCY") { Concurrent.physical_processor_count }) workers worker_count if worker_count > 1 end # Specifies the `worker_timeout` threshold that Puma will use to wait before # terminating a worker in development environments. # worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development" # Specifies the `port` that Puma will listen on to receive requests; default is 3000. port ENV.fetch("PORT", 3000) # Specifies the `environment` that Puma will run in. environment ENV.fetch("RAILS_ENV", "development") # Specifies the `pidfile` that Puma will use. pidfile ENV.fetch("PIDFILE", "tmp/pids/server.pid") # Allow puma to be restarted by `bin/rails restart` command. plugin :tmp_restart
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/routes.rb
config/routes.rb
# frozen_string_literal: true Rails.application.routes.draw do root "page#home" get "/home" => "page#home", as: :home get "/docs" => "page#docs", as: :docs get "/community" => "page#community", as: :community get "/types" => "page#types", as: :types resources :search, only: :index draw :gems draw :api # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. # Can be used by load balancers and uptime monitors to verify that the app is live. get "up" => "rails/health#show", as: :rails_health_check end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/sitemap.rb
config/sitemap.rb
# frozen_string_literal: true # Set the host name for URL creation SitemapGenerator::Sitemap.default_host = "https://gem.sh" SitemapGenerator::Sitemap.create do # Put links creation logic here. # # The root path "/" and sitemap index file are added automatically for you. # Links are added to the Sitemap in the order they are specified. # # Usage: add(path, options = {}) # (default options are used if you don"t specify) # # Defaults: priority: 0.5, changefreq: "weekly", lastmod: Time.now, host: default_host # # Examples: # # Add "/articles" # # add articles_path, priority: 0.7, changefreq: "daily" # # Add all articles: # # Article.find_each do |article| # add article_path(article), lastmod: article.updated_at # end add "/", changefreq: "weekly" add gems_path, changefreq: "daily" add docs_path, changefreq: "weekly" add community_path, changefreq: "weekly" Gem::Specification.find_each do |gem| add(gem_version_gem_path(gem.name, gem.version), changefreq: "weekly", lastmod: gem.date) spec = GemSpec.find(gem.name, gem.version) spec.classes.each do |klass| add(gem_version_class_path(spec.name, spec.version, klass.qualified_name), changefreq: "weekly", lastmod: gem.date) # spec.instance_methods.each do |method| # add(gem_version_class_instance_method_path(spec.name, spec.version, klass.qualified_name, method.name), changefreq: "weekly", lastmod: gem.date) # end # spec.class_methods.each do |method| # add(gem_version_class_class_method_path(spec.name, spec.version, klass.qualified_name, method.name), changefreq: "weekly", lastmod: gem.date) # end end spec.modules.each do |mod| add(gem_version_module_path(spec.name, spec.version, mod.qualified_name), changefreq: "weekly", lastmod: gem.date) # spec.instance_methods.each do |method| # add(gem_version_module_instance_method_path(spec.name, spec.version, mod.qualified_name, method.name), changefreq: "weekly", lastmod: gem.date) # end # spec.class_methods.each do |method| # add(gem_version_module_class_method_path(spec.name, spec.version, mod.qualified_name, method.name), changefreq: "weekly", lastmod: gem.date) # end end spec.instance_methods.each do |method| add(gem_version_instance_method_path(spec.name, spec.version, method.name), changefreq: "weekly", lastmod: gem.date) end spec.class_methods.each do |method| add(gem_version_class_method_path(spec.name, spec.version, method.name), changefreq: "weekly", lastmod: gem.date) end end end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/boot.rb
config/boot.rb
# frozen_string_literal: true 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
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/initializers/heroicon.rb
config/initializers/heroicon.rb
# frozen_string_literal: true Heroicon.configure do |config| config.variant = :solid # Options are :solid, :outline and :mini ## # You can set a default class, which will get applied to every icon with # the given variant. To do so, un-comment the line below. # config.default_class = {solid: "h-5 w-5", outline: "h-6 w-6", mini: "h-4 w-4"} end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/initializers/content_security_policy.rb
config/initializers/content_security_policy.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Define an application-wide content security policy. # See the Securing Rails Applications Guide for more information: # https://guides.rubyonrails.org/security.html#content-security-policy-header # Rails.application.configure do # 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 # # Specify URI for violation reports # # policy.report_uri "/csp-violation-report-endpoint" # end # # # Generate session nonces for permitted importmap, inline scripts, and inline styles. # config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } # config.content_security_policy_nonce_directives = %w(script-src style-src) # # # Report violations without enforcing the policy. # # config.content_security_policy_report_only = true # end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/initializers/filter_parameter_logging.rb
config/initializers/filter_parameter_logging.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file. # Use this to limit dissemination of sensitive information. # See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors. Rails.application.config.filter_parameters += [ :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, ]
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/initializers/rorvswild.rb
config/initializers/rorvswild.rb
# frozen_string_literal: true return unless Rails.env.production? if (api_key = Rails.application.credentials.dig(:rorvswild, :api_key)) RorVsWild.start( api_key: api_key, ignored_exceptions: [ "ActionController::RoutingError", "ZeroDivisionError", ], ) end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/initializers/type_fusion.rb
config/initializers/type_fusion.rb
# frozen_string_literal: true # require "type_fusion" # # TypeFusion.config do |config| # config.type_sample_call_rate = 0.001 # config.endpoint = "http://localhost:3000/api/v1/types/samples" # end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/initializers/inflections.rb
config/initializers/inflections.rb
# frozen_string_literal: true # 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 "API" inflect.acronym "RBS" inflect.acronym "UI" inflect.acronym "YARD" end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/initializers/permissions_policy.rb
config/initializers/permissions_policy.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # 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 |policy| # policy.camera :none # policy.gyroscope :none # policy.microphone :none # policy.usb :none # policy.fullscreen :self # policy.payment :self, "https://secure.example.com" # end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/initializers/assets.rb
config/initializers/assets.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = "1.0" # Add additional assets to the asset load path. # Rails.application.config.assets.paths << Emoji.images_path # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in the app/assets # folder are already added. # Rails.application.config.assets.precompile += %w( admin.js admin.css )
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/initializers/meta_tags.rb
config/initializers/meta_tags.rb
# frozen_string_literal: true MetaTags.config do |config| # Default title methods to be checked for title # # config.title_methods = %w(title name) # Default decsription methods to be checked for description # # config.description_methods = %w(description desc) # Default image methods to be checked for image # # config.image_methods = %w(image picture avatar) # When setting a title, keep original title after : # # Example : If you set the default title to "My Shop" and, on the home page # set the title to "Home", you'll end up with a title of : "Home - My Shop" # # Defaults to true # # config.keep_default_title_present = false end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/initializers/reactionview.rb
config/initializers/reactionview.rb
# frozen_string_literal: true ReActionView.configure do |config| # Intercept .html.erb templates and process them with `Herb::Engine` for enhanced features config.intercept_erb = Rails.env.development? # Enable debug mode in development (adds debug attributes to HTML) config.debug_mode = Rails.env.development? # Add custom transform visitors to process templates before compilation # config.transform_visitors = [ # Herb::Visitor::new # ] end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/routes/gems.rb
config/routes/gems.rb
# frozen_string_literal: true scope "/", as: :gem do resources :gems, only: [], param: :gem, as: :gem, module: :gems do member do scope "/v:version", as: :version, version: %r{[^/]*} do draw :gem get "/" => "/gems#show" end draw :gem end end end get "/gems" => "gems#index", as: :gems get "/gems/:gem" => "gems#show", as: :gem
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/routes/methods.rb
config/routes/methods.rb
# frozen_string_literal: true resources :instance_methods, only: :show resources :class_methods, only: :show # TODO: remove redirects get "/instance_method/:id", to: redirect { |_params, request| request.url.gsub("/instance_method/", "/instance_methods/") } get "/class_method/:id", to: redirect { |_params, request| request.url.gsub("/class_method/", "/class_methods/") }
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/routes/api.rb
config/routes/api.rb
# frozen_string_literal: true namespace :api do namespace :v1 do namespace :types do resources :samples, only: :create end end end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/routes/gem.rb
config/routes/gem.rb
# frozen_string_literal: true resources :classes, only: [:index, :show] do draw :methods end resources :modules, only: [:index, :show] do draw :methods end draw :methods resources :guides, only: [:index, :show] resources :search, only: [:index] resources :docs, only: [:index, :show] resources :files, only: [:index, :show], constraints: { id: /.*/ } resources :types, only: :index resources :versions, only: :index resources :rbs, only: :index pages = [ "announcements", "articles", "changelogs", "community", "metadata", "playground", "readme", "reference", "stats", "tutorials", "videos", "wiki", ] pages.each do |page| get page => "pages#show", id: page, as: page end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/environments/test.rb
config/environments/test.rb
# frozen_string_literal: true 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. # While tests run files are not watched, reloading is not necessary. config.enable_reloading = false # Eager loading loads your entire application. When running a single test locally, # this is usually not necessary, and can slow down your test suite. However, it's # recommended that you enable it in continuous integration systems to ensure eager # loading is working properly before deploying your code. config.eager_load = ENV["CI"].present? # 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 # Render exception templates for rescuable exceptions and raise for other exceptions. config.action_dispatch.show_exceptions = :rescuable # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false # Store uploaded files on the local file system in a temporary directory. config.active_storage.service = :test 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 # Raise error when a before_action's only/except options reference missing actions config.action_controller.raise_on_missing_callback_actions = true end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/environments/development.rb
config/environments/development.rb
# frozen_string_literal: true 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.enable_reloading = true # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable server timing config.server_timing = 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 # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # 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 = [] # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Highlight code that triggered database queries in logs. config.active_record.verbose_query_logs = true # Highlight code that enqueued background job in logs. config.active_job.verbose_enqueue_logs = true # Suppress logger output for asset requests. config.assets.quiet = true # 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 # Uncomment if you wish to allow Action Cable access from any origin. # config.action_cable.disable_request_forgery_protection = true # Raise error when a before_action's only/except options reference missing actions config.action_controller.raise_on_missing_callback_actions = true end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
marcoroth/gem.sh
https://github.com/marcoroth/gem.sh/blob/8a4a44bdd857ea79114017608d73c5cd03c21dba/config/environments/production.rb
config/environments/production.rb
# frozen_string_literal: true 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.enable_reloading = false # 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 ENV["RAILS_MASTER_KEY"], config/master.key, or an environment # key such as config/credentials/production.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from `public/`, relying on NGINX/Apache to do so instead. # config.public_file_server.enabled = false # Compress CSS using a preprocessor. # config.assets.css_compressor = :sass # Do not fall back to assets pipeline if a precompiled asset is missed. config.assets.compile = false # 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 # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # Mount Action Cable outside main process or domain. # config.action_cable.mount_path = nil # config.action_cable.url = "wss://example.com/cable" # config.action_cable.allowed_request_origins = [ "http://example.com", /http:\/\/example.*/ ] # Assume all access to the app is happening through a SSL-terminating reverse proxy. # Can be used together with config.force_ssl for Strict-Transport-Security and secure cookies. # config.assume_ssl = true # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. config.force_ssl = true # Log to STDOUT by default config.logger = ActiveSupport::Logger.new($stdout) .tap { |logger| logger.formatter = Logger::Formatter.new } .then { |logger| ActiveSupport::TaggedLogging.new(logger) } # Prepend all log lines with the following tags. config.log_tags = [:request_id] # "info" includes generic and useful information about system operation, but avoids logging too much # information to avoid inadvertent exposure of personally identifiable information (PII). If you # want to log everything, set the level to "debug". config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") # Use a different cache store in production. # config.cache_store = :mem_cache_store # 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 = "gemsh_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 # Don't log any deprecations. config.active_support.report_deprecations = false # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Enable DNS rebinding protection and other `Host` header attacks. # config.hosts = [ # "example.com", # Allow requests from example.com # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` # ] # Skip DNS rebinding protection for the default health check endpoint. # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } end
ruby
MIT
8a4a44bdd857ea79114017608d73c5cd03c21dba
2026-01-04T17:48:24.521520Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/init.rb
init.rb
require 'related'
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/test/model_test.rb
test/model_test.rb
require File.expand_path('test/test_helper') class ModelTest < ActiveModel::TestCase class Event < Related::Node property :attending_count, Integer property :popularity, Float property :start_date, DateTime property :end_date, DateTime property :location do |value| "http://maps.google.com/maps?q=#{value}" end end class Like < Related::Relationship weight do |dir| dir == :in ? in_score : out_score end end def setup Related.flushall end def test_property_conversion event = Event.create( :attending_count => 42, :popularity => 0.9, :start_date => Time.parse('2011-01-01'), :location => 'Stockholm') event = Event.find(event.id) assert_equal 42, event.attending_count assert_equal 0.9, event.popularity assert_equal Time.parse('2011-01-01'), event.start_date assert_equal Time.parse('2011-01-01').iso8601, event.read_attribute(:start_date) assert_equal nil, event.end_date assert_equal "http://maps.google.com/maps?q=Stockholm", event.location assert event.as_json.has_key?('end_date') end def test_model_factory e1 = Event.create(:popularity => 0.0) e2 = Event.create(:popularity => 1.0) e1, e2 = Related::Node.find(e1.id, e2.id, :model => lambda {|attributes| attributes['popularity'].to_f > 0.5 ? Event : Related::Node }) assert_equal Related::Node, e1.class assert_equal Event, e2.class Related::Relationship.create(:test, e1, e2) nodes = e1.outgoing(:test).nodes.options(:model => lambda {|attributes| attributes['popularity'].to_f > 0.5 ? Event : Related::Node }).to_a assert_equal Event, nodes.first.class nodes = Related::Node.find(e1.id, e2.id, model: Event) assert_equal [Event, Event], nodes.map(&:class) end def test_custom_weight node1 = Related::Node.create node2 = Related::Node.create like = Like.create(:like, node1, node2, :in_score => 42, :out_score => 10) assert_equal 42, like.weight(:in) assert_equal 10, like.weight(:out) end def test_weight_sorting node1 = Related::Node.create node2 = Related::Node.create node3 = Related::Node.create rel1 = Like.create(:like, node1, node2, :in_score => 1, :out_score => 1) rel2 = Like.create(:like, node1, node3, :in_score => 2, :out_score => 2) rel3 = Like.create(:like, node2, node1, :in_score => 1, :out_score => 1) rel4 = Like.create(:like, node3, node1, :in_score => 2, :out_score => 2) assert_equal [rel2,rel1], node1.outgoing(:like).relationships.options(:model => lambda {|a| Like }).to_a assert_equal [rel4,rel3], node1.incoming(:like).relationships.options(:model => lambda {|a| Like }).to_a assert_equal [rel1], node1.outgoing(:like).relationships.options(:model => lambda {|a| Like }).per_page(2).page(rel2).to_a assert_equal [rel3], node1.incoming(:like).relationships.options(:model => lambda {|a| Like }).per_page(2).page(rel4).to_a end end
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/test/test_helper.rb
test/test_helper.rb
dir = File.dirname(File.expand_path(__FILE__)) $LOAD_PATH.unshift dir + '/../lib' require 'rubygems' require 'bundler/setup' require 'test/unit' require 'related' require 'redis/distributed' # # make sure we can run redis # if !system("which redis-server") puts '', "** can't find `redis-server` in your path" puts "** try running `sudo rake install`" abort '' end # # start our own redis when the tests start, # kill it when they end # at_exit do next if $! if defined?(MiniTest) exit_code = MiniTest::Unit.new.run(ARGV) else exit_code = Test::Unit::AutoRunner.run end puts "Killing test redis server..." loop do pid = `ps -A -o pid,command | grep [r]edis-test`.split(" ")[0] break if pid.nil? Process.kill("KILL", pid.to_i) end `rm -f #{dir}/*.rdb` exit exit_code end puts "Starting redis for testing..." # `redis-server #{dir}/redis-test-1.conf` # Related.redis = 'localhost:6379' `redis-server #{dir}/redis-test-1.conf` `redis-server #{dir}/redis-test-2.conf` `redis-server #{dir}/redis-test-3.conf` `redis-server #{dir}/redis-test-4.conf` Related.redis = Redis::Distributed.new %w[ redis://localhost:6379 redis://localhost:6380 redis://localhost:6381 redis://localhost:6382], :tag => /^related:([^:]+)/
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/test/custom_id_attribute_test.rb
test/custom_id_attribute_test.rb
require File.expand_path('test/test_helper') class CustomIdAttribute < ActiveModel::TestCase class FakeThing < Related::Node property :id, Integer property :name, String end def setup Related.flushall end def test_manually_set_id FakeThing.create(id: 42, name: "Bond, James Bond") found = FakeThing.find(42) assert_equal 42, found.id assert_equal "Bond, James Bond", found.name end def test_unique_ids FakeThing.create(id: 42, name: "Bond, James Bond") assert_raise Related::ValidationsFailed do FakeThing.create(id: 42, name: "Black Bears") end found = FakeThing.find(42) assert_equal 42, found.id assert_equal "Bond, James Bond", found.name end end
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/test/follower_test.rb
test/follower_test.rb
require File.expand_path('test/test_helper') require 'related/follower' class User < Related::Node include Related::Follower end class FollowerTest < MiniTest::Unit::TestCase def setup Related.flushall @user1 = User.create @user2 = User.create end def test_can_follow @user1.follow!(@user2) assert @user1.following?(@user2) assert @user2.followed_by?(@user1) end def test_can_unfollow @user1.follow!(@user2) @user1.unfollow!(@user2) assert_equal false, @user1.following?(@user2) end def test_can_count_followers_and_following @user1.follow!(@user2) assert_equal 1, @user1.following_count assert_equal 0, @user1.followers_count assert_equal 0, @user2.following_count assert_equal 1, @user2.followers_count end def test_can_compute_friends @user1.follow!(@user2) @user2.follow!(@user1) assert_equal [@user2], @user1.friends.to_a assert_equal [@user1], @user2.friends.to_a end end
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/test/data_flow_test.rb
test/data_flow_test.rb
require File.expand_path('test/test_helper') class ModelTest < ActiveModel::TestCase class StepOne def self.perform(data) yield({ :text => data['text'] }) end end class StepTwo def self.perform(data) yield({ :id => 'StepTwo', :text => data['text'].downcase }) end end class StepThree def self.perform(data) yield({ :id => 'StepThree', :text => data['text'].upcase }) end end class LastStep def self.perform(data) Related.redis.set("DataFlowResult#{data['id']}", data['text']) end end def setup Related.flushall end def teardown Related.clear_data_flows end def test_defining_a_data_flow Related.data_flow :like, StepOne => { StepTwo => nil } assert_equal({ :like => [{ StepOne => { StepTwo => nil } }] }, Related.data_flows) end def test_executing_a_simple_data_flow Related.data_flow :like, StepOne => { LastStep => nil } Related::Relationship.create(:like, Related::Node.create, Related::Node.create, :text => 'Hello world!') assert_equal 'Hello world!', Related.redis.get('DataFlowResult') end def test_executing_a_complicated_data_flow Related.data_flow :like, StepOne => { StepTwo => { LastStep => nil }, StepThree => { LastStep => nil } } Related::Relationship.create(:like, Related::Node.create, Related::Node.create, :text => 'Hello world!') assert_equal 'hello world!', Related.redis.get('DataFlowResultStepTwo') assert_equal 'HELLO WORLD!', Related.redis.get('DataFlowResultStepThree') end end
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/test/related_test.rb
test/related_test.rb
require File.expand_path('test/test_helper') class RelatedTest < MiniTest::Unit::TestCase def setup Related.flushall end def test_can_set_a_namespace_through_a_url_like_string assert Related.redis assert_equal :related, Related.redis.namespace old_redis = Related.redis Related.redis = 'localhost:9736/namespace' assert_equal 'namespace', Related.redis.namespace Related.redis = old_redis end def test_can_create_node assert Related::Node.create end def test_can_create_node_with_attributes node = Related::Node.create(:name => 'Example', :popularity => 12.3) assert node assert_equal 'Example', node.name assert_equal 12.3, node.popularity end def test_can_create_node_and_then_find_it_again_using_its_id node1 = Related::Node.create(:name => 'Example', :popularity => 12.3) node2 = Related::Node.find(node1.id) assert node2 assert_equal node1.id, node2.id assert_equal 'Example', node2.name assert_equal '12.3', node2.popularity end def test_can_find_many_nodes_at_the_same_time node1 = Related::Node.create(:name => 'One') node2 = Related::Node.create(:name => 'Two') one, two = Related::Node.find(node1.id, node2.id) assert one assert two end def test_will_raise_exception_when_a_node_is_not_found assert_raises Related::NotFound do Related::Node.find('foo') end assert_raises Related::NotFound do Related::Node.find(nil) end end def test_can_update_node_with_new_attributes node1 = Related::Node.create(:name => 'Example', :popularity => 12.3) node1.description = 'Example description.' node1.save node2 = Related::Node.find(node1.id) assert_equal node1.description, node2.description end def test_two_nodes_with_the_same_id_should_be_equal assert_equal Related::Node.new.send(:load_attributes, 'test', {}), Related::Node.new.send(:load_attributes, 'test', {}) end def test_can_find_a_node_and_only_load_specific_attributes node1 = Related::Node.create(:name => 'Example', :popularity => 12.3) node2 = Related::Node.find(node1.id, :fields => [:does_not_exist, :name]) assert_equal node1.name, node2.name assert_nil node2.does_not_exist assert_nil node2.popularity end def test_can_find_multiple_nodes_and_only_load_specific_attributes node1 = Related::Node.create(:name => 'Example 1', :popularity => 12.3) node2 = Related::Node.create(:name => 'Example 2', :popularity => 42.5) n = Related::Node.find(node1.id, node2.id, :fields => [:does_not_exist, :name]) assert_equal 2, n.size assert_equal 'Example 1', n.first.name assert_nil n.first.does_not_exist assert_nil n.first.popularity assert_equal 'Example 2', n.last.name assert_nil n.last.does_not_exist assert_nil n.last.popularity end def test_can_destroy_node node = Related::Node.create node.destroy assert_raises Related::NotFound do Related::Node.find(node.id) end end def test_can_create_a_relationship_between_two_nodes node1 = Related::Node.create(:name => 'One') node2 = Related::Node.create(:name => 'Two') rel = Related::Relationship.create(:friends, node1, node2) assert_equal [rel], node1.outgoing(:friends).relationships.to_a assert_equal [node2], node1.outgoing(:friends).to_a assert_equal [], node1.incoming(:friends).to_a assert_equal [node1], node2.incoming(:friends).to_a assert_equal [], node2.outgoing(:friends).to_a end def test_can_create_a_relationship_with_attributes node1 = Related::Node.create(:name => 'One') node2 = Related::Node.create(:name => 'Two') rel = Related::Relationship.create(:friends, node1, node2, :score => 2.5) rel = Related::Relationship.find(rel.id) assert_equal '2.5', rel.score end def test_can_delete_a_relationship node1 = Related::Node.create(:name => 'One') node2 = Related::Node.create(:name => 'Two') rel = Related::Relationship.create(:friends, node1, node2) rel.destroy assert_equal [], node1.outgoing(:friends).to_a assert_equal [], node1.incoming(:friends).to_a assert_equal [], node2.incoming(:friends).to_a assert_equal [], node2.outgoing(:friends).to_a assert_raises Related::NotFound do Related::Relationship.find(rel.id) end end def test_can_limit_the_number_of_nodes_returned_from_a_query node1 = Related::Node.create node2 = Related::Node.create node3 = Related::Node.create node4 = Related::Node.create node5 = Related::Node.create Related::Relationship.create(:friends, node1, node2) Related::Relationship.create(:friends, node1, node3) Related::Relationship.create(:friends, node1, node4) Related::Relationship.create(:friends, node1, node5) assert_equal 3, node1.outgoing(:friends).nodes.limit(3).to_a.size assert_equal 3, node1.outgoing(:friends).relationships.limit(3).to_a.size end def test_can_paginate_the_results_from_a_query node1 = Related::Node.create node2 = Related::Node.create node3 = Related::Node.create node4 = Related::Node.create node5 = Related::Node.create node6 = Related::Node.create rel1 = Related::Relationship.create(:friends, node1, node2, :name => 'rel1') sleep(1) rel2 = Related::Relationship.create(:friends, node1, node3, :name => 'rel2') sleep(1) rel3 = Related::Relationship.create(:friends, node1, node4, :name => 'rel3') sleep(1) rel4 = Related::Relationship.create(:friends, node1, node5, :name => 'rel4') sleep(1) rel5 = Related::Relationship.create(:friends, node1, node6, :name => 'rel5') assert_equal [rel5,rel4,rel3], node1.outgoing(:friends).per_page(3).page(1).to_a assert_equal [rel2,rel1], node1.outgoing(:friends).per_page(3).page(2).to_a assert_equal [rel5,rel4,rel3], node1.outgoing(:friends).per_page(3).page(nil).to_a assert_equal [rel4,rel3,rel2], node1.outgoing(:friends).per_page(3).page(rel5).to_a assert_equal [rel2,rel1], node1.outgoing(:friends).per_page(3).page(rel3).to_a end def test_can_count_the_number_of_related_nodes node1 = Related::Node.create node2 = Related::Node.create node3 = Related::Node.create node4 = Related::Node.create node5 = Related::Node.create rel1 = Related::Relationship.create(:friends, node1, node2) rel1 = Related::Relationship.create(:friends, node1, node3) rel1 = Related::Relationship.create(:friends, node1, node4) rel1 = Related::Relationship.create(:friends, node1, node5) assert_equal 4, node1.outgoing(:friends).nodes.count assert_equal 4, node1.outgoing(:friends).nodes.size assert_equal 3, node1.outgoing(:friends).nodes.limit(3).count assert_equal 4, node1.outgoing(:friends).nodes.limit(5).count assert_equal 4, node1.outgoing(:friends).relationships.count assert_equal 4, node1.outgoing(:friends).relationships.size assert_equal 3, node1.outgoing(:friends).relationships.limit(3).count assert_equal 4, node1.outgoing(:friends).relationships.limit(5).count end def test_can_find_path_between_two_nodes node1 = Related::Node.create node2 = Related::Node.create node3 = Related::Node.create node4 = Related::Node.create node5 = Related::Node.create node6 = Related::Node.create node7 = Related::Node.create node8 = Related::Node.create rel1 = Related::Relationship.create(:friends, node1, node2) rel1 = Related::Relationship.create(:friends, node2, node3) rel1 = Related::Relationship.create(:friends, node3, node2) rel1 = Related::Relationship.create(:friends, node3, node4) rel1 = Related::Relationship.create(:friends, node4, node5) rel1 = Related::Relationship.create(:friends, node5, node3) rel1 = Related::Relationship.create(:friends, node5, node8) rel1 = Related::Relationship.create(:friends, node2, node5) rel1 = Related::Relationship.create(:friends, node2, node6) rel1 = Related::Relationship.create(:friends, node6, node7) rel1 = Related::Relationship.create(:friends, node7, node8) assert_equal node8, node1.path_to(node8).outgoing(:friends).depth(5).to_a.last assert_equal node1, node1.path_to(node8).outgoing(:friends).depth(5).include_start_node.to_a.first assert_equal node1, node8.path_to(node1).incoming(:friends).depth(5).to_a.last assert_equal node8, node8.path_to(node1).incoming(:friends).depth(5).include_start_node.to_a.first end def test_can_find_shortest_path_between_two_nodes node1 = Related::Node.create node2 = Related::Node.create node3 = Related::Node.create node4 = Related::Node.create node5 = Related::Node.create node6 = Related::Node.create node7 = Related::Node.create node8 = Related::Node.create rel1 = Related::Relationship.create(:friends, node1, node2) rel1 = Related::Relationship.create(:friends, node2, node3) rel1 = Related::Relationship.create(:friends, node3, node2) rel1 = Related::Relationship.create(:friends, node3, node4) rel1 = Related::Relationship.create(:friends, node4, node5) rel1 = Related::Relationship.create(:friends, node5, node3) rel1 = Related::Relationship.create(:friends, node5, node8) rel1 = Related::Relationship.create(:friends, node2, node5) rel1 = Related::Relationship.create(:friends, node2, node6) rel1 = Related::Relationship.create(:friends, node6, node7) rel1 = Related::Relationship.create(:friends, node7, node8) assert_equal [node2,node5,node8], node1.shortest_path_to(node8).outgoing(:friends).depth(5).to_a assert_equal [node1,node2,node5,node8], node1.shortest_path_to(node8).outgoing(:friends).depth(5).include_start_node.to_a end def test_can_union node1 = Related::Node.create node2 = Related::Node.create node3 = Related::Node.create node4 = Related::Node.create Related::Relationship.create(:friends, node1, node3) Related::Relationship.create(:friends, node2, node4) Related::Relationship.create(:friends, node2, node3) nodes = node1.outgoing(:friends).union(node2.outgoing(:friends)).to_a assert_equal 2, nodes.size assert nodes.include?(node3) assert nodes.include?(node4) end def test_can_diff node1 = Related::Node.create node2 = Related::Node.create node3 = Related::Node.create node4 = Related::Node.create Related::Relationship.create(:friends, node1, node3) Related::Relationship.create(:friends, node2, node4) Related::Relationship.create(:friends, node2, node3) nodes = node2.outgoing(:friends).diff(node1.outgoing(:friends)).to_a assert_equal 1, nodes.size assert nodes.include?(node4) end def test_can_intersect node1 = Related::Node.create node2 = Related::Node.create Related::Relationship.create(:friends, node1, node2) Related::Relationship.create(:friends, node2, node1) assert_equal [node2], node1.outgoing(:friends).intersect(node1.incoming(:friends)).to_a assert_equal [node1], node2.outgoing(:friends).intersect(node2.incoming(:friends)).to_a node3 = Related::Node.create Related::Relationship.create(:friends, node1, node3) assert_equal [node1], node2.incoming(:friends).intersect(node3.incoming(:friends)).to_a end def test_timestamps node = Related::Node.create.save node = Related::Node.find(node.id) assert_match /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ$/, node.created_at assert_match /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ$/, node.updated_at end def test_should_require_a_relationship_to_have_a_label_start_node_and_end_node assert_raises Related::ValidationsFailed do Related::Relationship.create(nil, 'x', 'y') end assert_raises Related::ValidationsFailed do Related::Relationship.create(:friend, nil, 'y') end assert_raises Related::ValidationsFailed do Related::Relationship.create(:friend, 'x', nil) end end def test_root assert_kind_of Related::Node, Related.root node = Related::Node.create rel = Related::Relationship.create(:friend, Related.root, node) assert_equal [node], Related.root.outgoing(:friend).to_a Related.root.name = 'Test' Related.root.save end def test_find node1 = Related::Node.create node2 = Related::Node.create rel = Related::Relationship.create(:friend, node1, node2) assert_equal node2, node1.outgoing(:friend).find(node2) assert_equal node1, node2.incoming(:friend).find(node1) assert_equal nil, node1.outgoing(:friend).find(node1) assert_equal nil, node2.incoming(:friend).find(node2) assert_equal rel, node1.outgoing(:friend).relationships.find(node2) assert_equal rel, node2.incoming(:friend).relationships.find(node1) assert_equal nil, node1.outgoing(:friend).relationships.find(node1) assert_equal nil, node2.incoming(:friend).relationships.find(node2) end def test_can_increment_and_decrement node = Related::Node.create(:test => 1) assert_equal 1, Related::Node.find(node.id).test.to_i node.increment!(:test, 5) assert_equal 6, Related::Node.find(node.id).test.to_i node.decrement!(:test, 4) assert_equal 2, Related::Node.find(node.id).test.to_i end def test_can_increment_and_decrement_relationship_weights node1 = Related::Node.create node2 = Related::Node.create rel = Related::Relationship.create(:friend, node1, node2) original_in_weight = Related::Relationship.find(rel.id).weight(:in) rel.increment_weight!(:in, 4.2) assert_equal original_in_weight + 4.2, Related::Relationship.find(rel.id).weight(:in) rel.decrement_weight!(:in, 2.2) assert_equal original_in_weight + 2.0, Related::Relationship.find(rel.id).weight(:in) original_out_weight = Related::Relationship.find(rel.id).weight(:out) rel.increment_weight!(:out, 5.2) assert_equal original_out_weight + 5.2, Related::Relationship.find(rel.id).weight(:out) rel.decrement_weight!(:out, 4.2) assert_equal original_out_weight + 1.0, Related::Relationship.find(rel.id).weight(:out) end end
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/test/custom_node_test.rb
test/custom_node_test.rb
require File.expand_path('test/test_helper') require 'pp' class CustomNodeTest < ActiveModel::TestCase class CustomNode include Related::Node::QueryMethods attr_accessor :id def self.flush @database = {} end def self.create n = self.new n.id = Related.generate_id @database ||= {} @database[n.id] = n n end def self.find(*ids) ids.pop if ids.size > 1 && ids.last.is_a?(Hash) ids.flatten.map do |id| @database[id] end end def to_s @id end protected def query Related::Node::Query.new(self) end end def setup Related.flushall CustomNode.flush end def test_property_conversion node1 = CustomNode.create node2 = CustomNode.create Related::Relationship.create(:friend, node1, node2) assert_equal [node2], node1.shortest_path_to(node2).outgoing(:friend).nodes.to_a end end
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/test/active_model_test.rb
test/active_model_test.rb
require File.expand_path('test/test_helper') class ActiveModelTest < ActiveModel::TestCase include ActiveModel::Lint::Tests class Like < Related::Entity validates_numericality_of :how_much, :allow_nil => true before_save :before_save_callback after_save :after_save_callback before_create :before_create_callback after_create :after_create_callback before_update :before_update_callback after_update :after_update_callback before_destroy :before_destroy_callback after_destroy :after_destroy_callback attr_reader :before_save_was_called attr_reader :after_save_was_called attr_reader :before_create_was_called attr_reader :after_create_was_called attr_reader :before_update_was_called attr_reader :after_update_was_called attr_reader :before_destroy_was_called attr_reader :after_destroy_was_called def before_save_callback @before_save_was_called = true end def after_save_callback @after_save_was_called = true end def before_create_callback @before_create_was_called = true end def after_create_callback @after_create_was_called = true end def before_update_callback @before_update_was_called = true end def after_update_callback @after_update_was_called = true end def before_destroy_callback @before_destroy_was_called = true end def after_destroy_callback @after_destroy_was_called = true end end def setup Related.flushall @model = Related::Entity.new end def test_attributes_has_id node = Related::Entity.create assert_equal node.id, node.attributes['id'] end def test_can_return_json node = Related::Entity.create(:name => 'test') json = { :node => node }.to_json json = JSON.parse(json) assert_equal node.id, json['node']['id'] assert_equal node.name, json['node']['name'] end def test_query_can_return_json node1 = Related::Node.create(:name => 'node1') node2 = Related::Node.create(:name => 'node2') Related::Relationship.create(:friends, node1, node2) json = { :nodes => node1.outgoing(:friends) }.to_json json = JSON.parse(json) assert_equal node2.id, json['nodes'][0]['id'] assert_equal node2.name, json['nodes'][0]['name'] end def test_validations like = Like.new(:how_much => 'not much') assert_equal false, like.valid? assert_equal [:how_much], like.errors.messages.keys assert_raises Related::ValidationsFailed do like.save end begin like.save rescue Related::ValidationsFailed => e assert_equal like, e.object end like.how_much = 1.0 assert_equal true, like.valid? assert_nothing_raised do like.save end end def test_save_callbacks like = Like.new assert_equal nil, like.before_save_was_called assert_equal nil, like.after_save_was_called like.save assert_equal true, like.before_save_was_called assert_equal true, like.after_save_was_called end def test_create_callbacks like = Like.new assert_equal nil, like.before_create_was_called assert_equal nil, like.after_create_was_called like.save assert_equal true, like.before_create_was_called assert_equal true, like.after_create_was_called end def test_update_callbacks like = Like.new like.save assert_equal nil, like.before_update_was_called assert_equal nil, like.after_update_was_called like.save assert_equal true, like.before_update_was_called assert_equal true, like.after_update_was_called end def test_create_callbacks like = Like.new assert_equal nil, like.before_destroy_was_called assert_equal nil, like.after_destroy_was_called like.destroy assert_equal true, like.before_destroy_was_called assert_equal true, like.after_destroy_was_called end end
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/test/performance_test.rb
test/performance_test.rb
require File.expand_path('test/test_helper') require 'benchmark' class PerformanceTest < MiniTest::Unit::TestCase def setup Related.flushall end def test_simple puts "Simple:" node = Related::Node.create time = Benchmark.measure do 1000.times do n = Related::Node.create rel = Related::Relationship.create(:friends, node, n) end end puts time time = Benchmark.measure do node.outgoing(:friends).to_a end puts time end def test_with_attributes puts "With attributes:" node = Related::Node.create time = Benchmark.measure do 1000.times do n = Related::Node.create( :title => 'Example title', :description => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', :status => 'archived', :length => 42.3, :enabled => true) rel = Related::Relationship.create(:friends, node, n, :weight => 2.5, :list => 'Co-workers') end end puts time time = Benchmark.measure do node.outgoing(:friends).to_a end puts time end def test_search puts "Search:" node = Related::Node.create time = Benchmark.measure do 10.times do n = Related::Node.create rel = Related::Relationship.create(:friends, node, n) 10.times do n2 = Related::Node.create rel2 = Related::Relationship.create(:friends, n, n2) 10.times do n3 = Related::Node.create rel3 = Related::Relationship.create(:friends, n2, n3) 10.times do n4 = Related::Node.create rel4 = Related::Relationship.create(:friends, n3, n4) end end end end end puts time time = Benchmark.measure do node.outgoing(:friends).path_to(Related::Node.create) end puts time end end
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/lib/related.rb
lib/related.rb
require 'redis' require 'redis/namespace' require 'active_model' require 'related/version' require 'related/helpers' require 'related/exceptions' require 'related/validations/check_redis_uniqueness' require 'related/entity' require 'related/node' require 'related/relationship' require 'related/root' require 'related/data_flow' module Related include Helpers include DataFlow extend self # Accepts: # 1. A 'hostname:port' string # 2. A 'hostname:port:db' string (to select the Redis db) # 3. A 'hostname:port/namespace' string (to set the Redis namespace) # 4. A redis URL string 'redis://host:port' # 5. An instance of `Redis`, `Redis::Client`, `Redis::Distributed`, # or `Redis::Namespace`. def redis=(server) if server.is_a? String if server =~ /redis\:\/\// redis = Redis.connect(:url => server) else server, namespace = server.split('/', 2) host, port, db = server.split(':') redis = Redis.new(:host => host, :port => port, :thread_safe => true, :db => db) end namespace ||= :related @redis = Redis::Namespace.new(namespace, :redis => redis) elsif server.respond_to? :namespace= @redis = server else @redis = Redis::Namespace.new(:related, :redis => server) end end # Returns the current Redis connection. If none has been created, will # create a new one. def redis return @redis if @redis self.redis = ENV['RELATED_REDIS_URL'] || ENV['REDIS_URL'] || 'localhost:6379' self.redis end def flushall self.redis.redis.flushall end end
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/lib/related/follower.rb
lib/related/follower.rb
module Related module Follower def follow!(other) Related::Relationship.create(:follow, self, other) end def unfollow!(other) rel = self.following.relationships.find(other) rel.destroy if rel end def followers self.incoming(:follow) end def following self.outgoing(:follow) end def friends self.followers.intersect(self.following) end def followed_by?(other) self.followers.include?(other) end def following?(other) self.following.include?(other) end def followers_count self.followers.size end def following_count self.following.size end end end
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/lib/related/version.rb
lib/related/version.rb
module Related Version = VERSION = '0.6.6' end
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/lib/related/exceptions.rb
lib/related/exceptions.rb
module Related class RelatedException < RuntimeError; end class NotFound < RelatedException; end class InvalidQuery < RelatedException; end class ValidationsFailed < RelatedException attr_reader :object def initialize(object) @object = object errors = @object.errors.full_messages.to_sentence super(errors) end end end
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/lib/related/relationship.rb
lib/related/relationship.rb
module Related class Relationship < Entity validates_presence_of :label, :start_node_id, :end_node_id def initialize(*attributes) @_internal_id = attributes.first.is_a?(String) ? attributes.first : Related.generate_id @attributes = attributes.last end def start_node @start_node ||= Related::Node.find(start_node_id) end def end_node @end_node ||= Related::Node.find(end_node_id) end def rank(direction) Related.redis.zrevrank(r_key(direction), self.id) end def weight(direction) Related.redis.zscore(r_key(direction), self.id).to_f end def increment_weight!(direction, by = 1) Related.redis.zincrby(r_key(direction), by.to_f, self.id) end def decrement_weight!(direction, by = 1) Related.redis.zincrby(r_key(direction), -by.to_f, self.id) end def self.weight(&block) @weight = block end def self.create(label, node1, node2, attributes = {}) self.new(attributes.merge( :label => label, :start_node_id => node1.is_a?(String) ? node1 : (node1 ? node1.id : nil), :end_node_id => node2.is_a?(String) ? node2 : (node2 ? node2.id : nil) )).save end private def r_key(direction) if direction.to_sym == :out "#{self.start_node_id}:r:#{self.label}:out" elsif direction.to_sym == :in "#{self.end_node_id}:r:#{self.label}:in" end end def n_key(direction) if direction.to_sym == :out "#{self.start_node_id}:n:#{self.label}:out" elsif direction.to_sym == :in "#{self.end_node_id}:n:#{self.label}:in" end end def dir_key "#{self.start_node_id}:#{self.label}:#{self.end_node_id}" end def self.weight_for(relationship, direction) if @weight relationship.instance_exec(direction, &@weight).to_i else Time.now.to_f end end def create #Related.redis.multi do super Related.redis.zadd(r_key(:out), self.class.weight_for(self, :out), self.id) Related.redis.zadd(r_key(:in), self.class.weight_for(self, :in), self.id) Related.redis.sadd(n_key(:out), self.end_node_id) Related.redis.sadd(n_key(:in), self.start_node_id) Related.redis.set(dir_key, self.id) #end Related.execute_data_flow(self.label, self) self end def update super Related.execute_data_flow(self.label, self) self end def delete #Related.redis.multi do Related.redis.zrem(r_key(:out), self.id) Related.redis.zrem(r_key(:in), self.id) Related.redis.srem(n_key(:out), self.end_node_id) Related.redis.srem(n_key(:in), self.start_node_id) Related.redis.del(dir_key) super #end Related.execute_data_flow(self.label, self) self end end end
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/lib/related/node.rb
lib/related/node.rb
module Related class Node < Entity module QueryMethods def relationships query = self.query query.result_type = :relationships query end def nodes query = self.query query.result_type = :nodes query end def options(opt) query = self.query query.options = opt query end def outgoing(type) query = self.query query.relationship_type = type query.direction = :out query end def incoming(type) query = self.query query.relationship_type = type query.direction = :in query end def limit(count) query = self.query query.limit = count query end def per_page(count) self.limit(count) end def page(nr) query = self.query query.page = nr query.result_type = :relationships query end def depth(depth) query = self.query query.depth = depth query end def include_start_node query = self.query query.include_start_node = true query end def path_to(node) query = self.query query.destination = node query.search_algorithm = :depth_first query end def shortest_path_to(node) query = self.query query.destination = node query.search_algorithm = :dijkstra query end end include QueryMethods module DistributedFallback def union(query) super(query) rescue Redis::Distributed::CannotDistribute s1 = Related.redis.smembers(key) s2 = Related.redis.smembers(query.key) @result = s1 | s2 self end def diff(query) super(query) rescue Redis::Distributed::CannotDistribute s1 = Related.redis.smembers(key) s2 = Related.redis.smembers(query.key) @result = s1 - s2 self end def intersect (query) super(query) rescue Redis::Distributed::CannotDistribute s1 = Related.redis.smembers(key) s2 = Related.redis.smembers(query.key) @result = s1 & s2 self end end class Query prepend DistributedFallback include QueryMethods attr_reader :result attr_writer :result_type attr_writer :relationship_type attr_writer :direction attr_writer :limit attr_writer :page attr_writer :depth attr_writer :include_start_node attr_writer :destination attr_writer :search_algorithm attr_writer :options def initialize(node) @node = node @result_type = :nodes @depth = 4 @options = {} end def each(&block) self.to_a.each(&block) end def map(&block) self.to_a.map(&block) end def to_a perform_query unless @result if @result_type == :nodes node_class.find(@result, @options) else Related::Relationship.find(@result, @options) end end def count @count = @result_type == :nodes ? Related.redis.scard(key) : Related.redis.zcard(key) @limit && @count > @limit ? @limit : @count end def size @count || count end def include?(entity) if @destination self.to_a.include?(entity) else if entity.is_a?(node_class) @result_type = :nodes Related.redis.sismember(key, entity.id) elsif entity.is_a?(Related::Relationship) @result_type = :relationships Related.redis.sismember(key, entity.id) end end end def find(node) if @result_type == :nodes if Related.redis.sismember(key, node.id) node_class.find(node.id, @options) end else if id = Related.redis.get(dir_key(node)) Related::Relationship.find(id, @options) end end end def union(query) @result_type = :nodes @result = Related.redis.sunion(key, query.key) self end def diff(query) @result_type = :nodes @result = Related.redis.sdiff(key, query.key) self end def intersect(query) @result_type = :nodes @result = Related.redis.sinter(key, query.key) self end def as_json(options = {}) self.to_a end def to_json(options = {}) self.as_json.to_json(options) end protected def node_class @node.class end def page_start if @page.nil? || @page.to_i.to_s == @page.to_s @page && @page.to_i != 1 ? (@page.to_i * @limit.to_i) - @limit.to_i : 0 else rel = @page.is_a?(String) ? Related::Relationship.find(@page) : @page rel.rank(@direction) + 1 end end def page_end page_start + @limit.to_i - 1 end def key(node=nil) n = node || @node node_id = n.is_a?(String) ? n : n.id "#{node_id}:#{@result_type == :nodes ? "n" : "r"}:#{@relationship_type}:#{@direction}" end def dir_key(node) if @direction == :out "#{@node.id}:#{@relationship_type}:#{node.id}" elsif @direction == :in "#{node.id}:#{@relationship_type}:#{@node.id}" end end def query self end def perform_query @result = [] if @destination @result_type = :nodes @result = self.send(@search_algorithm, [@node.id]) @result.shift unless @include_start_node @result else if @result_type == :nodes if @limit @result = (1..@limit.to_i).map { Related.redis.srandmember(key) } else @result = Related.redis.smembers(key) end else if @limit @result = Related.redis.zrevrange(key, page_start, page_end) else @result = Related.redis.zrevrange(key, 0, -1) end end end end def depth_first(nodes, depth = 0) return [] if depth > @depth nodes.each do |node| if Related.redis.sismember(key(node), @destination.id) return [node, @destination.id] else res = depth_first(Related.redis.smembers(key(node)), depth+1) return [node] + res unless res.empty? end end return [] end def dijkstra(nodes, depth = 0) return [] if depth > @depth shortest_path = [] nodes.each do |node| if Related.redis.sismember(key(node), @destination.id) return [node, @destination.id] else res = dijkstra(Related.redis.smembers(key(node)), depth+1) if res.size > 0 res = [node] + res if res.size < shortest_path.size || shortest_path.size == 0 shortest_path = res end end end end return shortest_path end end protected def query Query.new(self) end end end
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/lib/related/entity.rb
lib/related/entity.rb
module Related class Entity extend ActiveModel::Naming extend ActiveModel::Callbacks include ActiveModel::Conversion include ActiveModel::Validations include ActiveModel::Serializers::JSON include ActiveModel::Serializers::Xml include ActiveModel::Translation include ActiveModel::AttributeMethods include ActiveModel::Dirty self.include_root_in_json = false define_model_callbacks :create, :update, :destroy, :save attr_reader :id attr_reader :attributes validates_with CheckRedisUniqueness, on: :create def initialize(attributes = {}) @attributes = {} @_internal_id = attributes.delete(:id) || Related.generate_id attributes.each do |key,value| serializer = self.class.property_serializer(key) @attributes[key.to_s] = serializer ? serializer.to_string(value) : value end end def to_s self.id end def attributes @attributes ||= {} self.class.properties.inject({}) { |memo,key| memo[key.to_s] = nil memo }.merge(@attributes.inject({}) { |memo,(k,v)| memo[k.to_s] = v memo }.merge('id' => self.id)) end def attribute(name) read_attribute(name) end def read_attribute(name) @attributes ||= {} @attributes[name.to_s] || @attributes[name] end def write_attribute(name, value) @attributes ||= {} @attributes[name.to_s] = value end def has_attribute?(name) @attributes ||= {} @attributes.has_key?(name.to_s) || @attributes.has_key?(name) || @properties.has_key?(name.to_sym) end def method_missing(sym, *args, &block) if sym.to_s =~ /=$/ name = sym.to_s[0..-2] serializer = self.class.property_serializer(name) write_attribute(name, serializer ? serializer.to_string(args.first) : args.first) else serializer = self.class.property_serializer(sym) serializer ? serializer.from_string(read_attribute(sym)) : read_attribute(sym) end end def ==(other) other.is_a?(Related::Entity) && self.to_key == other.to_key end def new? @id.nil? ? true : false end alias new_record? new? def persisted? !new? end def destroyed? @destroyed end def save create_or_update end def destroy delete end def self.create(attributes = {}) self.new(attributes).save end def self.find(*args) options = args.size > 1 && args.last.is_a?(Hash) ? args.pop : {} args.size == 1 && !args.first.is_a?(Array) ? find_one(args.first, options) : find_many(args.flatten, options) end def self.property(name, klass=nil, &block) @properties ||= {} @properties[name.to_sym] = Serializer.new(klass, block) end def self.properties @properties ? @properties.keys : [] end def self.increment!(id, attribute, by = 1) raise Related::NotFound if id.blank? Related.redis.hincrby(id.to_s, attribute.to_s, by.to_i) end def self.decrement!(id, attribute, by = 1) raise Related::NotFound if id.blank? Related.redis.hincrby(id.to_s, attribute.to_s, -by.to_i) end def increment!(attribute, by = 1) self.class.increment!(@id, attribute, by) end def decrement!(attribute, by = 1) self.class.decrement!(@id, attribute, by) end private def load_attributes(id, attributes) @id = id @attributes = attributes self end def create_or_update run_callbacks :save do new? ? create : update end end def create run_callbacks :create do raise Related::ValidationsFailed, self unless valid?(:create) @id = @_internal_id @attributes.merge!('created_at' => Time.now.utc.iso8601) Related.redis.hmset(@id, *@attributes.to_a.flatten) end self end def update run_callbacks :update do raise Related::ValidationsFailed, self unless valid?(:update) @attributes.merge!('updated_at' => Time.now.utc.iso8601) Related.redis.hmset(@id, *@attributes.to_a.flatten) end self end def delete run_callbacks :destroy do Related.redis.del(id) @destroyed = true end self end def self.find_fields(id, fields) res = Related.redis.hmget(id.to_s, *fields) if res attributes = {} res.each_with_index do |value, i| attributes[fields[i]] = value end attributes end end def self.find_one(id, options = {}) attributes = options[:fields] ? find_fields(id, options[:fields]) : Related.redis.hgetall(id.to_s) if attributes.empty? if Related.redis.exists(id) == false raise Related::NotFound, id end end klass = get_model(options[:model], attributes) klass.new.send(:load_attributes, id, attributes) end def self.find_many(ids, options = {}) res = pipelined_fetch(ids) do |id| if options[:fields] Related.redis.hmget(id.to_s, *options[:fields]) else Related.redis.hgetall(id.to_s) end end objects = [] ids.each_with_index do |id,i| if options[:fields] attributes = {} res[i].each_with_index do |value, i| attributes[options[:fields][i]] = value end klass = get_model(options[:model], attributes) objects << klass.new.send(:load_attributes, id, attributes) else attributes = res[i].is_a?(Array) ? Hash[*res[i]] : res[i] klass = get_model(options[:model], attributes) objects << klass.new.send(:load_attributes, id, attributes) end end objects end def self.get_model(model, attributes) return self unless model model.is_a?(Proc) ? model.call(attributes) : model end def self.pipelined_fetch(ids, &block) Related.redis.pipelined do ids.each do |id| block.call(id) end end rescue Redis::Distributed::CannotDistribute ids.map do |id| block.call(id) end end def self.property_serializer(property) @properties ||= {} @properties[property.to_sym] end class Serializer def initialize(klass, block = nil) @klass = klass @block = block end def to_string(value) case @klass.to_s when 'DateTime', 'Time' value.iso8601 else value.to_s end end def from_string(value) value = case @klass.to_s when 'String' value.to_s when 'Integer' value.to_i when 'Float' value.to_f when 'DateTime', 'Time' Time.parse(value) else value end unless value.nil? @block ? @block.call(value) : value end end end end
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/lib/related/data_flow.rb
lib/related/data_flow.rb
module Related module DataFlow def data_flow(name, steps) @data_flows ||= {} @data_flows[name.to_sym] ||= [] @data_flows[name.to_sym] << steps end def data_flows @data_flows end def clear_data_flows @data_flows = {} end def execute_data_flow(name_or_flow, data) @data_flows ||= {} if name_or_flow.is_a?(Hash) enqueue_flow(name_or_flow, data) else flows = @data_flows[name_or_flow.to_sym] || [] flows.each do |flow| enqueue_flow(flow, data) end end end class DataFlowJob @queue = :related def self.perform(flow, data) flow.keys.each do |key| step = key.constantize step.perform(data) do |result| if flow[key] Related.execute_data_flow(flow[key], result) end end end end end protected def enqueue_flow(flow, data) if defined?(Resque) Resque.enqueue(DataFlowJob, flow, data) else DataFlowJob.perform(JSON.parse(flow.to_json), JSON.parse(data.to_json)) end end end end
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/lib/related/helpers.rb
lib/related/helpers.rb
require 'base64' require 'digest/md5' module Related module Helpers # Generate a unique id def generate_id Base64.encode64( Digest::MD5.digest("#{Time.now}-#{rand}") ).gsub('/','x').gsub('+','y').gsub('=','').strip end # Returns the root node for the graph def root @root ||= Related::Root.new end end end
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/lib/related/root.rb
lib/related/root.rb
module Related class Root < Related::Node def initialize(attributes = {}) @id = 'root' super(attributes) end end end
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
niho/related
https://github.com/niho/related/blob/c18d66911c4f08ed7422d2122bc2fbfdb0274c8f/lib/related/validations/check_redis_uniqueness.rb
lib/related/validations/check_redis_uniqueness.rb
module Related class CheckRedisUniqueness < ActiveModel::Validator def validate(entity) internal_id = entity.instance_variable_get(:@_internal_id) if Related.redis.exists(internal_id) entity.errors[:id] << "#{internal_id.inspect} already exists." end end end end
ruby
MIT
c18d66911c4f08ed7422d2122bc2fbfdb0274c8f
2026-01-04T17:48:29.697273Z
false
sagmor/sii_chile
https://github.com/sagmor/sii_chile/blob/3600424a5b85ff948f7a5bee420e92798cc55307/app/sii_chile/application.rb
app/sii_chile/application.rb
require 'sii_chile' require 'sinatra' require 'dalli' require 'rack/contrib/jsonp' require 'multi_json' require 'newrelic_rpm' module SIIChile class Application < Sinatra::Base set :cache, Dalli::Client.new(ENV["MEMCACHIER_SERVERS"].split(","), {:username => ENV["MEMCACHIER_USERNAME"], :password => ENV["MEMCACHIER_PASSWORD"]}) use Rack::JSONP get '/' do redirect 'https://github.com/sagmor/sii_chile' end get '/consulta' do @consulta = Consulta.new(params[:rut]) @cache_key = [ SIIChile::VERSION, @consulta.rut.format, Time.now.strftime('%Y%m%d') ].join('/') @resultado = settings.cache.get(@cache_key) cached = true unless @resultado cached = false @resultado = @consulta.resultado settings.cache.set(@cache_key, @resultado) end [ 200, { 'Content-Type' => 'application/json', 'Access-Control-Allow-Origin' => '*', 'X-Version' => SIIChile::VERSION }, MultiJson.dump(@resultado) ] end end end
ruby
MIT
3600424a5b85ff948f7a5bee420e92798cc55307
2026-01-04T17:48:25.496512Z
false
sagmor/sii_chile
https://github.com/sagmor/sii_chile/blob/3600424a5b85ff948f7a5bee420e92798cc55307/gem/lib/sii_chile.rb
gem/lib/sii_chile.rb
require 'faraday' require 'nokogiri' require "sii_chile/version" require "sii_chile/rut" require "sii_chile/consulta"
ruby
MIT
3600424a5b85ff948f7a5bee420e92798cc55307
2026-01-04T17:48:25.496512Z
false
sagmor/sii_chile
https://github.com/sagmor/sii_chile/blob/3600424a5b85ff948f7a5bee420e92798cc55307/gem/lib/sii_chile/version.rb
gem/lib/sii_chile/version.rb
module SIIChile VERSION = "0.1.4" end
ruby
MIT
3600424a5b85ff948f7a5bee420e92798cc55307
2026-01-04T17:48:25.496512Z
false
sagmor/sii_chile
https://github.com/sagmor/sii_chile/blob/3600424a5b85ff948f7a5bee420e92798cc55307/gem/lib/sii_chile/consulta.rb
gem/lib/sii_chile/consulta.rb
require 'json' require 'base64' module SIIChile class Consulta attr_reader :rut def initialize(rut) @rut = Rut.new(rut) end def resultado @resultado ||= self.fetch! end protected XPATH_RAZON_SOCIAL = '/html/body/div/div[4]' XPATH_ACTIVIDADES = '/html/body/div/table[1]/tr' def fetch! raise 'Rut invalido' unless @rut.valid? captcha = fetch_captcha! # HTML form: https://zeus.sii.cl/cvc/stc/stc.html response = Faraday.post('https://zeus.sii.cl/cvc_cgi/stc/getstc', { 'RUT' => @rut.number, 'DV' => @rut.code, 'PRG' => 'STC', 'OPC' => 'NOR', 'txt_code' => captcha[:code], 'txt_captcha' => captcha[:captcha] }) data = Nokogiri::HTML(response.body) actividades = data.xpath(XPATH_ACTIVIDADES)[1..-1].map do |node| { :giro => node.xpath('./td[1]/font').text.strip, :codigo => node.xpath('./td[2]/font').text.strip.to_i, :categoria => node.xpath('./td[3]/font').text.strip, :afecta => node.xpath('./td[4]/font').text.strip == 'Si' } end rescue [] { :rut => @rut.format, :razon_social => data.xpath(XPATH_RAZON_SOCIAL).text.strip, :actividades => actividades } rescue StandardError => e { :rut => @rut.format, :error => e.message } end def fetch_captcha! response = Faraday.post('https://zeus.sii.cl/cvc_cgi/stc/CViewCaptcha.cgi', { oper: 0 }); data = JSON.parse(response.body) { code: Base64.decode64(data["txtCaptcha"])[36..39], captcha: data["txtCaptcha"] } end end end
ruby
MIT
3600424a5b85ff948f7a5bee420e92798cc55307
2026-01-04T17:48:25.496512Z
false
sagmor/sii_chile
https://github.com/sagmor/sii_chile/blob/3600424a5b85ff948f7a5bee420e92798cc55307/gem/lib/sii_chile/rut.rb
gem/lib/sii_chile/rut.rb
module SIIChile # "Stealed" from https://github.com/iortega/rut_validator/blob/master/lib/rut_validator/rut.rb class Rut attr_reader :number attr_reader :code def initialize(rut) @rut = rut.to_s.strip @number = @rut.gsub(/[^0-9K]/i,'')[0...-1] @code = @rut[-1].upcase end def valid? size_valid? && code_valid? end def size_valid? @number.size <= 8 end def code_valid? @code == calculated_code end def calculated_code all_codes = (0..9).to_a + ['K'] reverse_digits = @number.split('').reverse factors = (2..7).to_a * 2 partial_sum = reverse_digits.zip(factors).inject(0) do |r, a| digit, factor = *a r += digit.to_i * factor end all_codes[(11 - partial_sum%11)%11].to_s end def number_with_delimiter(delimiter='.') @number.to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{delimiter}") end def format(opts={}) delimiter = opts[:delimiter] || '.' with_dash = opts[:with_dash].nil? ? true : opts[:with_dash] formatted_rut = number_with_delimiter(delimiter) formatted_rut << '-' if with_dash formatted_rut << @code end def to_s; format; end end end
ruby
MIT
3600424a5b85ff948f7a5bee420e92798cc55307
2026-01-04T17:48:25.496512Z
false
sagmor/sii_chile
https://github.com/sagmor/sii_chile/blob/3600424a5b85ff948f7a5bee420e92798cc55307/spec/spec_helper.rb
spec/spec_helper.rb
RSpec.configure do |config| config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true end config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end end
ruby
MIT
3600424a5b85ff948f7a5bee420e92798cc55307
2026-01-04T17:48:25.496512Z
false
sagmor/sii_chile
https://github.com/sagmor/sii_chile/blob/3600424a5b85ff948f7a5bee420e92798cc55307/spec/integration/sii_consulta.rb
spec/integration/sii_consulta.rb
require 'faraday' require 'nokogiri' require File.expand_path('gem/lib/sii_chile/version') require File.expand_path('gem/lib/sii_chile/rut') require File.expand_path('gem/lib/sii_chile/consulta') describe "Materialización del objeto y resultados" do before do @sii_chile_rut = "76.118.195-5" @sii_chile = SIIChile::Consulta.new(@sii_chile_rut) @sii_chile_resultado = @sii_chile.resultado end it "Retornar el rut desde el objecto" do expect(@sii_chile_rut).to eq(@sii_chile.rut.to_s) end it "Retornar el rut desde el servicio" do expect(@sii_chile_resultado[:rut]).to eq(@sii_chile_rut) end it "Retornar la razón social desde el servicio" do expect(@sii_chile_resultado[:razon_social]).to eq("WELCU CHILE SPA") end it "Retornar las actividades desde el servicio" do expect(@sii_chile_resultado[:actividades]).to_not eq(nil) expect(@sii_chile_resultado[:actividades].length).to be > 0 end it "La primera actividad debiera ser 'EMPRESAS DE SERVICIOS INTEGRALES DE INFORMATICA'" do expect(@sii_chile_resultado[:actividades][0][:giro]).to eq("EMPRESAS DE SERVICIOS INTEGRALES DE INFORMATICA") end it "La primera actividad debiera ser 'EMPRESAS DE SERVICIOS INTEGRALES DE INFORMATICA'" do expect(@sii_chile_resultado[:actividades][0][:giro]).to eq("EMPRESAS DE SERVICIOS INTEGRALES DE INFORMATICA") end it "El primer codigo debiera ser '726000'" do expect(@sii_chile_resultado[:actividades][0][:codigo]).to eq(726000) end it "La primera categoría debiera ser 'Primera'" do expect(@sii_chile_resultado[:actividades][0][:categoria]).to eq("Primera") end it "La actividad debiera ser afecta" do expect(@sii_chile_resultado[:actividades][0][:afecta]).to eq(true) end end
ruby
MIT
3600424a5b85ff948f7a5bee420e92798cc55307
2026-01-04T17:48:25.496512Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/yard/templates/mathjax/constant/text/setup.rb
yard/templates/mathjax/constant/text/setup.rb
def init sections :header, [T('docstring')] end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/yard/templates/mathjax/root/dot/setup.rb
yard/templates/mathjax/root/dot/setup.rb
include T('default/module/dot') def format_path(object) "" end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/yard/templates/mathjax/root/html/setup.rb
yard/templates/mathjax/root/html/setup.rb
include T('default/module/html')
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/yard/templates/mathjax/fulldoc/html/setup.rb
yard/templates/mathjax/fulldoc/html/setup.rb
include Helpers::ModuleHelper def init options.objects = objects = run_verifier(options.objects) return serialize_onefile if options.onefile generate_assets serialize('_index.html') options.files.each_with_index do |file, i| serialize_file(file, file.title) end options.delete(:objects) options.delete(:files) objects.each do |object| begin serialize(object) rescue => e path = options.serializer.serialized_path(object) log.error "Exception occurred while generating '#{path}'" log.backtrace(e) end end end # Generate an HTML document for the specified object. This method is used by # most of the objects found in the Registry. # @param [CodeObject] object to be saved to HTML def serialize(object) options.object = object serialize_index(options) if object == '_index.html' && options.readme.nil? Templates::Engine.with_serializer(object, options.serializer) do T('layout').run(options) end end # Generate the documentation output in one file (--one-file) which will load the # contents of all the javascript and css and output the entire contents without # depending on any additional files def serialize_onefile Templates::Engine.with_serializer('index.html', options.serializer) do T('onefile').run(options) end end # Generate the index document for the output # @params [Hash] options contains data and flags that influence the output def serialize_index(options) Templates::Engine.with_serializer('index.html', options.serializer) do T('layout').run(options.merge(:index => true)) end end # Generate a single HTML file with the layout template applied. This is generally # the README file or files specified on the command-line. # # @param [File] file object to be saved to the output # @param [String] title currently unused # # @see layout#diskfile def serialize_file(file, title = nil) options.object = Registry.root options.file = file outfile = 'file.' + file.name + '.html' serialize_index(options) if file == options.readme Templates::Engine.with_serializer(outfile, options.serializer) do T('layout').run(options) end options.delete(:file) end # # Generates a file to the output with the specified contents. # # @example saving a custom html file to the documenation root # # asset('my_custom.html','<html><body>Custom File</body></html>') # # @param [String] path relative to the document output where the file will be # created. # @param [String] content the contents that are saved to the file. def asset(path, content) if options.serializer log.capture("Generating asset #{path}") do options.serializer.serialize(path, content) end end end # @return [Array<String>] Stylesheet files that are additionally loaded for the # searchable full lists, e.g., Class List, Method List, File List # @since 0.7.0 def stylesheets_full_list %w(css/full_list.css css/common.css) end # @return [Array<String>] Javascript files that are additionally loaded for the # searchable full lists, e.g., Class List, Method List, File List. # @since 0.7.0 def javascripts_full_list %w(js/jquery.js js/full_list.js) end def menu_lists Object.new.extend(T('layout')).menu_lists end # Generates all the javascript files, stylesheet files, menu lists # (i.e. class, method, and file) based on the the values returned from the # layout's menu_list method, and the frameset in the documentation output # def generate_assets @object = Registry.root layout = Object.new.extend(T('layout')) (layout.javascripts + javascripts_full_list + layout.stylesheets + stylesheets_full_list).uniq.each do |file| asset(file, file(file, true)) end layout.menu_lists.each do |list| list_generator_method = "generate_#{list[:type]}_list" if respond_to?(list_generator_method) send(list_generator_method) else log.error "Unable to generate '#{list[:title]}' list because no method " + "'#{list_generator_method}' exists" end end generate_frameset end # Generate a searchable method list in the output # @see ModuleHelper#prune_method_listing def generate_method_list @items = prune_method_listing(Registry.all(:method), false) @items = @items.reject {|m| m.name.to_s =~ /=$/ && m.is_attribute? } @items = @items.sort_by {|m| m.name.to_s } @list_title = "Method List" @list_type = "method" generate_list_contents end # Generate a searchable class list in the output def generate_class_list @items = options.objects if options.objects @list_title = "Class List" @list_type = "class" generate_list_contents end # Generate a searchable file list in the output def generate_file_list @file_list = true @items = options.files @list_title = "File List" @list_type = "file" generate_list_contents @file_list = nil end def generate_list_contents asset(url_for_list(@list_type), erb(:full_list)) end # Generate the frame documentation in the output def generate_frameset @javascripts = javascripts_full_list @stylesheets = stylesheets_full_list asset(url_for_frameset, erb(:frames)) end # @api private class TreeContext def initialize @depth = 0 @even_odd = Alternator.new(:even, :odd) end def nest @depth += 1 yield @depth -= 1 end # @return [String] Returns a css pixel offset, e.g. "30px" def indent "#{(@depth + 2) * 15}px" end def classes classes = [] classes << 'collapsed' if @depth > 0 classes << @even_odd.next if @depth < 2 classes end class Alternator def initialize(first, second) @next = first @after = second end def next @next, @after = @after, @next @after end end end # @return [String] HTML output of the classes to be displayed in the # full_list_class template. def class_list(root = Registry.root, tree = TreeContext.new) out = "" children = run_verifier(root.children) if root == Registry.root children += @items.select {|o| o.namespace.is_a?(CodeObjects::Proxy) } end children.compact.sort_by(&:path).each do |child| if child.is_a?(CodeObjects::NamespaceObject) name = child.namespace.is_a?(CodeObjects::Proxy) ? child.path : child.name has_children = run_verifier(child.children).any? {|o| o.is_a?(CodeObjects::NamespaceObject) } out << "<li id='object_#{child.path}' class='#{tree.classes.join(' ')}'>" out << "<div class='item' style='padding-left:#{tree.indent}'>" out << "<a class='toggle'></a> " if has_children out << linkify(child, name) out << " &lt; #{child.superclass.name}" if child.is_a?(CodeObjects::ClassObject) && child.superclass out << "<small class='search_info'>" out << child.namespace.title out << "</small>" out << "</div>" tree.nest do out << "<ul>#{class_list(child, tree)}</ul>" if has_children end out << "</li>" end end out end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/yard/templates/mathjax/tags/setup.rb
yard/templates/mathjax/tags/setup.rb
def init tags = Tags::Library.visible_tags - [:abstract, :deprecated, :note, :todo] create_tag_methods(tags - [:example, :option, :overload, :see]) sections :index, tags.map {|t| t.to_s.gsub('.', '_').to_sym } sections.any(:overload).push(T('docstring')) end def return if object.type == :method return if object.constructor? return if object.tags(:return).size == 1 && object.tag(:return).types == ['void'] end tag(:return) end def param tag(:param) if object.type == :method end private def tag(name, opts = nil) return unless object.has_tag?(name) opts ||= options_for_tag(name) @no_names = true if opts[:no_names] @no_types = true if opts[:no_types] @name = name out = erb('tag') @no_names, @no_types = nil, nil out end def create_tag_methods(tags) tags.each do |tag| tag_meth = tag.to_s.gsub('.', '_') next if respond_to?(tag_meth) instance_eval(<<-eof, __FILE__, __LINE__ + 1) def #{tag_meth}; tag(#{tag.inspect}) end eof end end def options_for_tag(tag) opts = {:no_types => true, :no_names => true} case Tags::Library.factory_method_for(tag) when :with_types opts[:no_types] = false when :with_types_and_name opts[:no_types] = false opts[:no_names] = false when :with_name opts[:no_names] = false end opts end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/yard/templates/mathjax/method_details/setup.rb
yard/templates/mathjax/method_details/setup.rb
def init sections :header, [:method_signature, T('docstring'), :source] end def source return if owner != object.namespace return if Tags::OverloadTag === object return if object.source.nil? erb(:source) end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/yard/templates/mathjax/method_details/text/setup.rb
yard/templates/mathjax/method_details/text/setup.rb
def init super sections.last.pop end def format_object_title(object) title = "Method: #{object.name(true)}" title += " (#{object.namespace})" if !object.namespace.root? title end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/yard/templates/mathjax/method/setup.rb
yard/templates/mathjax/method/setup.rb
def init sections :header, [T('method_details')] end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/yard/templates/mathjax/layout/dot/setup.rb
yard/templates/mathjax/layout/dot/setup.rb
attr_reader :contents def init if object type = object.root? ? :module : object.type sections :header, [T(type)] else sections :header, [:contents] end end def header tidy erb(:header) end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/yard/templates/mathjax/layout/html/setup.rb
yard/templates/mathjax/layout/html/setup.rb
def init @breadcrumb = [] if @onefile sections :layout elsif @file if @file.attributes[:namespace] @object = options.object = Registry.at(@file.attributes[:namespace]) || Registry.root end @breadcrumb_title = "File: " + @file.title @page_title = @breadcrumb_title sections :layout, [:diskfile] elsif @contents sections :layout, [:contents] else case object when '_index.html' @page_title = options.title sections :layout, [:index, [:listing, [:files, :objects]]] when CodeObjects::Base unless object.root? cur = object.namespace while !cur.root? @breadcrumb.unshift(cur) cur = cur.namespace end end @page_title = format_object_title(object) type = object.root? ? :module : object.type sections :layout, [T(type)] end end end def contents @contents end def index @objects_by_letter = {} objects = Registry.all(:class, :module).sort_by {|o| o.name.to_s } objects = run_verifier(objects) objects.each {|o| (@objects_by_letter[o.name.to_s[0,1].upcase] ||= []) << o } erb(:index) end def layout @nav_url = url_for_list(!@file || options.index ? 'class' : 'file') if !object || object.is_a?(String) @path = nil elsif @file @path = @file.path elsif !object.is_a?(YARD::CodeObjects::NamespaceObject) @path = object.parent.path else @path = object.path end erb(:layout) end def diskfile @file.attributes[:markup] ||= markup_for_file('', @file.filename) data = htmlify(@file.contents, @file.attributes[:markup]) "<div id='filecontents'>" + data + "</div>" end # @return [Array<String>] core javascript files for layout # @since 0.7.0 def javascripts %w(js/jquery.js js/app.js) end # @return [Array<String>] core stylesheets for the layout # @since 0.7.0 def stylesheets %w(css/style.css css/common.css) end # @return [Array<Hash{Symbol=>String}>] the list of search links and drop-down menus # @since 0.7.0 def menu_lists [ { :type => 'class', :title => 'Classes', :search_title => 'Class List' }, { :type => 'method', :title => 'Methods', :search_title => 'Method List' }, { :type => 'file', :title => 'Files', :search_title => 'File List' } ] end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/yard/templates/mathjax/docstring/setup.rb
yard/templates/mathjax/docstring/setup.rb
def init return if object.docstring.blank? && !object.has_tag?(:api) sections :index, [:private, :deprecated, :abstract, :todo, :note, :returns_void, :text], T('tags') end def private return unless object.has_tag?(:api) && object.tag(:api).text == 'private' erb(:private) end def abstract return unless object.has_tag?(:abstract) erb(:abstract) end def deprecated return unless object.has_tag?(:deprecated) erb(:deprecated) end def todo return unless object.has_tag?(:todo) erb(:todo) end def note return unless object.has_tag?(:note) erb(:note) end def returns_void return unless object.type == :method return if object.name == :initialize && object.scope == :instance return unless object.tags(:return).size == 1 && object.tag(:return).types == ['void'] erb(:returns_void) end def docstring_text text = "" unless object.tags(:overload).size == 1 && object.docstring.empty? text = object.docstring end if text.strip.empty? && object.tags(:return).size == 1 && object.tag(:return).text text = object.tag(:return).text.gsub(/\A([a-z])/) {|x| x.downcase } text = "Returns #{text}" unless text.empty? || text =~ /^\s*return/i text = text.gsub(/\A([a-z])/) {|x| x.upcase } end text.strip end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/yard/templates/mathjax/class/setup.rb
yard/templates/mathjax/class/setup.rb
include T('default/module') def init super sections.place(:subclasses).before(:children) sections.place(:constructor_details, [T('method_details')]).before(:methodmissing) end def constructor_details ctors = object.meths(:inherited => true, :included => true) return unless @ctor = ctors.find {|o| o.constructor? } return if prune_method_listing([@ctor]).empty? erb(:constructor_details) end def subclasses return if object.path == "Object" # don't show subclasses for Object unless globals.subclasses globals.subclasses = {} list = run_verifier Registry.all(:class) list.each do |o| (globals.subclasses[o.superclass.path] ||= []) << o if o.superclass end end @subclasses = globals.subclasses[object.path] return if @subclasses.nil? || @subclasses.empty? @subclasses = @subclasses.sort_by {|o| o.path }.map do |child| name = child.path if object.namespace name = object.relative_path(child) end [name, child] end erb(:subclasses) end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/yard/templates/mathjax/class/dot/setup.rb
yard/templates/mathjax/class/dot/setup.rb
include T('default/module/dot') def init super sections.push :superklass end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/yard/templates/mathjax/class/html/setup.rb
yard/templates/mathjax/class/html/setup.rb
include T('default/module/html')
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/yard/templates/mathjax/class/text/setup.rb
yard/templates/mathjax/class/text/setup.rb
include T('default/module/text') def init super sections.place(:subclasses).before(:children) sections.delete(:children) end def format_object_title(object) "Class: #{object.title} < #{object.superclass.title}" end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/yard/templates/mathjax/module/setup.rb
yard/templates/mathjax/module/setup.rb
include Helpers::ModuleHelper def init sections :header, :box_info, :pre_docstring, T('docstring'), :children, :constant_summary, [T('docstring')], :inherited_constants, :attribute_summary, [:item_summary], :inherited_attributes, :method_summary, [:item_summary], :inherited_methods, :methodmissing, [T('method_details')], :attribute_details, [T('method_details')], :method_details_list, [T('method_details')] end def pre_docstring return if object.docstring.blank? erb(:pre_docstring) end def children @inner = [[:modules, []], [:classes, []]] object.children.each do |child| @inner[0][1] << child if child.type == :module @inner[1][1] << child if child.type == :class end @inner.map! {|v| [v[0], run_verifier(v[1].sort_by {|o| o.name.to_s })] } return if (@inner[0][1].size + @inner[1][1].size) == 0 erb(:children) end def methodmissing mms = object.meths(:inherited => true, :included => true) return unless @mm = mms.find {|o| o.name == :method_missing && o.scope == :instance } erb(:methodmissing) end def method_listing(include_specials = true) return @smeths ||= method_listing.reject {|o| special_method?(o) } unless include_specials return @meths if @meths @meths = object.meths(:inherited => false, :included => !options.embed_mixins.empty?) if options.embed_mixins.size > 0 @meths = @meths.reject {|m| options.embed_mixins_match?(m.namespace) == false } end @meths = sort_listing(prune_method_listing(@meths)) @meths end def special_method?(meth) return true if meth.name(true) == '#method_missing' return true if meth.constructor? false end def attr_listing return @attrs if @attrs @attrs = [] object.inheritance_tree(true).each do |superclass| next if superclass.is_a?(CodeObjects::Proxy) next if options.embed_mixins.size > 0 && !options.embed_mixins_match?(superclass) [:class, :instance].each do |scope| superclass.attributes[scope].each do |name, rw| attr = prune_method_listing([rw[:read], rw[:write]].compact, false).first @attrs << attr if attr end end break if options.embed_mixins.empty? end @attrs = sort_listing(@attrs) end def constant_listing return @constants if @constants @constants = object.constants(:included => false, :inherited => false) @constants += object.cvars @constants = run_verifier(@constants) @constants end def sort_listing(list) list.sort_by {|o| [o.scope.to_s, o.name.to_s.downcase] } end def inherited_attr_list(&block) object.inheritance_tree(true)[1..-1].each do |superclass| next if superclass.is_a?(YARD::CodeObjects::Proxy) next if options.embed_mixins.size > 0 && options.embed_mixins_match?(superclass) != false attribs = superclass.attributes[:instance] attribs = attribs.reject {|name, rw| object.child(:scope => :instance, :name => name) != nil } attribs = attribs.sort_by {|args| args.first.to_s }.map {|n, m| m[:read] || m[:write] } attribs = prune_method_listing(attribs, false) yield superclass, attribs if attribs.size > 0 end end def inherited_constant_list(&block) object.inheritance_tree(true)[1..-1].each do |superclass| next if superclass.is_a?(YARD::CodeObjects::Proxy) next if options.embed_mixins.size > 0 && options.embed_mixins_match?(superclass) != false consts = superclass.constants(:included => false, :inherited => false) consts = consts.reject {|const| object.child(:type => :constant, :name => const.name) != nil } consts = consts.sort_by {|const| const.name.to_s } consts = run_verifier(consts) yield superclass, consts if consts.size > 0 end end def docstring_full(obj) docstring = "" if obj.tags(:overload).size == 1 && obj.docstring.empty? docstring = obj.tag(:overload).docstring else docstring = obj.docstring end if docstring.summary.empty? && obj.tags(:return).size == 1 && obj.tag(:return).text docstring = Docstring.new(obj.tag(:return).text.gsub(/\A([a-z])/) {|x| x.upcase }.strip) end docstring end def docstring_summary(obj) docstring_full(obj).summary end def groups(list, type = "Method") if groups_data = object.groups list.each {|m| groups_data |= [m.group] if m.group && owner != m.namespace } others = list.select {|m| !m.group || !groups_data.include?(m.group) } groups_data.each do |name| items = list.select {|m| m.group == name } yield(items, name) unless items.empty? end else others = [] group_data = {} list.each do |meth| if meth.group (group_data[meth.group] ||= []) << meth else others << meth end end group_data.each {|group, items| yield(items, group) unless items.empty? } end scopes(others) {|items, scope| yield(items, "#{scope.to_s.capitalize} #{type} Summary") } end def scopes(list) [:class, :instance].each do |scope| items = list.select {|m| m.scope == scope } yield(items, scope) unless items.empty? end end def mixed_into(object) unless globals.mixed_into globals.mixed_into = {} list = run_verifier Registry.all(:class, :module) list.each {|o| o.mixins.each {|m| (globals.mixed_into[m.path] ||= []) << o } } end globals.mixed_into[object.path] || [] end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/yard/templates/mathjax/module/dot/setup.rb
yard/templates/mathjax/module/dot/setup.rb
def init @modules = object.children.select {|o| o.type == :module } @classes = object.children.select {|o| o.type == :class } sections :child, [:info], :classes, [T('class')], :header, [T('module')], :dependencies end def dependencies return unless options.dependencies erb(:dependencies) end def classes @classes.map {|k| yieldall :object => k }.join("\n") end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/yard/templates/mathjax/module/text/setup.rb
yard/templates/mathjax/module/text/setup.rb
def init sections :header, [T('docstring')], :children, :includes, :extends, :class_meths_list, :instance_meths_list end def class_meths @classmeths ||= method_listing.select {|o| o.scope == :class } end def instance_meths @instmeths ||= method_listing.select {|o| o.scope == :instance } end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/yard/templates/mathjax/onefile/html/setup.rb
yard/templates/mathjax/onefile/html/setup.rb
include T('default/layout/html') include YARD::Parser::Ruby::Legacy def init override_serializer @object = YARD::Registry.root @files.shift @objects.delete(YARD::Registry.root) @objects.unshift(YARD::Registry.root) sections :layout, [:readme, :files, :all_objects] end def all_objects @objects.map {|obj| obj.format(options) }.join("\n") end def layout fulldoc = Object.new.extend(T('fulldoc')) layout = Object.new.extend(T('layout')) @css_data = layout.stylesheets.map {|sheet| read_asset(sheet) }.join("\n") @js_data = layout.javascripts.map {|script| read_asset(script) }.join("") erb(:layout) end def read_asset(file) return unless file = T('fulldoc').find_file(file) data = File.read(file) superfile = self.class.find_nth_file('fulldoc', 2) data.gsub!('{{{__super__}}}', superfile ? IO.read(superfile) : "") data end private def parse_top_comments_from_file return unless @readme return @readme.contents unless @readme.filename =~ /\.rb$/ data = "" tokens = TokenList.new(@readme.contents) tokens.each do |token| break unless token.is_a?(RubyToken::TkCOMMENT) || token.is_a?(RubyToken::TkNL) data << (token.text[/\A#\s{0,1}(.*)/, 1] || "\n") end YARD::Docstring.new(data) end def override_serializer return if @serializer.nil? class << @serializer def serialize(object, data) return unless object == 'index.html' super end def serialized_path(object) return object if object.is_a?(String) return 'index.html' end end end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/test/run-test.rb
test/run-test.rb
$VERBOSE = true base_dir = File.expand_path("../..", __FILE__) lib_dir = File.join(base_dir, "lib") test_dir = File.join(base_dir, "test") $LOAD_PATH.unshift(lib_dir) require "test/unit" require "enumerable/statistics" exit Test::Unit::AutoRunner.run(true, test_dir)
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/test/test-ractor.rb
test/test-ractor.rb
if defined?(Ractor) class Ractor alias_method :value, :take unless method_defined?(:value) end end class RactorTest < Test::Unit::TestCase ractor test("Array#mean") do r = Ractor.new do [1, 2, 3, 4].mean end assert_equal(2.5, r.value) end end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/test/test-array.rb
test/test-array.rb
class ArrayTest < Test::Unit::TestCase sub_test_case("find_max and argmax") do data(:case, [ { array: [3, 6, 2, 4, 9, 1, 2, 9], result: [9, 4] }, { array: [3, 6, 2, 4, 3, 1, 2, 8], result: [8, 7] }, { array: [7, 6, 2, 4, 3, 1, 2, 6], result: [7, 0] } ]) def test_find_max(data) array, result = data[:case].values_at(:array, :result) assert_equal(result, array.find_max) end def test_argmax(data) array, result = data[:case].values_at(:array, :result) assert_equal(result[1], array.argmax) end end sub_test_case("find_min and argmin") do data(:case, [ { array: [3, 6, 1, 4, 9, 1, 2, 9], result: [1, 2] }, { array: [3, 6, 3, 4, 4, 8, 3, 2], result: [2, 7] }, { array: [3, 6, 5, 4, 3, 6, 8, 6], result: [3, 0] } ]) def test_find_min(data) array, result = data[:case].values_at(:array, :result) assert_equal(result, array.find_min) end def test_argmin(data) array, result = data[:case].values_at(:array, :result) assert_equal(result[1], array.argmin) end end end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/test/test-sum.rb
test/test-sum.rb
require "delegate" class SumTest < Test::Unit::TestCase large_number = 100_000_000 small_number = 1e-9 until (large_number + small_number) == large_number small_number /= 10 end generic_test_data = [ [ [], 0, 0 ], [ [], 0.0, 0.0 ], [ [3], 0, 3 ], [ [3], 0.0, 3.0 ], [ [3, 5], 0, 8 ], [ [3, 5, 7], 0, 15 ], [ [3, Rational(5)], 0, Rational(8) ], [ [3, 5, 7.0], 0, 15.0 ], [ [3, Rational(5), 7.0], 0, 15.0 ], [ [3, Rational(5), Complex(0, 1)], 0, Complex(Rational(8), 1) ], [ [3, Rational(5), 7.0, Complex(0, 1)], 0, Complex(15.0, 1) ], [ [3.5, 5], 0, 8.5 ], [ [2, 8.5], 0, 10.5 ], [ [Rational(1, 2), 1], 0, Rational(3, 2) ], [ [Rational(1, 2), Rational(1, 3)], 0, Rational(5, 6) ], [ [2.0, Complex(0, 3.0)], 0, Complex(2.0, 3.0) ], [ [1, 2], 10, 13], [ [large_number, *[small_number]*10], 0, large_number + small_number*10 ], [ [Rational(large_number), *[small_number]*10], 0, large_number + small_number*10 ], [ [small_number, Rational(large_number), *[small_number]*10], 0, large_number + small_number*11 ], [ ["a", "b", "c"], "", "abc"], [ [[1], [[2]], [3]], [], [1, [2], 3]], ].map { |recv, init, expected_result| [ "#{recv.inspect}.sum(#{init.inspect}) == #{expected_result.inspect}", [recv, init, expected_result]] }.to_h sub_test_case("Array#sum") do data(generic_test_data) def test_generic_case(data) ary, init, expected_result, conversion = data actual_result = ary.sum(init, &conversion) assert_equal({ value: expected_result, class: expected_result.class }, { value: actual_result, class: actual_result.class }) end def test_sum_with_block ary = [1, 2, SimpleDelegator.new(3)] yielded = [] result = ary.sum(0) {|x| yielded << x; 2*x } assert_equal({ result: 12, yielded: ary }, { result: result, yielded: yielded }) end def test_skip_na_false ary = [1, 2, nil, SimpleDelegator.new(3)] assert_raise(TypeError) do ary.sum(0, skip_na: false) end end def test_skip_na_true ary = [1, 2, nil, SimpleDelegator.new(3)] result = ary.sum(0, skip_na: true) assert_equal(6, result) end def test_skip_na_true_with_block ary = [1, 2, nil, SimpleDelegator.new(3)] result = ary.sum(0, skip_na: true) {|x| x || 10 } assert_equal(16, result) end def test_type_error assert_raise(TypeError) do [Object.new].sum(0) end end end sub_test_case("Enumerable#sum") do test_data = generic_test_data.map {|key, value| [ key.sub(/\.sum/, ".each.sum"), value ] }.to_h data(test_data) def test_generic_case(data) ary, init, expected_result, conversion = data actual_result = ary.each.sum(init, &conversion) assert_equal({ value: expected_result, class: expected_result.class }, { value: actual_result, class: actual_result.class }) end def test_sum_with_block ary = [1, 2, SimpleDelegator.new(3)] yielded = [] result = ary.each.sum(0) {|x| yielded << x; 2*x } assert_equal({ result: 12, yielded: ary }, { result: result, yielded: yielded }) end def test_skip_na_false ary = [1, 2, nil, SimpleDelegator.new(3)] assert_raise(TypeError) do ary.each.sum(0, skip_na: false) end end def test_skip_na_true ary = [1, 2, nil, SimpleDelegator.new(3)] result = ary.each.sum(0, skip_na: true) assert_equal(6, result) end def test_type_error assert_raise(TypeError) do [Object.new].each.sum(0) end end end sub_test_case("Hash#sum") do def test_skip_na_false hash = { a: 1, b: 2, c: nil, d: 3 } assert_raise(TypeError) do hash.sum(0, skip_na: false, &:last) end end def test_skip_na_true hash = { a: 1, b: 2, c: nil, d: 3 } result = hash.sum(0, skip_na: true, &:last) assert_equal(6, result) end end end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/ext/enumerable/statistics/extension/extconf.rb
ext/enumerable/statistics/extension/extconf.rb
require 'mkmf' have_type('struct RRational') have_func('rb_rational_new') have_func('rb_rational_num') have_func('rb_rational_den') have_func('rb_rational_plus') have_type('struct RComplex') have_func('rb_complex_raw') have_func('rb_complex_real') have_func('rb_complex_imag') have_func('rb_complex_plus') have_func('rb_complex_div') have_func('rb_dbl_complex_new') create_makefile('enumerable/statistics/extension')
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/spec/array_spec.rb
spec/array_spec.rb
require 'spec_helper' require 'enumerable/statistics' require 'delegate' RSpec.describe Array do describe '#mean' do let(:ary) { [] } let(:block) { nil } subject(:mean) { ary.mean(&block) } with_array [] do it_is_float_equal(0.0) context 'with a conversion block' do it_is_float_equal(0.0) it 'does not call the block' do expect { |b| ary.mean(&b) }.not_to yield_control end end end with_array [3] do it_is_float_equal(3.0) with_conversion ->(v) { v * 2 }, 'v * 2' do it_is_float_equal(6.0) end end with_array [3, 5] do it_is_float_equal(4.0) with_conversion ->(v) { v * 2 }, 'v * 2' do it_is_float_equal(8.0) end end with_array [3, Rational(5), Complex(7, 3)] do it_is_complex_equal(Complex(5.0, 1.0)) end with_array [Object.new] do specify do expect { subject }.to raise_error(TypeError) end end large_number = 100_000_000 small_number = 1e-9 until (large_number + small_number) == large_number small_number /= 10 end with_array [large_number, *[small_number]*10] do it_is_float_equal((large_number + small_number*10)/11.0) end with_array [Rational(large_number, 1), *[small_number]*10] do it_is_float_equal((large_number + small_number*10)/11.0) end with_array [small_number, Rational(large_number, 1), *[small_number]*10] do it_is_float_equal((Rational(large_number, 1) + small_number*11)/12.0) end end describe '#variance' do let(:ary) { [] } let(:block) { nil } subject(:variance) { ary.variance(&block) } with_array [] do it_is_float_nan context 'with a conversion block' do it_is_float_nan it 'does not call the block' do expect { |b| ary.variance(&b) }.not_to yield_control end end end with_array [3] do it_is_float_nan with_conversion ->(v) { v * 2 }, 'v * 2' do it_is_float_nan end end with_array [3, 5] do it_is_float_equal(2.0) end with_array [3.0, 5.0] do it_is_float_equal(2.0) context 'with population: nil' do subject(:variance) { ary.variance(population: nil, &block) } it_is_float_equal(2.0) end context 'with population: false' do subject(:variance) { ary.variance(population: false, &block) } it_is_float_equal(2.0) end context 'with population: true' do subject(:variance) { ary.variance(population: true, &block) } it_is_float_equal(1.0) end end with_array [Object.new] do specify do expect { subject }.to raise_error(TypeError) end end with_array [Object.new, Object.new] do specify do expect { subject }.to raise_error(TypeError) end end large_number = 100_000_000 small_number = 1e-9 until (large_number + small_number) == large_number small_number /= 10 end ary = [large_number, *[small_number]*10] m = ary.mean s2 = ary.map { |x| (x - m)**2 }.sum var = s2 / (ary.length - 1).to_f with_array ary do it_is_float_equal(var) end while true ary = Array.new(4) { 1.0 + rand*1e-6 } x = ary.map { |e| e**2 }.sum / ary.length.to_f y = (ary.sum / ary.length.to_f) ** 2 break if x < y end with_array ary do it { is_expected.to be > 0.0 } end end describe '#mean_variance' do let(:ary) { [] } let(:block) { nil } subject(:mean_variance) { ary.mean_variance(&block) } with_array [] do specify do expect(subject[0]).to eq(0.0) expect(subject[1]).to be_nan end context 'with a conversion block' do it 'does not call the block' do expect { |b| ary.mean_variance(&b) }.not_to yield_control end end end with_array [3] do specify do expect(subject[0]).to eq(3.0) expect(subject[1]).to be_nan end with_conversion ->(v) { v * 2 }, 'v * 2' do specify do expect(subject[0]).to eq(6.0) expect(subject[1]).to be_nan end end end with_array [3.0, 5.0] do context 'with population: nil' do subject(:mean_variance) { ary.mean_variance(population: nil, &block) } specify do expect(subject[0]).to eq(4.0) expect(subject[1]).to eq(2.0) end end context 'with population: false' do subject(:mean_variance) { ary.mean_variance(population: false, &block) } specify do expect(subject[0]).to eq(4.0) expect(subject[1]).to eq(2.0) end end context 'with population: true' do subject(:mean_variance) { ary.mean_variance(population: true, &block) } specify do expect(subject[0]).to eq(4.0) expect(subject[1]).to eq(1.0) end end end with_array [Object.new] do specify do expect { subject }.to raise_error(TypeError) end end large_number = 100_000_000 small_number = 1e-9 until (large_number + small_number) == large_number small_number /= 10 end ary = [large_number, *[small_number]*10] m = ary.mean s2 = ary.map { |x| (x - m)**2 }.sum var = s2 / (ary.length - 1).to_f with_array ary do it { is_expected.to eq([m, var]) } end while true ary = Array.new(4) { 1.0 + rand*1e-6 } x = ary.map { |e| e**2 }.sum / ary.length.to_f y = (ary.sum / ary.length.to_f) ** 2 break if x < y end with_array ary do it { is_expected.to eq([ary.mean, ary.variance]) } end end describe '#mean_stdev' do let(:ary) { [] } let(:block) { nil } subject(:mean_stdev) { ary.mean_stdev(&block) } with_array [] do specify do expect(subject[0]).to eq(0.0) expect(subject[1]).to be_nan end context 'with a conversion block' do it 'does not call the block' do expect { |b| ary.mean_stdev(&b) }.not_to yield_control end end end with_array [3] do specify do expect(subject[0]).to eq(3.0) expect(subject[1]).to be_nan end with_conversion ->(v) { v * 2 }, 'v * 2' do specify do expect(subject[0]).to eq(6.0) expect(subject[1]).to be_nan end end end with_array [3.0, 5.0] do context 'with population: nil' do subject(:mean_stdev) { ary.mean_stdev(population: nil, &block) } specify do expect(subject[0]).to eq(4.0) expect(subject[1]).to eq(Math.sqrt(2.0)) end end context 'with population: false' do subject(:mean_stdev) { ary.mean_stdev(population: false, &block) } specify do expect(subject[0]).to eq(4.0) expect(subject[1]).to eq(Math.sqrt(2.0)) end end context 'with population: true' do subject(:mean_stdev) { ary.mean_stdev(population: true, &block) } specify do expect(subject[0]).to eq(4.0) expect(subject[1]).to eq(1.0) end end end with_array [Object.new] do specify do expect { subject }.to raise_error(TypeError) end end large_number = 100_000_000 small_number = 1e-9 until (large_number + small_number) == large_number small_number /= 10 end ary = [large_number, *[small_number]*10] m = ary.mean s2 = ary.map { |x| (x - m)**2 }.sum var = s2 / (ary.length - 1).to_f sd = Math.sqrt(var) with_array ary do it { is_expected.to eq([m, sd]) } end while true ary = Array.new(4) { 1.0 + rand*1e-6 } x = ary.map { |e| e**2 }.sum / ary.length.to_f y = (ary.sum / ary.length.to_f) ** 2 break if x < y end with_array ary do it { is_expected.to eq([ary.mean, Math.sqrt(ary.variance)]) } end end describe '#stdev' do let(:ary) { [] } let(:block) { nil } subject(:stdev) { ary.stdev(&block) } with_array [] do it_is_float_nan context 'with a conversion block' do it_is_float_nan it 'does not call the block' do expect { |b| ary.stdev(&b) }.not_to yield_control end end end with_array [3] do it_is_float_nan with_conversion ->(v) { v * 2 }, 'v * 2' do it_is_float_nan end end with_array [3, 5] do it_is_float_equal(Math.sqrt(2.0)) end with_array [3.0, 5.0] do it_is_float_equal(Math.sqrt(2.0)) context 'with population: nil' do subject(:stdev) { ary.stdev(population: nil, &block) } it_is_float_equal(Math.sqrt(2.0)) end context 'with population: false' do subject(:stdev) { ary.stdev(population: false, &block) } it_is_float_equal(Math.sqrt(2.0)) end context 'with population: true' do subject(:stdev) { ary.stdev(population: true, &block) } it_is_float_equal(1.0) end end with_array [Object.new] do specify do expect { subject }.to raise_error(TypeError) end end with_array [Object.new, Object.new] do specify do expect { subject }.to raise_error(TypeError) end end large_number = 100_000_000 small_number = 1e-9 until (large_number + small_number) == large_number small_number /= 10 end ary = [large_number, *[small_number]*10] m = ary.mean s2 = ary.map { |x| (x - m)**2 }.sum var = s2 / (ary.length - 1).to_f sd = Math.sqrt(var) with_array ary do it_is_float_equal(sd) end while true ary = Array.new(4) { 1.0 + rand*1e-6 } x = ary.map { |e| e**2 }.sum / ary.length.to_f y = (ary.sum / ary.length.to_f) ** 2 break if x < y end with_array ary do it { is_expected.to be > 0.0 } end end end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/spec/enum_spec.rb
spec/enum_spec.rb
require 'spec_helper' require 'enumerable/statistics' require 'delegate' RSpec.describe Enumerable do describe '#mean' do subject(:mean) { enum.mean(&block) } let(:block) { nil } with_enum [] do it_is_float_equal(0.0) context 'with a conversion block' do it_is_float_equal(0.0) it 'does not call the block' do expect { |b| enum.mean(&b) }.not_to yield_control end end end with_enum [3] do it_is_float_equal(3.0) with_conversion ->(v) { v * 2 }, 'v * 2' do it_is_float_equal(6.0) end end with_enum [3, 5] do it_is_float_equal(4.0) with_conversion ->(v) { v * 2 }, 'v * 2' do it_is_float_equal(8.0) end end with_enum [3, Rational(5), Complex(7, 3)] do it_is_complex_equal(Complex(5.0, 1.0)) end with_enum [Object.new] do specify do expect { subject }.to raise_error(TypeError) end end large_number = 100_000_000 small_number = 1e-9 until (large_number + small_number) == large_number small_number /= 10 end with_enum [large_number, *[small_number]*10] do it_is_float_equal((large_number + small_number*10)/11.0) end with_enum [Rational(large_number, 1), *[small_number]*10] do it_is_float_equal((large_number + small_number*10)/11.0) end with_enum [small_number, Rational(large_number, 1), *[small_number]*10] do it_is_float_equal((Rational(large_number, 1) + small_number*11)/12.0) end end describe '#variance' do subject(:variance) { enum.variance(&block) } let(:enum) { [].to_enum } let(:block) { nil } with_enum [] do it_is_float_nan context 'with a conversion block' do it_is_float_nan it 'does not call the block' do expect { |b| enum.variance(&b) }.not_to yield_control end end end with_enum [3] do it_is_float_nan with_conversion ->(v) { v * 2 }, 'v * 2' do it_is_float_nan end end with_enum [3, 5] do it_is_float_equal(2.0) context 'with population: nil' do subject(:variance) { enum.variance(population: nil, &block) } it_is_float_equal(2.0) end context 'with population: false' do subject(:variance) { enum.variance(population: false, &block) } it_is_float_equal(2.0) end context 'with population: true' do subject(:variance) { enum.variance(population: true, &block) } it_is_float_equal(1.0) end end with_enum [3.0, 5.0] do it_is_float_equal(2.0) end with_enum [Object.new] do specify do expect { subject }.to raise_error(TypeError) end end with_enum [Object.new, Object.new] do specify do expect { subject }.to raise_error(TypeError) end end large_number = 100_000_000 small_number = 1e-9 until (large_number + small_number) == large_number small_number /= 10 end ary = [large_number, *[small_number]*10] m = ary.mean s2 = ary.map { |x| (x - m)**2 }.sum var = s2 / (ary.length - 1).to_f with_enum ary do it_is_float_equal(var) end while true ary = Array.new(4) { 1.0 + rand*1e-6 } x = ary.map { |e| e**2 }.sum / ary.length.to_f y = (ary.sum / ary.length.to_f) ** 2 break if x < y end with_enum ary do it { is_expected.to be > 0.0 } end end describe '#mean_variance' do subject(:mean_variance) { enum.mean_variance(&block) } let(:enum) { [].each } let(:block) { nil } with_enum [] do specify do expect(subject[0]).to eq(0.0) expect(subject[1]).to be_nan end context 'with a conversion block' do it 'does not call the block' do expect { |b| enum.mean_variance(&b) }.not_to yield_control end end end with_enum [3] do specify do expect(subject[0]).to eq(3.0) expect(subject[1]).to be_nan end with_conversion ->(v) { v * 2 }, 'v * 2' do specify do expect(subject[0]).to eq(6.0) expect(subject[1]).to be_nan end end end with_enum [3.0, 5.0] do context 'with population: nil' do subject(:mean_variance) { enum.mean_variance(population: nil, &block) } specify do expect(subject[0]).to eq(4.0) expect(subject[1]).to eq(2.0) end end context 'with population: false' do subject(:mean_variance) { enum.mean_variance(population: false, &block) } specify do expect(subject[0]).to eq(4.0) expect(subject[1]).to eq(2.0) end end context 'with population: true' do subject(:mean_variance) { enum.mean_variance(population: true, &block) } specify do expect(subject[0]).to eq(4.0) expect(subject[1]).to eq(1.0) end end end with_enum [Object.new] do specify do expect { subject }.to raise_error(TypeError) end end large_number = 100_000_000 small_number = 1e-9 until (large_number + small_number) == large_number small_number /= 10 end ary = [large_number, *[small_number]*10] m = ary.mean s2 = ary.map { |x| (x - m)**2 }.sum var = s2 / (ary.length - 1).to_f with_enum ary do it { is_expected.to eq([m, var]) } end while true ary = Array.new(4) { 1.0 + rand*1e-6 } x = ary.map { |e| e**2 }.sum / ary.length.to_f y = (ary.sum / ary.length.to_f) ** 2 break if x < y end with_enum ary do it { is_expected.to eq([ary.mean, ary.variance]) } end end describe '#stdev' do subject(:stdev) { enum.stdev(&block) } let(:enum) { [].to_enum } let(:block) { nil } with_enum [] do it_is_float_nan context 'with a conversion block' do it_is_float_nan it 'does not call the block' do expect { |b| enum.stdev(&b) }.not_to yield_control end end end with_enum [3] do it_is_float_nan with_conversion ->(v) { v * 2 }, 'v * 2' do it_is_float_nan end end with_enum [3, 5] do it_is_float_equal(Math.sqrt(2.0)) context 'with population: nil' do subject(:stdev) { enum.stdev(population: nil, &block) } it_is_float_equal(Math.sqrt(2.0)) end context 'with population: false' do subject(:stdev) { enum.stdev(population: false, &block) } it_is_float_equal(Math.sqrt(2.0)) end context 'with population: true' do subject(:stdev) { enum.stdev(population: true, &block) } it_is_float_equal(1.0) end end with_enum [3.0, 5.0] do it_is_float_equal(Math.sqrt(2.0)) end with_enum [Object.new] do specify do expect { subject }.to raise_error(TypeError) end end with_enum [Object.new, Object.new] do specify do expect { subject }.to raise_error(TypeError) end end large_number = 100_000_000 small_number = 1e-9 until (large_number + small_number) == large_number small_number /= 10 end ary = [large_number, *[small_number]*10] m = ary.mean s2 = ary.map { |x| (x - m)**2 }.sum var = s2 / (ary.length - 1).to_f sd = Math.sqrt(var) with_enum ary do it_is_float_equal(sd) end while true ary = Array.new(4) { 1.0 + rand*1e-6 } x = ary.map { |e| e**2 }.sum / ary.length.to_f y = (ary.sum / ary.length.to_f) ** 2 break if x < y end with_enum ary do it { is_expected.to be > 0.0 } end end describe '#mean_stdev' do subject(:mean_stdev) { enum.mean_stdev(&block) } let(:enum) { [].each } let(:block) { nil } with_enum [] do specify do expect(subject[0]).to eq(0.0) expect(subject[1]).to be_nan end context 'with a conversion block' do it 'does not call the block' do expect { |b| enum.mean_stdev(&b) }.not_to yield_control end end end with_enum [3] do specify do expect(subject[0]).to eq(3.0) expect(subject[1]).to be_nan end with_conversion ->(v) { v * 2 }, 'v * 2' do specify do expect(subject[0]).to eq(6.0) expect(subject[1]).to be_nan end end end with_enum [3.0, 5.0] do context 'with population: nil' do subject(:mean_stdev) { enum.mean_stdev(population: nil, &block) } specify do expect(subject[0]).to eq(4.0) expect(subject[1]).to eq(Math.sqrt(2.0)) end end context 'with population: false' do subject(:mean_stdev) { enum.mean_stdev(population: false, &block) } specify do expect(subject[0]).to eq(4.0) expect(subject[1]).to eq(Math.sqrt(2.0)) end end context 'with population: true' do subject(:mean_stdev) { enum.mean_stdev(population: true, &block) } specify do expect(subject[0]).to eq(4.0) expect(subject[1]).to eq(1.0) end end end with_enum [Object.new] do specify do expect { subject }.to raise_error(TypeError) end end large_number = 100_000_000 small_number = 1e-9 until (large_number + small_number) == large_number small_number /= 10 end ary = [large_number, *[small_number]*10] m = ary.mean s2 = ary.map { |x| (x - m)**2 }.sum var = s2 / (ary.length - 1).to_f sd = Math.sqrt(var) with_enum ary do it { is_expected.to eq([m, sd]) } end while true ary = Array.new(4) { 1.0 + rand*1e-6 } x = ary.map { |e| e**2 }.sum / ary.length.to_f y = (ary.sum / ary.length.to_f) ** 2 break if x < y end with_enum ary do it { is_expected.to eq([ary.mean, Math.sqrt(ary.variance)]) } end end end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/spec/range_spec.rb
spec/range_spec.rb
require 'spec_helper' require 'enumerable/statistics' require 'delegate' RSpec.describe Enumerable do describe '#sum' do subject(:sum) { enum.sum(init, &block) } let(:init) { 0 } let(:block) { nil } with_enum 1..0 do it_is_int_equal(0) with_init(0.0) do it_is_float_equal(0.0) end context 'with a conversion block' do it 'does not call the conversion block' do expect { |b| enum.sum(&b) }.not_to yield_control end end end with_enum 3..3 do it_is_int_equal(3) with_init(0.0) do it_is_float_equal(3.0) end end with_enum 3..5 do it_is_int_equal(12) end with_enum 1..2 do with_init(10)do it_is_int_equal(13) with_conversion ->(v) { v * 2 }, 'v * 2' do it_is_int_equal(16) end end end it 'calls a block for each item once' do yielded = [] range = 1..3 expect(range.each.sum {|x| yielded << x; x * 2 }).to eq(12) expect(yielded).to eq(range.to_a) end with_enum :a..:b do specify do expect { subject }.to raise_error(TypeError) end end with_enum "a".."c" do with_init("") do it { is_expected.to eq("abc") } end end end describe '#mean' do subject(:mean) { enum.mean(&block) } let(:block) { nil } with_enum 1..0 do it_is_float_equal(0.0) context 'with a conversion block' do it_is_float_equal(0.0) it 'does not call the block' do expect { |b| enum.mean(&b) }.not_to yield_control end end end with_enum 3..3 do it_is_float_equal(3.0) with_conversion ->(v) { v * 2 }, 'v * 2' do it_is_float_equal(6.0) end end with_enum 3..5 do it_is_float_equal(4.0) with_conversion ->(v) { v * 2 }, 'v * 2' do it_is_float_equal(8.0) end end end end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/spec/hash_spec.rb
spec/hash_spec.rb
require 'spec_helper' require 'enumerable/statistics' require 'delegate' RSpec.describe Hash do describe '#sum' do subject(:sum) { enum.sum(init, &block) } let(:init) { 0 } let(:block) { nil } with_enum({}) do it_is_int_equal(0) with_init(0.0) do it_is_float_equal(0.0) end context 'with a conversion block' do it 'does not call the conversion block' do expect { |b| enum.sum(&b) }.not_to yield_control end end end with_enum({ a: 3 }) do with_conversion ->((_, v)) { v }, '(k, v) -> v' do it_is_int_equal(3) with_init(0.0) do it_is_float_equal(3.0) end end end with_enum({ a: 3, b: 5 }) do with_conversion ->((_, v)) { v }, '(k, v) -> v' do it_is_int_equal(8) end end with_enum({ a: 3, b: 5, c: 7 }) do with_conversion ->((_, v)) { v }, '(k, v) -> v' do it_is_int_equal(15) end end with_enum({ a: 3, b: Rational(5) }) do with_conversion ->((_, v)) { v }, '(k, v) -> v' do it_is_rational_equal(Rational(8)) end end with_enum({ a: 3, b: 5, c: 7.0 }) do with_conversion ->((_, v)) { v }, '(k, v) -> v' do it_is_float_equal(15.0) end end with_enum({ a: 3, b: Rational(5), c: 7.0 }) do with_conversion ->((_, v)) { v }, '(k, v) -> v' do it_is_float_equal(15.0) end end with_enum({ a: 3, b: Rational(5), c: Complex(0, 1) }) do with_conversion ->((_, v)) { v }, '(k, v) -> v' do it_is_complex_equal(Complex(8, 1)) end end with_enum({ a: 3, b: Rational(5), c: 7.0, d: Complex(0, 1) }) do with_conversion ->((_, v)) { v }, '(k, v) -> v' do it_is_complex_equal(Complex(15.0, 1)) end end with_enum({ a: 3.5, b: 5 }) do with_conversion ->((_, v)) { v }, '(k, v) -> v' do it_is_float_equal(8.5) end end with_enum({ a: 2, b: 8.5 }) do with_conversion ->((_, v)) { v }, '(k, v) -> v' do it_is_float_equal(10.5) end end with_enum({ a: Rational(1, 2), b: Rational(1, 3) }) do with_conversion ->((_, v)) { v }, '(k, v) -> v' do it_is_rational_equal(Rational(5, 6)) end end with_enum({ a: 2.0, b: Complex(0, 3.0) }) do with_conversion ->((_, v)) { v }, '(k, v) -> v' do it_is_complex_equal(Complex(2.0, 3.0)) end end it 'calls a block for each item once' do yielded = [] three = SimpleDelegator.new(3) hash = { a: 1, b: 2.0, c: three } expect(hash.sum {|k, x| yielded << x; x * 2 }).to eq(12.0) expect(yielded).to eq(hash.values) end with_enum({ a: Object.new }) do with_conversion ->((_, v)) { v }, '(k, v) -> v' do specify do expect { subject }.to raise_error(TypeError) end end end large_number = 100_000_000 small_number = 1e-9 until (large_number + small_number) == large_number small_number /= 10 end with_enum Hash[[*:a..:k].zip([large_number, *[small_number]*10])] do with_conversion ->((_, v)) { v }, '(k, v) -> v' do it_is_float_equal(large_number + small_number*10) end end with_enum Hash[[*:a..:k].zip([Rational(large_number, 1), *[small_number]*10])] do with_conversion ->((_, v)) { v }, '(k, v) -> v' do it_is_float_equal(large_number + small_number*10) end end with_enum Hash[[*:a..:l].zip([small_number, Rational(large_number, 1), *[small_number]*10])] do with_conversion ->((_, v)) { v }, '(k, v) -> v' do it_is_float_equal(large_number + small_number*11) end end with_enum({ a: "a", b: "b", c: "c"}) do with_conversion ->((_, v)) { v }, '(k, v) -> v' do with_init("") do it { is_expected.to eq("abc") } end end end with_enum({ a: [1], b: [[2]], c: [3]}) do with_conversion ->((_, v)) { v }, '(k, v) -> v' do with_init([]) do it { is_expected.to eq([1, [2], 3]) } end end end with_enum({ 1 => 2, 3 => 4, 5 => 6 }) do with_conversion ->((k, v)) { k * v }, '(k, v) -> k * v' do it_is_int_equal(44) end end end end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/spec/value_counts_spec.rb
spec/value_counts_spec.rb
require 'spec_helper' require 'enumerable/statistics' RSpec.shared_examples_for 'value_counts' do matrix = [ { normalize: false, sort: true, ascending: false, dropna: true, result: {"g"=>11, "b"=>10, "f"=>6, "e"=>4, "a"=>3, "c"=>3, "d"=>3} }, { normalize: false, sort: true, ascending: false, dropna: false, result: {"g"=>11, "b"=>10, "f"=>6, "e"=>4, "a"=>3, "c"=>3, "d"=>3, nil=>3} }, { normalize: false, sort: true, ascending: true, dropna: true, result: {"a"=>3, "c"=>3, "d"=>3, "e"=>4, "f"=>6, "b"=>10, "g"=>11} }, { normalize: false, sort: true, ascending: true, dropna: false, result: {nil=>3, "a"=>3, "c"=>3, "d"=>3, "e"=>4, "f"=>6, "b"=>10, "g"=>11} }, { normalize: false, sort: false, ascending: false, dropna: true, result: {"b"=>10, "g"=>11, "a"=>3, "f"=>6, "e"=>4, "c"=>3, "d"=>3} }, { normalize: false, sort: false, ascending: false, dropna: false, result: {nil=>3, "b"=>10, "g"=>11, "a"=>3, "f"=>6, "e"=>4, "c"=>3, "d"=>3} }, { normalize: false, sort: false, ascending: true, dropna: true, result: {"b"=>10, "g"=>11, "a"=>3, "f"=>6, "e"=>4, "c"=>3, "d"=>3} }, { normalize: false, sort: false, ascending: true, dropna: false, result: {nil=>3, "b"=>10, "g"=>11, "a"=>3, "f"=>6, "e"=>4, "c"=>3, "d"=>3} }, { normalize: true, sort: true, ascending: false, dropna: true, result: {"g"=>0.275, "b"=>0.250, "f"=>0.150, "e"=>0.100, "a"=>0.075, "c"=>0.075, "d"=>0.075} }, { normalize: true, sort: true, ascending: false, dropna: false, result: {"g"=>11/43.0, "b"=>10/43.0, "f"=>6/43.0, "e"=>4/43.0, "a"=>3/43.0, "c"=>3/43.0, "d"=>3/43.0, nil=>3/43.0} }, { normalize: true, sort: true, ascending: true, dropna: true, result: {"a"=>0.075, "c"=>0.075, "d"=>0.075, "e"=>0.100, "f"=>0.150, "b"=>0.250, "g"=>0.275} }, { normalize: true, sort: true, ascending: true, dropna: false, result: {nil=>3/43.0, "a"=>3/43.0, "c"=>3/43.0, "d"=>3/43.0, "e"=>4/43.0, "f"=>6/43.0, "b"=>10/43.0, "g"=>11/43.0} }, { normalize: true, sort: false, ascending: false, dropna: true, result: {"b"=>0.250, "g"=>0.275, "a"=>0.075, "f"=>0.150, "e"=>0.100, "c"=>0.075, "d"=>0.075} }, { normalize: true, sort: false, ascending: false, dropna: false, result: {nil=>3/43.0, "b"=>10/43.0, "g"=>11/43.0, "a"=>3/43.0, "f"=>6/43.0, "e"=>4/43.0, "c"=>3/43.0, "d"=>3/43.0} }, { normalize: true, sort: false, ascending: true, dropna: true, result: {"b"=>0.250, "g"=>0.275, "a"=>0.075, "f"=>0.150, "e"=>0.100, "c"=>0.075, "d"=>0.075} }, { normalize: true, sort: false, ascending: true, dropna: false, result: {nil=>3/43.0, "b"=>10/43.0, "g"=>11/43.0, "a"=>3/43.0, "f"=>6/43.0, "e"=>4/43.0, "c"=>3/43.0, "d"=>3/43.0} }, ] matrix.each do |params| param_values = params.values_at(:normalize, :sort, :ascending, :dropna) context "with normalize: %s, sort: %s, ascending: %s, dropna: %s" % param_values do args = params.dup expected_result = args.delete(:result) specify "the order of counts" do result_values = receiver.value_counts(**args).values expected_values = expected_result.values expect(result_values).to eq(expected_values) end specify "pairs" do result_pairs = receiver.value_counts(**args).to_a.sort_by {|a| a[0].to_s } expected_pairs = expected_result.to_a.sort_by {|a| a[0].to_s } expect(result_pairs).to eq(expected_pairs) end end end end RSpec.describe Array do describe '#value_counts' do let(:receiver) do 'bggbafgeeebgbbaccdgdgdbbgbgffbaffggcegbf'.chars.tap do |ary| ary[5, 0] = nil ary[15, 0] = nil ary[20, 0] = nil end end include_examples 'value_counts' end end RSpec.describe Hash do describe '#value_counts' do let(:array) do 'bggbafgeeebgbbaccdgdgdbbgbgffbaffggcegbf'.chars.tap do |ary| ary[5, 0] = nil ary[15, 0] = nil ary[20, 0] = nil end end let(:receiver) do array.map.with_index {|x, i| [i, x] }.to_h end include_examples 'value_counts' end end RSpec.describe Enumerable do describe '#value_counts' do let(:array) do 'bggbafgeeebgbbaccdgdgdbbgbgffbaffggcegbf'.chars.tap do |ary| ary[5, 0] = nil ary[15, 0] = nil ary[20, 0] = nil end end let(:receiver) do array.each end include_examples 'value_counts' end end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/spec/spec_helper.rb
spec/spec_helper.rb
RSpec.configure do |config| config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true end config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end config.filter_run :focus config.run_all_when_everything_filtered = true config.example_status_persistence_file_path = "spec/reports/examples.txt" config.disable_monkey_patching! config.warnings = true if config.files_to_run.one? config.default_formatter = 'doc' end config.profile_examples = 10 config.order = :random Kernel.srand config.seed end Dir[File.expand_path('../support/**/*.rb', __FILE__)].each do |file| require file end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/spec/support/macros.rb
spec/support/macros.rb
module Enumerable module Statistics module RSpecMacros def self.included(mod) mod.module_eval do extend ExampleGroupMethods end end module ExampleGroupMethods def with_array(given_ary, &example_group_block) describe "for #{given_ary.inspect}" do let(:ary) { given_ary } module_eval(&example_group_block) end end def with_enum(given_enum, description=given_enum.inspect, &example_group_block) if given_enum.is_a? Array given_enum = given_enum.each description += '.each' end describe "for #{description}" do let(:enum) { given_enum } module_eval(&example_group_block) end end def with_init(init_value, &example_group_block) context "with init=#{init_value.inspect}" do let(:init) { init_value } module_eval(&example_group_block) end end def with_conversion(conversion_block, description, &example_group_block) context "with conversion `#{description}`" do let(:block) { conversion_block } module_eval(&example_group_block) end end def it_equals_with_type(x, type) it { is_expected.to be_an(type) } it { is_expected.to eq(x) } end def it_is_int_equal(n) it_equals_with_type(n, Integer) end def it_is_rational_equal(n) it_equals_with_type(n, Rational) end def it_is_float_equal(n) it_equals_with_type(n, Float) end def it_is_float_nan it { is_expected.to be_an(Float) } it { is_expected.to be_nan } end def it_is_complex_equal(n) it_equals_with_type(n, Complex) end end end end end RSpec.configure do |c| c.include Enumerable::Statistics::RSpecMacros end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/spec/histogram/array_spec.rb
spec/histogram/array_spec.rb
require 'spec_helper' require 'enumerable/statistics' RSpec.describe Array, '#histogram' do let(:ary) { [] } let(:args) { [] } let(:kwargs) { {} } subject(:histogram) { ary.histogram(*args, **kwargs) } with_array [] do context 'default' do specify do expect(histogram.edges).to eq([0.0]) expect(histogram.weights).to eq([]) expect(histogram.closed).to eq(:left) expect(histogram.density?).to eq(false) end end context 'closed: :right' do let(:kwargs) { {closed: :right} } specify do expect(histogram.edges).to eq([0.0]) expect(histogram.weights).to eq([]) expect(histogram.closed).to eq(:right) expect(histogram.density?).to eq(false) end end end with_array [1] do context 'default' do specify do expect(histogram.edges).to eq([1.0, 2.0]) expect(histogram.weights).to eq([1]) expect(histogram.closed).to eq(:left) expect(histogram.density?).to eq(false) end end context 'nbins: 5' do let(:args) { [5] } specify do expect(histogram.edges).to eq([1.0, 2.0]) expect(histogram.weights).to eq([1]) expect(histogram.closed).to eq(:left) expect(histogram.density?).to eq(false) end end end with_array [1, 2] do context 'closed: :left' do let(:kwargs) { {closed: :left} } specify do expect(histogram.edges).to eq([1.0, 1.5, 2.0, 2.5]) expect(histogram.weights).to eq([1, 0, 1]) expect(histogram.closed).to eq(:left) expect(histogram.density?).to eq(false) end end end with_array [1, 2, 3, 4, 5, 6, 7, 8, 9] do context 'default' do specify do expect(histogram.edges).to eq([0.0, 2.0, 4.0, 6.0, 8.0, 10.0]) expect(histogram.weights).to eq([1, 2, 2, 2, 2]) expect(histogram.closed).to eq(:left) expect(histogram.density?).to eq(false) end end context 'nbins: :auto' do let(:args) { [:auto] } specify do expect(histogram.edges).to eq([0.0, 2.0, 4.0, 6.0, 8.0, 10.0]) expect(histogram.weights).to eq([1, 2, 2, 2, 2]) expect(histogram.closed).to eq(:left) expect(histogram.density?).to eq(false) end end context 'closed: :right' do let(:kwargs) { {closed: :right} } specify do expect(histogram.edges).to eq([0.0, 2.0, 4.0, 6.0, 8.0, 10.0]) expect(histogram.weights).to eq([2, 2, 2, 2, 1]) expect(histogram.closed).to eq(:right) expect(histogram.density?).to eq(false) end end context 'nbins: 3' do let(:args) { [3] } specify do expect(histogram.edge).to eq([0.0, 5.0, 10.0]) expect(histogram.weights).to eq([4, 5]) expect(histogram.closed).to eq(:left) expect(histogram.density?).to eq(false) end end context 'weights: [3, 3, 3, 2, 2, 2, 1, 1, 1]' do let(:kwargs) { {weights: [3, 3, 3, 2, 2, 2, 1, 1, 1]} } specify do expect(histogram.edge).to eq([0.0, 2.0, 4.0, 6.0, 8.0, 10.0]) expect(histogram.weights).to eq([3, 6, 4, 3, 2]) expect(histogram.closed).to eq(:left) expect(histogram.density?).to eq(false) end end context 'weights: [3, 3i, 3, 2, 2, 2, 1, 1, 1]' do let(:kwargs) { {weights: [3, 3i, 3, 2, 2, 2, 1, 1, 1]} } specify do expect { histogram }.to raise_error(TypeError) end end context 'edges: [0.0, 3.0, 6.0, 9.0, 12.0]' do let(:kwargs) { {edges: [0.0, 3.0, 6.0, 9.0, 12.0]} } specify do expect(histogram.edge).to eq([0.0, 3.0, 6.0, 9.0, 12.0]) expect(histogram.weights).to eq([2, 3, 3, 1]) expect(histogram.closed).to eq(:left) expect(histogram.density?).to eq(false) end end context 'edges: [3.0, 6.0, 9.0]' do let(:kwargs) { {edges: [3.0, 6.0, 9.0]} } specify do expect(histogram.edge).to eq([3.0, 6.0, 9.0]) expect(histogram.weights).to eq([3, 3]) expect(histogram.closed).to eq(:left) expect(histogram.density?).to eq(false) end end end context "with 10,000 normal random values" do let(:ary) do random = Random.new(13) Array.new(10000) do # Box-Muller method x, y = random.rand, random.rand Math.sqrt(-2 * Math.log(x)) * Math.cos(2 * Math::PI * y) end end context "default" do specify do expect(histogram.edge).to eq([-4.0, -3.5, -3.0, -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5]) expect(histogram.weights).to eq([2, 14, 50, 161, 451, 884, 1508, 1880, 1966, 1538, 893, 432, 160, 51, 10]) expect(histogram.closed).to eq(:left) expect(histogram.density?).to eq(false) end end context "closed: :right" do let(:kwargs) { {closed: :right} } specify do expect(histogram.edge).to eq([-4.0, -3.5, -3.0, -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5]) expect(histogram.weights).to eq([2, 14, 50, 161, 451, 884, 1508, 1880, 1966, 1538, 893, 432, 160, 51, 10]) expect(histogram.closed).to eq(:right) expect(histogram.density?).to eq(false) end end context "nbins: 5" do let(:args) { [5] } specify do expect(histogram.edge).to eq([-4.0, -2.0, 0.0, 2.0, 4.0]) expect(histogram.weights).to eq([227, 4723, 4829, 221]) expect(histogram.closed).to eq(:left) expect(histogram.density?).to eq(false) end end end end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/spec/percentile/array_spec.rb
spec/percentile/array_spec.rb
require 'spec_helper' RSpec.describe Array, '#percentile' do let(:ary) { [] } let(:args) { [0, 25, 50, 75, 100] } subject(:percentile) { ary.percentile(args) } with_array [] do specify do expect { percentile }.to raise_error(ArgumentError) end end with_array [1] do specify do expect(percentile).to eq([1.0, 1.0, 1.0, 1.0, 1.0]) end end with_array [1, 2, 3] do specify do expect(percentile).to eq([1.0, 1.5, 2.0, 2.5, 3.0]) end end with_array [1, 2] do let(:args) { 50 } specify do expect(percentile).to eq(1.5) end end with_array [1, 2] do let(:args) { [50] } specify do expect(percentile).to eq([1.5]) end end with_array [1, 2, 3] do let(:args) { [100, 25, 0, 75, 50] } specify do expect(percentile).to eq([3.0, 1.5, 1.0, 2.5, 2.0]) end end with_array [1, Float::NAN, 3] do let(:args) { [100, 25] } specify do expect(percentile).to match([be_nan, be_nan]) end end with_array [1, nil, 3] do let(:args) { [100, 25] } specify do expect(percentile).to match([be_nan, be_nan]) end end end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/spec/median/array_spec.rb
spec/median/array_spec.rb
require 'spec_helper' RSpec.describe Array, '#median' do let(:ary) { [] } subject(:median) { ary.median } with_array [] do it_is_float_nan end with_array [1] do it_is_int_equal(1) end with_array [0, 1] do it_is_float_equal(0.5) end with_array [0.0444502, 0.0463301, 0.141249, 0.0606775] do it_is_float_equal((0.0463301 + 0.0606775) / 2.0) end with_array [0.0463301, 0.0444502, 0.141249] do it_is_float_equal(0.0463301) end with_array [0.0444502, 0.141249, 0.0463301] do it_is_float_equal(0.0463301) end with_array [0.0444502, Float::NAN, 0.0463301] do it_is_float_nan end with_array [0.0444502, nil, 0.0463301] do it_is_float_nan end end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/lib/enumerable_statistics.rb
lib/enumerable_statistics.rb
require_relative "enumerable_statistics/version" require_relative "enumerable_statistics/array_ext" require_relative "enumerable_statistics/histogram"
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/lib/enumerable/statistics.rb
lib/enumerable/statistics.rb
require "enumerable_statistics" require "enumerable/statistics/extension"
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/lib/enumerable_statistics/version.rb
lib/enumerable_statistics/version.rb
module EnumerableStatistics VERSION = '2.1.0' module Version numbers, TAG = VERSION.split('-', 2) MAJOR, MINOR, MICRO = numbers.split('.', 3).map(&:to_i) STRING = VERSION end end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/lib/enumerable_statistics/array_ext.rb
lib/enumerable_statistics/array_ext.rb
module EnumerableStatistics module ArrayExtension def find_max n = size return nil if n == 0 imax, i = 0, 1 while i < n imax = i if self[i] > self[imax] i += 1 end [self[imax], imax] end def argmax find_max[1] end def find_min n = size return nil if n == 0 imin, i = 0, 1 while i < n imin = i if self[i] < self[imax] i += 1 end [self[imin], imin] end def argmin find_min[1] end end Array.include ArrayExtension end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
red-data-tools/enumerable-statistics
https://github.com/red-data-tools/enumerable-statistics/blob/480765c1e114d6166f98756546243e2a9ee6488e/lib/enumerable_statistics/histogram.rb
lib/enumerable_statistics/histogram.rb
module EnumerableStatistics class Histogram < Struct.new(:edges, :weights, :closed, :isdensity) alias edge edges alias density? isdensity end end
ruby
MIT
480765c1e114d6166f98756546243e2a9ee6488e
2026-01-04T17:48:35.335590Z
false
lewagon/foot_traffic
https://github.com/lewagon/foot_traffic/blob/a3e577c2f1d3222f2b8d279465823061584d4a60/spec/foot_traffic_spec.rb
spec/foot_traffic_spec.rb
RSpec.describe FootTraffic do it "has a version number" do expect(FootTraffic::VERSION).not_to be nil end end
ruby
MIT
a3e577c2f1d3222f2b8d279465823061584d4a60
2026-01-04T17:48:16.406321Z
false
lewagon/foot_traffic
https://github.com/lewagon/foot_traffic/blob/a3e577c2f1d3222f2b8d279465823061584d4a60/spec/spec_helper.rb
spec/spec_helper.rb
require "bundler/setup" require "foot_traffic" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end end
ruby
MIT
a3e577c2f1d3222f2b8d279465823061584d4a60
2026-01-04T17:48:16.406321Z
false
lewagon/foot_traffic
https://github.com/lewagon/foot_traffic/blob/a3e577c2f1d3222f2b8d279465823061584d4a60/examples/cookies.rb
examples/cookies.rb
require "concurrent" # concurrent-ruby tokens = [] # imaginary array of auth tokens cookies = Concurrent::Hash.new opts = { headless: false, # Headless or not timeout: 300, # How long to wait for new tab to open, set for high value slowmo: 0.1, # How fast do you want bots to type window_size: [1200, 800] } FootTraffic::Session.start(options: opts, quit: true) do |window, pool| tokens.each do |token| sleep(1) # Need to sleep so we can propely save cookies pool << window.with_tab { |tab| tab.goto("https://example.com/sign_in/#{token}") cookies[token] = tab.cookies["_example_session"].value } end pool.wait end FootTraffic::Session.start(options: opts) do |window| tokens.each do |token| sleep(1) # Wait to properly load cookies window.with_tab do |tab| tab.cookies.clear tab.cookies.set( name: "_example_session", domain: "example.lewagon.co", value: cookies[token] ) tab.goto("https://example.com/protected_route") end end 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.rb
examples/multi_threaded.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 do |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) end end
ruby
MIT
a3e577c2f1d3222f2b8d279465823061584d4a60
2026-01-04T17:48:16.406321Z
false