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 |
|---|---|---|---|---|---|---|---|---|
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/faraday/request.rb | lib/notion/faraday/request.rb | # frozen_string_literal: true
module Notion
module Faraday
module Request
def get(path, options = {})
request(:get, path, options)
end
def patch(path, options = {})
request(:patch, path, options)
end
def post(path, options = {})
request(:post, path, options)
end
def put(path, options = {})
request(:put, path, options)
end
def delete(path, options = {})
request(:delete, path, options)
end
private
def request(method, path, options)
response = connection.send(method) do |request|
request.headers['Authorization'] = "Bearer #{token}"
request.headers['Notion-Version'] = Notion::NOTION_REQUEST_VERSION
case method
when :get, :delete
request.url(path, options)
when :post, :put, :patch
request.headers['Content-Type'] = 'application/json'
request.path = path
request.body = options.to_json unless options.empty?
end
request.options.merge!(options.delete(:request)) if options.key?(:request)
end
response.body
end
end
end
end
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/faraday/response/raise_error.rb | lib/notion/faraday/response/raise_error.rb | # frozen_string_literal: true
module Notion
module Faraday
module Response
class RaiseError < ::Faraday::Response::Json
def on_complete(env)
raise Notion::Api::Errors::TooManyRequests, env.response if env.status == 429
return if env.success?
body = env.body
return unless body
error_code = body['code']
error_message = body['message']
error_details = body['details']
error_class = Notion::Api::Errors::ERROR_CLASSES[error_code]
error_class ||= Notion::Api::Errors::NotionError
raise error_class.new(error_message, error_details, env.response)
end
def call(env)
super
rescue ::Faraday::ParsingError
raise Notion::Api::Errors::ParsingError.new('parsing_error', env.response)
end
end
end
end
end
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
phacks/notion-ruby-client | https://github.com/phacks/notion-ruby-client/blob/f651b70b665358f9001489c1a06325eb70ec3f64/lib/notion/faraday/response/wrap_error.rb | lib/notion/faraday/response/wrap_error.rb | # frozen_string_literal: true
module Notion
module Faraday
module Response
class WrapError < ::Faraday::Response::Json
UNAVAILABLE_ERROR_STATUSES = (500..599).freeze
def on_complete(env)
return unless UNAVAILABLE_ERROR_STATUSES.cover?(env.status)
raise Notion::Api::Errors::UnavailableError.new('unavailable_error', env.response)
end
def call(env)
super
rescue ::Faraday::TimeoutError, ::Faraday::ConnectionFailed
raise Notion::Api::Errors::TimeoutError.new('timeout_error', env.response)
end
end
end
end
end
| ruby | MIT | f651b70b665358f9001489c1a06325eb70ec3f64 | 2026-01-04T17:51:29.828973Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/rails_helper.rb | spec/rails_helper.rb | ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../dummy/config/environment", __FILE__)
require 'rspec/rails'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.infer_base_class_for_anonymous_controllers = false
config.infer_spec_type_from_file_location!
config.render_views = true
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/spec_helper.rb | spec/spec_helper.rb | RSpec.configure do |config|
config.expect_with(:rspec) do |c|
c.syntax = :should
end
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/support/patch.rb | spec/support/patch.rb | # Rails 4.2 call `initialize` inside `recycle!`. However Ruby 2.6 doesn't allow calling `initialize` twice.
# See for detail: https://github.com/rails/rails/issues/34790
if RUBY_VERSION.to_f >= 2.6 && Rails::VERSION::MAJOR == 4
class ActionController::TestResponse
prepend Module.new {
def recycle!
@mon_mutex_owner_object_id = nil
@mon_mutex = nil
super
end
}
end
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/controllers/examples_controller_spec.rb | spec/controllers/examples_controller_spec.rb | require "rails_helper"
describe ExamplesController do
describe "#index" do
context "when render as HTML" do
subject do
get :index
end
context "when RenderWithPathComment is not attached" do
before do
ViewSourceMap.detach
end
it "does not show partial view's relative path as HTML comment" do
should be_successful
response.body.should_not include("<!-- BEGIN app/views/examples/_example.html.erb -->")
response.body.should_not include("<!-- END app/views/examples/_example.html.erb -->")
response.body.should_not include("<!-- BEGIN app/views/examples/index.html.erb -->")
response.body.should_not include("<!-- END app/views/examples/index.html.erb -->")
end
end
context "when RenderWithPathComment is attached" do
before do
ViewSourceMap.attach
end
it "shows partial view's relative path as HTML comment" do
should be_successful
response.body.should include("<!-- BEGIN app/views/examples/_example.html.erb -->")
response.body.should include("<!-- END app/views/examples/_example.html.erb -->")
response.body.should include("<!-- BEGIN app/views/examples/index.html.erb -->")
response.body.should include("<!-- END app/views/examples/index.html.erb -->")
end
it "does not show partial view's relative path as HTML comment when disabled" do
response.body.should_not include("<!-- BEGIN app/views/examples/_example_disabled.html.erb -->")
response.body.should_not include("<!-- BEGIN app/views/examples/_example_disabled_partial.html.erb -->")
end
end
context "when ViewSourceMap is detached" do
before do
ViewSourceMap.detach
end
it "does not show partial view's relative path as HTML comment" do
should be_successful
response.body.should_not include("<!-- BEGIN app/views/examples/_example.html.erb -->")
response.body.should_not include("<!-- END app/views/examples/_example.html.erb -->")
response.body.should_not include("<!-- BEGIN app/views/examples/index.html.erb -->")
response.body.should_not include("<!-- END app/views/examples/index.html.erb -->")
end
end
end
context "when render as TEXT" do
subject do
get "index", :format => "text"
end
context "when RenderWithPathComment is attached" do
before do
ViewSourceMap.attach
end
it "does not show partial view's relative path as HTML comment" do
should be_successful
response.body.should_not include("<!-- BEGIN app/views/examples/_example.text.erb -->")
response.body.should_not include("<!-- END app/views/examples/_example.text.erb -->")
response.body.should_not include("<!-- BEGIN app/views/examples/index.text.erb -->")
response.body.should_not include("<!-- END app/views/examples/index.text.erb -->")
end
end
end
end
describe "#render_to_string" do
before do
ViewSourceMap.attach
end
let(:locals) { {} }
subject do
described_class.new.render_to_string(partial: 'example', locals: locals)
end
context 'with no option' do
it "shows partial view's relative path as HTML comment" do
subject.should include("<!-- BEGIN app/views/examples/_example.html.erb -->")
end
end
context 'with disable option' do
let(:locals) { { view_source_map: false } }
it "does not show partial view's relative path as HTML comment" do
subject.should_not include("<!-- BEGIN app/views/examples/_example.html.erb -->")
end
end
end
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/dummy/app/helpers/application_helper.rb | spec/dummy/app/helpers/application_helper.rb | module ApplicationHelper
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/dummy/app/controllers/examples_controller.rb | spec/dummy/app/controllers/examples_controller.rb | class ExamplesController < ApplicationController
protect_from_forgery
def index
end
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/dummy/app/controllers/application_controller.rb | spec/dummy/app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
protect_from_forgery
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/dummy/config/application.rb | spec/dummy/config/application.rb | require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
Bundler.require
require "view_source_map"
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
# config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
end
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/dummy/config/environment.rb | spec/dummy/config/environment.rb | # Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
Dummy::Application.initialize!
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/dummy/config/routes.rb | spec/dummy/config/routes.rb | Dummy::Application.routes.draw do
resources :examples, :only => :index
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/dummy/config/boot.rb | spec/dummy/config/boot.rb | require 'rubygems'
gemfile = File.expand_path('../../../../Gemfile', __FILE__)
if File.exist?(gemfile)
ENV['BUNDLE_GEMFILE'] = gemfile
require 'bundler'
Bundler.setup
end
$:.unshift File.expand_path('../../../../lib', __FILE__) | ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/dummy/config/initializers/session_store.rb | spec/dummy/config/initializers/session_store.rb | # Be sure to restart your server when you modify this file.
Dummy::Application.config.session_store :cookie_store, :key => '_dummy_session'
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rails generate session_migration")
# Dummy::Application.config.session_store :active_record_store
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/dummy/config/initializers/wrap_parameters.rb | spec/dummy/config/initializers/wrap_parameters.rb | # Be sure to restart your server when you modify this file.
#
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters :format => [:json]
end
# Disable root element in JSON by default.
ActiveSupport.on_load(:active_record) do
self.include_root_in_json = false
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/dummy/config/initializers/inflections.rb | spec/dummy/config/initializers/inflections.rb | # Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format
# (all these examples are active by default):
# ActiveSupport::Inflector.inflections 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 do |inflect|
# inflect.acronym 'RESTful'
# end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/dummy/config/initializers/backtrace_silencers.rb | spec/dummy/config/initializers/backtrace_silencers.rb | # Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/dummy/config/initializers/mime_types.rb | spec/dummy/config/initializers/mime_types.rb | # Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/dummy/config/initializers/secret_token.rb | spec/dummy/config/initializers/secret_token.rb | # Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
secret_key_base = 'c3a62b6e2236d66db4f1213324eb87df2889765d0b12c67ccb272c7c56f2d56b4ed07200100058aeb5f4d0ee94ea9cab8bad2044f21cac59b58dfb78f2886238'
if Rails.gem_version >= Gem::Version.new('5')
Dummy::Application.config.secret_key_base = secret_key_base
else
Dummy::Application.config.secret_token = secret_key_base
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/dummy/config/environments/test.rb | spec/dummy/config/environments/test.rb | Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Configure static asset server for tests with Cache-Control for performance
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
# Log error messages when you accidentally call methods on nil
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Raise exception on mass assignment protection for Active Record models
# config.active_record.mass_assignment_sanitizer = :strict
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
config.eager_load = false
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/dummy/config/environments/development.rb | spec/dummy/config/environments/development.rb | Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Raise exception on mass assignment protection for Active Record models
config.active_record.mass_assignment_sanitizer = :strict
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
config.active_record.auto_explain_threshold_in_seconds = 0.5
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/spec/dummy/config/environments/production.rb | spec/dummy/config/environments/production.rb | Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/lib/view_source_map_rails_6_0.rb | lib/view_source_map_rails_6_0.rb | module ViewSourceMap
def self.attach
return if defined?(@attached) && @attached
@attached = true
ActionView::PartialRenderer.class_eval do
def render_with_path_comment(context, options, block)
content = render_without_path_comment(context, options, block)
return content if ViewSourceMap.force_disabled?(options)
if @lookup_context.formats.first == :html
case content
when ActionView::AbstractRenderer::RenderedCollection
content.rendered_templates.each do |rendered_template|
ViewSourceMap.wrap_rendered_template(rendered_template, options)
end
when ActionView::AbstractRenderer::RenderedTemplate
ViewSourceMap.wrap_rendered_template(content, options)
end
end
content
end
alias_method :render_without_path_comment, :render
alias_method :render, :render_with_path_comment
end
ActionView::TemplateRenderer.class_eval do
def render_template_with_path_comment(view, template, layout_name, locals)
render_with_layout(view, template, layout_name, locals) do |layout|
instrument(:template, identifier: template.identifier, layout: layout.try(:virtual_path)) do
content = template.render(view, locals) { |*name| view._layout_for(*name) }
return content if ViewSourceMap.force_disabled?(locals)
path = Pathname.new(template.identifier)
if @lookup_context.formats.first == :html && path.file?
name = path.relative_path_from(Rails.root)
"<!-- BEGIN #{name} -->\n#{content}<!-- END #{name} -->".html_safe
else
content
end
end
end
end
alias_method :render_template_without_path_comment, :render_template
alias_method :render_template, :render_template_with_path_comment
end
end
# @private
# @param [ActionView::AbstractRenderer::RenderedTemplate] rendered_template
# @param [Hash] options Options passed to #render method.
def self.wrap_rendered_template(rendered_template, options)
name = begin
if options[:layout]
"#{options[:layout]}(layout)"
elsif rendered_template.template.respond_to?(:identifier)
Pathname.new(rendered_template.template.identifier).relative_path_from(Rails.root)
end
end
if name
rendered_template.instance_variable_set(
:@body,
"<!-- BEGIN #{name} -->\n#{rendered_template.body}<!-- END #{name} -->".html_safe
)
end
end
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/lib/view_source_map_rails_4_and_5.rb | lib/view_source_map_rails_4_and_5.rb | module ViewSourceMap
def self.attach
return if defined?(@attached) && @attached
@attached = true
ActionView::PartialRenderer.class_eval do
def render_with_path_comment(context, options, block)
content = render_without_path_comment(context, options, block)
return content if ViewSourceMap.force_disabled?(options)
if @lookup_context.rendered_format == :html
if options[:layout]
name = "#{options[:layout]}(layout)"
else
return content unless @template.respond_to?(:identifier)
path = Pathname.new(@template.identifier)
name = path.relative_path_from(Rails.root)
end
"<!-- BEGIN #{name} -->\n#{content}<!-- END #{name} -->".html_safe
else
content
end
end
alias_method :render_without_path_comment, :render
alias_method :render, :render_with_path_comment
end
ActionView::TemplateRenderer.class_eval do
def render_template_with_path_comment(template, layout_name = nil, locals = {})
view, locals = @view, locals || {}
render_with_layout(layout_name, locals) do |layout|
instrument(:template, :identifier => template.identifier, :layout => layout.try(:virtual_path)) do
content = template.render(view, locals) { |*name| view._layout_for(*name) }
return content if ViewSourceMap.force_disabled?(locals)
path = Pathname.new(template.identifier)
if @lookup_context.rendered_format == :html && path.file?
name = path.relative_path_from(Rails.root)
"<!-- BEGIN #{name} -->\n#{content}<!-- END #{name} -->".html_safe
else
content
end
end
end
end
alias_method :render_template_without_path_comment, :render_template
alias_method :render_template, :render_template_with_path_comment
end
end
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/lib/view_source_map.rb | lib/view_source_map.rb | require 'view_source_map/railtie'
if Rails.gem_version >= Gem::Version.new('6.1')
require 'view_source_map_rails_6'
elsif Rails.gem_version >= Gem::Version.new('6.0')
require 'view_source_map_rails_6_0'
else
require 'view_source_map_rails_4_and_5'
end
module ViewSourceMap
def self.detach
return unless @attached
@attached = false
ActionView::PartialRenderer.class_eval do
undef_method :render_with_path_comment
alias_method :render, :render_without_path_comment
end
ActionView::TemplateRenderer.class_eval do
undef_method :render_template_with_path_comment
alias_method :render_template, :render_template_without_path_comment
end
end
def self.force_disabled?(options)
return false if options.nil?
return true if options[:view_source_map] == false
return false if options[:locals].nil?
options[:locals][:view_source_map] == false
end
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/lib/view_source_map_rails_6.rb | lib/view_source_map_rails_6.rb | module ViewSourceMap
def self.attach
return if defined?(@attached) && @attached
@attached = true
ActionView::PartialRenderer.class_eval do
def render_with_path_comment(partial, context, block)
content = render_without_path_comment(partial, context, block)
return content if ViewSourceMap.force_disabled?(@options)
if @lookup_context.formats.first == :html
case content
when ActionView::AbstractRenderer::RenderedCollection
content.rendered_templates.each do |rendered_template|
ViewSourceMap.wrap_rendered_template(rendered_template, @options)
end
when ActionView::AbstractRenderer::RenderedTemplate
ViewSourceMap.wrap_rendered_template(content, @options)
end
end
content
end
alias_method :render_without_path_comment, :render
alias_method :render, :render_with_path_comment
end
ActionView::TemplateRenderer.class_eval do
def render_template_with_path_comment(view, template, layout_name, locals)
render_with_layout(view, template, layout_name, locals) do |layout|
ActiveSupport::Notifications.instrument(
'render_template.action_view',
identifier: template.identifier,
layout: layout.try(:virtual_path),
) do
content = template.render(view, locals) { |*name| view._layout_for(*name) }
return content if ViewSourceMap.force_disabled?(locals)
path = Pathname.new(template.identifier)
if @lookup_context.formats.first == :html && path.file?
name = path.relative_path_from(Rails.root)
"<!-- BEGIN #{name} -->\n#{content}<!-- END #{name} -->".html_safe
else
content
end
end
end
end
alias_method :render_template_without_path_comment, :render_template
alias_method :render_template, :render_template_with_path_comment
end
end
# @private
# @param [ActionView::AbstractRenderer::RenderedTemplate] rendered_template
# @param [Hash] options Options passed to #render method.
def self.wrap_rendered_template(rendered_template, options)
name = begin
if options[:layout]
"#{options[:layout]}(layout)"
elsif rendered_template.template.respond_to?(:identifier)
Pathname.new(rendered_template.template.identifier).relative_path_from(Rails.root)
end
end
if name
rendered_template.instance_variable_set(
:@body,
"<!-- BEGIN #{name} -->\n#{rendered_template.body}<!-- END #{name} -->".html_safe
)
end
end
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/lib/view_source_map/version.rb | lib/view_source_map/version.rb | module ViewSourceMap
VERSION = "0.3.0"
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
r7kamura/view_source_map | https://github.com/r7kamura/view_source_map/blob/75b99802cdc2efc4481967dc0e484c45d865b3b1/lib/view_source_map/railtie.rb | lib/view_source_map/railtie.rb | module ViewSourceMap
class Railtie < Rails::Railtie
initializer "render_with_path_comment.initialize" do
if !ENV["DISABLE_VIEW_SOURCE_MAP"] && Rails.env.development?
ViewSourceMap.attach
end
end
end
end
| ruby | MIT | 75b99802cdc2efc4481967dc0e484c45d865b3b1 | 2026-01-04T17:51:33.791483Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/spec_helper.rb | spec/spec_helper.rb | ENV["RAILS_ENV"] = "test"
ENV["DB"] ||= "sqlite3"
require 'rails'
require "pagy_cursor"
require "dummy/config/environment"
ActiveRecord::Migration.verbose = false
ActiveRecord::Tasks::DatabaseTasks.drop_current 'test'
ActiveRecord::Tasks::DatabaseTasks.create_current 'test'
ActiveRecord::Migration.maintain_test_schema!
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
class TestController
include Pagy::Backend
attr_reader :params
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/app/jobs/application_job.rb | spec/dummy/app/jobs/application_job.rb | class ApplicationJob < ActiveJob::Base
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/app/helpers/application_helper.rb | spec/dummy/app/helpers/application_helper.rb | module ApplicationHelper
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/app/controllers/application_controller.rb | spec/dummy/app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/app/models/post.rb | spec/dummy/app/models/post.rb | class Post < ApplicationRecord
before_create :set_uuid # for test with uuid
def set_uuid
self.id = SecureRandom.uuid
end
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/app/models/application_record.rb | spec/dummy/app/models/application_record.rb | class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/app/models/user.rb | spec/dummy/app/models/user.rb | class User < ApplicationRecord
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/app/mailers/application_mailer.rb | spec/dummy/app/mailers/application_mailer.rb | class ApplicationMailer < ActionMailer::Base
default from: 'from@example.com'
layout 'mailer'
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/app/channels/application_cable/channel.rb | spec/dummy/app/channels/application_cable/channel.rb | module ApplicationCable
class Channel < ActionCable::Channel::Base
end
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/app/channels/application_cable/connection.rb | spec/dummy/app/channels/application_cable/connection.rb | module ApplicationCable
class Connection < ActionCable::Connection::Base
end
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/db/schema.rb | spec/dummy/db/schema.rb | # encoding: UTF-8
# frozen_string_literal: true
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20190307102949) do
create_table(:users) do |t|
t.string :name
t.timestamps
end
create_table(:posts, id: false) do |t|
t.string :id, limit: 36, primary_key: true, null: false
t.string :title
t.timestamps
end
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/db/migrate/20190307102949_create_tables.rb | spec/dummy/db/migrate/20190307102949_create_tables.rb | class CreateTables < ActiveRecord::Migration[5.0]
def self.up
create_table(:users) do |t|
t.string :name
t.timestamps
end
create_table(:posts, id: false) do |t|
t.string :id, limit: 36, primary_key: true, null: false
t.string :title
t.timestamps
end
end
def self.down
drop_table :users
drop_table :posts
end
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/config/application.rb | spec/dummy/config/application.rb | require_relative 'boot'
require 'rails/all'
Bundler.require(*Rails.groups)
require "pagy_cursor"
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
end
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/config/environment.rb | spec/dummy/config/environment.rb | # Load the Rails application.
require_relative 'application'
# Initialize the Rails application.
Rails.application.initialize!
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/config/puma.rb | spec/dummy/config/puma.rb | # 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.
#
threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
threads threads_count, threads_count
# 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 number of `workers` to boot in clustered mode.
# Workers are forked webserver processes. If using threads and workers together
# the concurrency of the application would be max `threads` * `workers`.
# Workers do not work on JRuby or Windows (both of which do not support
# processes).
#
# workers ENV.fetch("WEB_CONCURRENCY") { 2 }
# Use the `preload_app!` method when specifying a `workers` number.
# This directive tells Puma to first boot the application and load code
# before forking the application. This takes advantage of Copy On Write
# process behavior so workers use less memory.
#
# preload_app!
# Allow puma to be restarted by `rails restart` command.
plugin :tmp_restart
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/config/routes.rb | spec/dummy/config/routes.rb | Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/config/spring.rb | spec/dummy/config/spring.rb | %w[
.ruby-version
.rbenv-vars
tmp/restart.txt
tmp/caching-dev.txt
].each { |path| Spring.watch(path) }
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/config/boot.rb | spec/dummy/config/boot.rb | # Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../Gemfile', __dir__)
require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
$LOAD_PATH.unshift File.expand_path('../../../lib', __dir__)
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/config/initializers/content_security_policy.rb | spec/dummy/config/initializers/content_security_policy.rb | # Be sure to restart your server when you modify this file.
# Define an application-wide content security policy
# For further information see the following documentation
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
# Rails.application.config.content_security_policy do |policy|
# policy.default_src :self, :https
# policy.font_src :self, :https, :data
# policy.img_src :self, :https, :data
# policy.object_src :none
# policy.script_src :self, :https
# policy.style_src :self, :https
# # Specify URI for violation reports
# # policy.report_uri "/csp-violation-report-endpoint"
# end
# If you are using UJS then enable automatic nonce generation
# Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
# Report CSP violations to a specified URI
# For further information see the following documentation:
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
# Rails.application.config.content_security_policy_report_only = true
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/config/initializers/filter_parameter_logging.rb | spec/dummy/config/initializers/filter_parameter_logging.rb | # Be sure to restart your server when you modify this file.
# Configure sensitive parameters which will be filtered from the log file.
Rails.application.config.filter_parameters += [:password]
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/config/initializers/application_controller_renderer.rb | spec/dummy/config/initializers/application_controller_renderer.rb | # Be sure to restart your server when you modify this file.
# ActiveSupport::Reloader.to_prepare do
# ApplicationController.renderer.defaults.merge!(
# http_host: 'example.org',
# https: false
# )
# end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/config/initializers/wrap_parameters.rb | spec/dummy/config/initializers/wrap_parameters.rb | # Be sure to restart your server when you modify this file.
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json]
end
# To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do
# self.include_root_in_json = true
# end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/config/initializers/inflections.rb | spec/dummy/config/initializers/inflections.rb | # Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format. Inflections
# are locale specific, and you may define rules for as many different
# locales as you wish. All of these examples are active by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.acronym 'RESTful'
# end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/config/initializers/cookies_serializer.rb | spec/dummy/config/initializers/cookies_serializer.rb | # Be sure to restart your server when you modify this file.
# Specify a serializer for the signed and encrypted cookie jars.
# Valid options are :json, :marshal, and :hybrid.
Rails.application.config.action_dispatch.cookies_serializer = :json
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/config/initializers/backtrace_silencers.rb | spec/dummy/config/initializers/backtrace_silencers.rb | # Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/config/initializers/mime_types.rb | spec/dummy/config/initializers/mime_types.rb | # Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/config/environments/test.rb | spec/dummy/config/environments/test.rb | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure 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
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# 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
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/config/environments/development.rb | spec/dummy/config/environments/development.rb | 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 on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.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 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
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
# config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/dummy/config/environments/production.rb | spec/dummy/config/environments/production.rb | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.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.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# 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 = "dummy_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/pagy_cursor/cursor_spec.rb | spec/pagy_cursor/cursor_spec.rb | require "spec_helper"
require "pagy_cursor/pagy/extras/cursor"
RSpec.describe Pagy::Backend do
let(:backend) { TestController.new }
context 'no records' do
it 'returns an empty collection' do
pagy, records = backend.send(:pagy_cursor, User.all)
expect(records).to be_empty
expect(pagy.has_more?).to eq(false)
end
end
context 'with records' do
before do
User.destroy_all
1.upto(100) do |i|
User.create!(name: "user#{i}")
end
end
it "paginates with defaults" do
pagy, records = backend.send(:pagy_cursor, User.all)
expect(records.map(&:name)).to eq(
["user100", "user99", "user98", "user97", "user96",
"user95", "user94", "user93", "user92", "user91",
"user90", "user89", "user88", "user87", "user86",
"user85", "user84", "user83", "user82", "user81"])
expect(pagy.has_more?).to eq(true)
end
it "paginates with before" do
record = User.find_by! name: "user30"
pagy, records = backend.send(:pagy_cursor, User.all, before: record.id)
expect(records.first.name).to eq("user29")
expect(records.last.name).to eq("user10")
expect(pagy.has_more?).to eq(true)
end
it "paginates with before nearly starting" do
record = User.find_by! name: "user5"
pagy, records = backend.send(:pagy_cursor, User.all, before: record.id)
expect(records.first.name).to eq("user4")
expect(records.last.name).to eq("user1")
expect(pagy.has_more?).to eq(false)
end
it "paginates with after" do
record = User.find_by! name: "user30"
pagy, records = backend.send(:pagy_cursor, User.all, after: record.id)
expect(records.first.name).to eq("user31")
expect(records.last.name).to eq("user50")
expect(pagy.has_more?).to eq(true)
end
it "paginates with after nearly ending" do
record = User.find_by! name: "user90"
pagy, records = backend.send(:pagy_cursor, User.all, after: record.id)
expect(records.first.name).to eq("user91")
expect(records.last.name).to eq("user100")
expect(pagy.has_more?).to eq(false)
end
it 'returns a chainable relation' do
_, records = backend.send(:pagy_cursor, User.all)
expect(records).to be_a(ActiveRecord::Relation)
end
end
context 'with ordered records' do
before do
User.delete_all
1.upto(100) do |i|
User.create!(name: "user#{i}")
end
sleep 1 # delay for mysql timestamp
user = User.find_by name: "user81"
user.update(name: "I am user81")
end
it "paginates with defaults" do
pagy, records = backend.send(
:pagy_cursor,
User.all,
order: {
updated_at: :desc
}
)
expect(records.map(&:name)).to eq(
["I am user81", "user100", "user99", "user98", "user97", "user96",
"user95", "user94", "user93", "user92", "user91",
"user90", "user89", "user88", "user87", "user86",
"user85", "user84", "user83", "user82"])
expect(pagy.has_more?).to eq(true)
expect(pagy.order[:updated_at]).to eq(:desc)
end
end
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/spec/pagy_cursor/uuid_cursor_spec.rb | spec/pagy_cursor/uuid_cursor_spec.rb | require "spec_helper"
require "pagy_cursor/pagy/extras/uuid_cursor"
RSpec.describe PagyCursor do
let(:backend) { TestController.new }
context 'no records' do
it 'returns an empty collection' do
pagy, records = backend.send(:pagy_uuid_cursor, Post.all)
expect(records).to be_empty
expect(pagy.has_more?).to eq(false)
end
end
context 'with records' do
before do
Post.destroy_all
1.upto(100) do |i|
Post.create!(title: "post#{i}", created_at: (100-i).minutes.ago)
end
end
it "paginates with defaults" do
pagy, records = backend.send(:pagy_uuid_cursor, Post.all)
expect(records.map(&:title)).to eq(
["post100", "post99", "post98", "post97", "post96",
"post95", "post94", "post93", "post92", "post91",
"post90", "post89", "post88", "post87", "post86",
"post85", "post84", "post83", "post82", "post81"])
expect(pagy.has_more?).to eq(true)
end
it "paginates with before" do
record = Post.find_by! title: "post30"
pagy, records = backend.send(:pagy_uuid_cursor, Post.all, before: record.id)
expect(records.first.title).to eq("post29")
expect(records.last.title).to eq("post10")
expect(pagy.has_more?).to eq(true)
end
it "paginates with before nearly starting" do
record = Post.find_by! title: "post5"
pagy, records = backend.send(:pagy_uuid_cursor, Post.all, before: record.id)
expect(records.first.title).to eq("post4")
expect(records.last.title).to eq("post1")
expect(pagy.has_more?).to eq(false)
end
it "paginates with after" do
record = Post.find_by! title: "post30"
pagy, records = backend.send(:pagy_uuid_cursor, Post.all, after: record.id)
expect(records.first.title).to eq("post31")
expect(records.last.title).to eq("post50")
expect(pagy.has_more?).to eq(true)
end
it "paginates with before nearly starting" do
record = Post.find_by! title: "post90"
pagy, records = backend.send(:pagy_uuid_cursor, Post.all, after: record.id)
expect(records.first.title).to eq("post91")
expect(records.last.title).to eq("post100")
expect(pagy.has_more?).to eq(false)
end
it 'returns a chainable relation' do
_, records = backend.send(:pagy_uuid_cursor, User.all)
expect(records).to be_a(ActiveRecord::Relation)
end
end
context 'with ordered records' do
before do
Post.destroy_all
1.upto(100) do |i|
Post.create!(title: "post#{i}", created_at: (100-i).minutes.ago)
end
sleep 1 # delay for mysql timestamp
post = Post.find_by(title: "post81")
post.update(title: "post81 was updated")
sleep 1 # delay for mysql timestamp
post = Post.find_by(title: "post91")
post.update(title: "post91 was updated")
end
it "paginates with defaults" do
pagy, records = backend.send(
:pagy_uuid_cursor,
Post.all,
order: {
updated_at: :desc
}
)
expect(records.map(&:title)).to eq(
["post91 was updated", "post81 was updated","post100", "post99", "post98",
"post97", "post96", "post95", "post94", "post93",
"post92", "post90", "post89", "post88", "post87",
"post86", "post85", "post84", "post83", "post82",])
expect(pagy.has_more?).to eq(true)
expect(pagy.order[:updated_at]).to eq(:desc)
end
it "paginates with before updated record" do
previous_record = Post.find_by(title: "post91 was updated")
pagy, records = backend.send(
:pagy_uuid_cursor,
Post.all,
order: {
updated_at: :desc
},
before: previous_record.id
)
expect(records.map(&:title)).to eq(
["post81 was updated", "post100", "post99", "post98", "post97",
"post96", "post95", "post94", "post93", "post92",
"post90", "post89", "post88", "post87", "post86",
"post85", "post84", "post83", "post82", "post80"
])
expect(pagy.has_more?).to eq(true)
expect(pagy.order[:updated_at]).to eq(:desc)
end
it "paginates with after updated record" do
previous_record = Post.find_by(title: "post91 was updated")
pagy, records = backend.send(
:pagy_uuid_cursor,
Post.all,
order: {
updated_at: :desc
},
after: previous_record.id
)
expect(records.map(&:title)).to eq([])
expect(pagy.has_more?).to eq(false)
expect(pagy.order[:updated_at]).to eq(:desc)
end
end
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/lib/pagy_cursor.rb | lib/pagy_cursor.rb | # frozen_string_literal: true
require "pagy"
require "pagy_cursor/pagy/cursor"
require "pagy_cursor/pagy/extras/cursor"
require "pagy_cursor/pagy/extras/uuid_cursor"
require "pagy_cursor/version"
module PagyCursor
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/lib/pagy_cursor/version.rb | lib/pagy_cursor/version.rb | # frozen_string_literal: true
module PagyCursor
VERSION = "0.8.0"
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/lib/pagy_cursor/pagy/cursor.rb | lib/pagy_cursor/pagy/cursor.rb | # frozen_string_literal: true
class Pagy
class Cursor < Pagy
attr_reader :before, :after, :arel_table, :primary_key, :order, :comparison, :position
attr_accessor :has_more
alias_method :has_more?, :has_more
def initialize(vars)
@vars = DEFAULT.merge(vars.delete_if { |_, v| v.nil? || v == "" })
@items = vars[:items] || DEFAULT[:items]
@before = vars[:before]
@after = vars[:after]
@arel_table = vars[:arel_table]
@primary_key = vars[:primary_key]
@reorder = vars[:order] || {}
if @before.present? and @after.present?
raise(ArgumentError, "before and after can not be both mentioned")
end
if vars[:backend] == "uuid"
@comparison = "lt" # arel table less than
@position = @before
@order = @reorder.merge({ :created_at => :desc, @primary_key => :desc })
if @after.present? || (@reorder.present? && @reorder.values.uniq.first&.to_sym == :asc)
@comparison = "gt" # arel table greater than
@position = @after
@order = @reorder.merge({ :created_at => :asc, @primary_key => :asc })
end
else
@comparison = "lt"
@position = @before
@order = @reorder.merge({ @primary_key => :desc })
if @after.present? || (@reorder.present? && @reorder.values.uniq.first&.to_sym == :asc)
@comparison = "gt"
@position = @after
@order = @reorder.merge({ @primary_key => :asc })
end
end
end
end
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/lib/pagy_cursor/pagy/extras/cursor.rb | lib/pagy_cursor/pagy/extras/cursor.rb | # frozen_string_literal: true
class Pagy
module Backend; private # the whole module is private so no problem with including it in a controller
# Return Pagy object and items
def pagy_cursor(collection, vars = {})
pagy = Pagy::Cursor.new(pagy_cursor_get_vars(collection, vars))
items = pagy_cursor_get_items(collection, pagy, pagy.position)
pagy.has_more = pagy_cursor_has_more?(items, pagy)
[pagy, items]
end
def pagy_cursor_get_vars(collection, vars)
pagy_set_items_from_params(vars) if defined?(ItemsExtra)
vars[:arel_table] = collection.arel_table
vars[:primary_key] = collection.primary_key
vars[:backend] = "sequence"
vars
end
def pagy_cursor_get_items(collection, pagy, position = nil)
if position.present?
sql_comparison = pagy.arel_table[pagy.primary_key].send(pagy.comparison, position)
collection.where(sql_comparison).reorder(pagy.order).limit(pagy.items)
else
collection.reorder(pagy.order).limit(pagy.items)
end
end
def pagy_cursor_has_more?(collection, pagy)
return false if collection.empty?
next_position = collection.last[pagy.primary_key]
pagy_cursor_get_items(collection, pagy, next_position).exists?
end
end
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
Uysim/pagy-cursor | https://github.com/Uysim/pagy-cursor/blob/104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a/lib/pagy_cursor/pagy/extras/uuid_cursor.rb | lib/pagy_cursor/pagy/extras/uuid_cursor.rb | # frozen_string_literal: true
class Pagy
module Backend; private # the whole module is private so no problem with including it in a controller
# Return Pagy object and items
def pagy_uuid_cursor(collection, vars = {})
pagy = Pagy::Cursor.new(pagy_uuid_cursor_get_vars(collection, vars))
items = pagy_uuid_cursor_get_items(collection, pagy, pagy.position)
pagy.has_more = pagy_uuid_cursor_has_more?(items, pagy)
return pagy, items
end
def pagy_uuid_cursor_get_vars(collection, vars)
pagy_set_items_from_params(vars) if defined?(ItemsExtra)
vars[:arel_table] = collection.arel_table
vars[:primary_key] = collection.primary_key
vars[:backend] = "uuid"
vars
end
def pagy_uuid_cursor_get_items(collection, pagy, position = nil)
if position.present?
arel_table = pagy.arel_table
# If the primary sort key is not "created_at"
# Select the primary sort key
# pagy.order should be something like:
# [:created_at, :id] or [:foo_column, ..., :created_at, :id]
primary_sort_key = pagy.order.keys.detect { |order_key| ![:created_at, :id].include?(order_key.to_sym) } || :created_at
select_previous_row = arel_table.project(arel_table[primary_sort_key]).
where(arel_table[pagy.primary_key].eq(position))
sql_comparison = arel_table[primary_sort_key].
send(pagy.comparison, select_previous_row).
or(
arel_table[primary_sort_key].eq(select_previous_row).
and(arel_table[pagy.primary_key].send(pagy.comparison, position))
)
collection = collection.where(sql_comparison)
end
collection.reorder(pagy.order).limit(pagy.items)
end
def pagy_uuid_cursor_has_more?(collection, pagy)
return false if collection.empty?
next_position = collection.last[pagy.primary_key]
pagy_uuid_cursor_get_items(collection, pagy, next_position).exists?
end
end
end
| ruby | MIT | 104c9cb2a15ac5e9cdd75e8ac276173a998d5a7a | 2026-01-04T17:51:32.347526Z | false |
ktheory/dalli-elasticache | https://github.com/ktheory/dalli-elasticache/blob/100fe160eca65a4fa9f81ce607b4190b1f73687c/spec/endpoint_spec.rb | spec/endpoint_spec.rb | # frozen_string_literal: true
require_relative 'spec_helper'
describe 'Dalli::Elasticache::AutoDiscovery::Endpoint' do
let(:endpoint) do
Dalli::Elasticache::AutoDiscovery::Endpoint.new(arg_string)
end
describe '.new' do
context 'when the string includes both host and port' do
let(:arg_string) { 'my-cluster.cfg.use1.cache.amazonaws.com:12345' }
it 'parses host' do
expect(endpoint.host).to eq 'my-cluster.cfg.use1.cache.amazonaws.com'
end
it 'parses port' do
expect(endpoint.port).to eq 12_345
end
end
context 'when the string includes only a host' do
let(:arg_string) { 'example.cfg.use1.cache.amazonaws.com' }
it 'parses host' do
expect(endpoint.host).to eq 'example.cfg.use1.cache.amazonaws.com'
end
it 'parses port' do
expect(endpoint.port).to eq 11_211
end
end
context 'when the string is nil' do
let(:arg_string) { nil }
it 'raises ArgumentError' do
expect do
endpoint
end.to raise_error ArgumentError, "Unable to parse configuration endpoint address - #{arg_string}"
end
end
context 'when the string contains disallowed characters in the host' do
let(:arg_string) { 'my-cluster?.cfg.use1.cache.amazonaws.com:12345' }
it 'raises ArgumentError' do
expect do
endpoint
end.to raise_error ArgumentError, "Unable to parse configuration endpoint address - #{arg_string}"
end
end
context 'when the string contains disallowed characters in the port' do
let(:arg_string) { 'my-cluster.cfg.use1.cache.amazonaws.com:1234a5' }
it 'raises ArgumentError' do
expect do
endpoint
end.to raise_error ArgumentError, "Unable to parse configuration endpoint address - #{arg_string}"
end
end
context 'when the string contains trailing characters' do
let(:arg_string) { 'my-cluster.cfg.use1.cache.amazonaws.com:12345abcd' }
it 'raises ArgumentError' do
expect do
endpoint
end.to raise_error ArgumentError, "Unable to parse configuration endpoint address - #{arg_string}"
end
end
context 'when the host in the string includes an underscore' do
let(:arg_string) { 'my_cluster.cfg.use1.cache.amazonaws.com:12345' }
it 'parses host' do
expect(endpoint.host).to eq 'my_cluster.cfg.use1.cache.amazonaws.com'
end
it 'parses port' do
expect(endpoint.port).to eq 12_345
end
end
end
end
| ruby | MIT | 100fe160eca65a4fa9f81ce607b4190b1f73687c | 2026-01-04T17:51:34.942242Z | false |
ktheory/dalli-elasticache | https://github.com/ktheory/dalli-elasticache/blob/100fe160eca65a4fa9f81ce607b4190b1f73687c/spec/stats_response_spec.rb | spec/stats_response_spec.rb | # frozen_string_literal: true
require_relative 'spec_helper'
describe 'Dalli::Elasticache::AutoDiscovery::StatsResponse' do
let(:response) { Dalli::Elasticache::AutoDiscovery::StatsResponse.new(response_text) }
describe '#engine_version' do
context 'when the version number is a number' do
let(:engine_version) { ['1.4.14', '1.5.6', '1.6.10'].sample }
context 'when the response with the version stat only includes the version number' do
let(:response_text) do
"STAT pid 1\r\nSTAT uptime 68717\r\nSTAT time 1398885375\r\n" \
"STAT version #{engine_version}\r\n" \
"STAT libevent 1.4.13-stable\r\nSTAT pointer_size 64\r\nSTAT rusage_user 0.136008\r\n" \
"STAT rusage_system 0.424026\r\nSTAT curr_connections 5\r\nSTAT total_connections 1159\r\n" \
"STAT connection_structures 6\r\nSTAT reserved_fds 5\r\nSTAT cmd_get 0\r\n" \
"STAT cmd_set 0\r\nSTAT cmd_flush 0\r\nSTAT cmd_touch 0\r\nSTAT cmd_config_get 4582\r\n" \
"STAT cmd_config_set 2\r\nSTAT get_hits 0\r\nSTAT get_misses 0\r\nSTAT delete_misses 0\r\n" \
"STAT delete_hits 0\r\nSTAT incr_misses 0\r\nSTAT incr_hits 0\r\nSTAT decr_misses 0\r\n" \
"STAT decr_hits 0\r\nSTAT cas_misses 0\r\nSTAT cas_hits 0\r\nSTAT cas_badval 0\r\n" \
"STAT touch_hits 0\r\nSTAT touch_misses 0\r\nSTAT auth_cmds 0\r\nSTAT auth_errors 0\r\n" \
"STAT bytes_read 189356\r\nSTAT bytes_written 2906615\r\nSTAT limit_maxbytes 209715200\r\n" \
"STAT accepting_conns 1\r\nSTAT listen_disabled_num 0\r\nSTAT threads 1\r\n" \
"STAT conn_yields 0\r\nSTAT curr_config 1\r\nSTAT hash_power_level 16\r\n" \
"STAT hash_bytes 524288\r\nSTAT hash_is_expanding 0\r\nSTAT expired_unfetched 0\r\n" \
"STAT evicted_unfetched 0\r\nSTAT bytes 0\r\nSTAT curr_items 0\r\nSTAT total_items 0\r\n" \
"STAT evictions 0\r\nSTAT reclaimed 0\r\n"
end
it 'parses out the engine version' do
expect(response.engine_version).to eq engine_version
end
end
context 'when the response with the version stat includes the version number and trailing text' do
let(:response_text) do
"STAT pid 1\r\nSTAT uptime 68717\r\nSTAT time 1398885375\r\n" \
"STAT version #{engine_version} #{SecureRandom.hex(5)}\r\n" \
"STAT libevent 1.4.13-stable\r\nSTAT pointer_size 64\r\nSTAT rusage_user 0.136008\r\n" \
"STAT rusage_system 0.424026\r\nSTAT curr_connections 5\r\nSTAT total_connections 1159\r\n" \
"STAT connection_structures 6\r\nSTAT reserved_fds 5\r\nSTAT cmd_get 0\r\n" \
"STAT cmd_set 0\r\nSTAT cmd_flush 0\r\nSTAT cmd_touch 0\r\nSTAT cmd_config_get 4582\r\n" \
"STAT cmd_config_set 2\r\nSTAT get_hits 0\r\nSTAT get_misses 0\r\nSTAT delete_misses 0\r\n" \
"STAT delete_hits 0\r\nSTAT incr_misses 0\r\nSTAT incr_hits 0\r\nSTAT decr_misses 0\r\n" \
"STAT decr_hits 0\r\nSTAT cas_misses 0\r\nSTAT cas_hits 0\r\nSTAT cas_badval 0\r\n" \
"STAT touch_hits 0\r\nSTAT touch_misses 0\r\nSTAT auth_cmds 0\r\nSTAT auth_errors 0\r\n" \
"STAT bytes_read 189356\r\nSTAT bytes_written 2906615\r\nSTAT limit_maxbytes 209715200\r\n" \
"STAT accepting_conns 1\r\nSTAT listen_disabled_num 0\r\nSTAT threads 1\r\n" \
"STAT conn_yields 0\r\nSTAT curr_config 1\r\nSTAT hash_power_level 16\r\n" \
"STAT hash_bytes 524288\r\nSTAT hash_is_expanding 0\r\nSTAT expired_unfetched 0\r\n" \
"STAT evicted_unfetched 0\r\nSTAT bytes 0\r\nSTAT curr_items 0\r\nSTAT total_items 0\r\n" \
"STAT evictions 0\r\nSTAT reclaimed 0\r\n"
end
it 'parses out the engine version' do
expect(response.engine_version).to eq engine_version
end
end
end
context "when the version number is the string 'unknown'" do
let(:engine_version) { 'UNKNOWN' }
context 'when the response with the version stat only includes the version number' do
let(:response_text) do
"STAT pid 1\r\nSTAT uptime 68717\r\nSTAT time 1398885375\r\n" \
"STAT version #{engine_version}\r\n" \
"STAT libevent 1.4.13-stable\r\nSTAT pointer_size 64\r\nSTAT rusage_user 0.136008\r\n" \
"STAT rusage_system 0.424026\r\nSTAT curr_connections 5\r\nSTAT total_connections 1159\r\n" \
"STAT connection_structures 6\r\nSTAT reserved_fds 5\r\nSTAT cmd_get 0\r\n" \
"STAT cmd_set 0\r\nSTAT cmd_flush 0\r\nSTAT cmd_touch 0\r\nSTAT cmd_config_get 4582\r\n" \
"STAT cmd_config_set 2\r\nSTAT get_hits 0\r\nSTAT get_misses 0\r\nSTAT delete_misses 0\r\n" \
"STAT delete_hits 0\r\nSTAT incr_misses 0\r\nSTAT incr_hits 0\r\nSTAT decr_misses 0\r\n" \
"STAT decr_hits 0\r\nSTAT cas_misses 0\r\nSTAT cas_hits 0\r\nSTAT cas_badval 0\r\n" \
"STAT touch_hits 0\r\nSTAT touch_misses 0\r\nSTAT auth_cmds 0\r\nSTAT auth_errors 0\r\n" \
"STAT bytes_read 189356\r\nSTAT bytes_written 2906615\r\nSTAT limit_maxbytes 209715200\r\n" \
"STAT accepting_conns 1\r\nSTAT listen_disabled_num 0\r\nSTAT threads 1\r\n" \
"STAT conn_yields 0\r\nSTAT curr_config 1\r\nSTAT hash_power_level 16\r\n" \
"STAT hash_bytes 524288\r\nSTAT hash_is_expanding 0\r\nSTAT expired_unfetched 0\r\n" \
"STAT evicted_unfetched 0\r\nSTAT bytes 0\r\nSTAT curr_items 0\r\nSTAT total_items 0\r\n" \
"STAT evictions 0\r\nSTAT reclaimed 0\r\n"
end
it "parses out the engine version as 'UNKNOWN'" do
expect(response.engine_version).to eq engine_version
end
end
context 'when the response with the version stat includes the version number and trailing text' do
let(:response_text) do
"STAT pid 1\r\nSTAT uptime 68717\r\nSTAT time 1398885375\r\n" \
"STAT version #{engine_version} #{SecureRandom.hex(5)}\r\n" \
"STAT libevent 1.4.13-stable\r\nSTAT pointer_size 64\r\nSTAT rusage_user 0.136008\r\n" \
"STAT rusage_system 0.424026\r\nSTAT curr_connections 5\r\nSTAT total_connections 1159\r\n" \
"STAT connection_structures 6\r\nSTAT reserved_fds 5\r\nSTAT cmd_get 0\r\n" \
"STAT cmd_set 0\r\nSTAT cmd_flush 0\r\nSTAT cmd_touch 0\r\nSTAT cmd_config_get 4582\r\n" \
"STAT cmd_config_set 2\r\nSTAT get_hits 0\r\nSTAT get_misses 0\r\nSTAT delete_misses 0\r\n" \
"STAT delete_hits 0\r\nSTAT incr_misses 0\r\nSTAT incr_hits 0\r\nSTAT decr_misses 0\r\n" \
"STAT decr_hits 0\r\nSTAT cas_misses 0\r\nSTAT cas_hits 0\r\nSTAT cas_badval 0\r\n" \
"STAT touch_hits 0\r\nSTAT touch_misses 0\r\nSTAT auth_cmds 0\r\nSTAT auth_errors 0\r\n" \
"STAT bytes_read 189356\r\nSTAT bytes_written 2906615\r\nSTAT limit_maxbytes 209715200\r\n" \
"STAT accepting_conns 1\r\nSTAT listen_disabled_num 0\r\nSTAT threads 1\r\n" \
"STAT conn_yields 0\r\nSTAT curr_config 1\r\nSTAT hash_power_level 16\r\n" \
"STAT hash_bytes 524288\r\nSTAT hash_is_expanding 0\r\nSTAT expired_unfetched 0\r\n" \
"STAT evicted_unfetched 0\r\nSTAT bytes 0\r\nSTAT curr_items 0\r\nSTAT total_items 0\r\n" \
"STAT evictions 0\r\nSTAT reclaimed 0\r\n"
end
it "parses out the engine version as 'UNKNOWN'" do
expect(response.engine_version).to eq engine_version
end
end
end
end
end
| ruby | MIT | 100fe160eca65a4fa9f81ce607b4190b1f73687c | 2026-01-04T17:51:34.942242Z | false |
ktheory/dalli-elasticache | https://github.com/ktheory/dalli-elasticache/blob/100fe160eca65a4fa9f81ce607b4190b1f73687c/spec/config_command_spec.rb | spec/config_command_spec.rb | # frozen_string_literal: true
require_relative 'spec_helper'
describe 'Dalli::Elasticache::AutoDiscovery::ConfigCommand' do
let(:host) { Faker::Internet.domain_name(subdomain: true) }
let(:port) { rand(1024..16_023) }
let(:command) { Dalli::Elasticache::AutoDiscovery::ConfigCommand.new(host, port, engine_version) }
let(:socket_response_lines) do
[
"CONFIG cluster 0 142\r\n",
"12\r\n",
'mycluster.0001.cache.amazonaws.com|10.112.21.1|11211 ' \
'mycluster.0002.cache.amazonaws.com|10.112.21.2|11211 ' \
"mycluster.0003.cache.amazonaws.com|10.112.21.3|11211\r\n",
"\r\n",
"END\r\n"
]
end
let(:expected_nodes) do
[
Dalli::Elasticache::AutoDiscovery::Node.new('mycluster.0001.cache.amazonaws.com',
'10.112.21.1',
11_211),
Dalli::Elasticache::AutoDiscovery::Node.new('mycluster.0002.cache.amazonaws.com',
'10.112.21.2',
11_211),
Dalli::Elasticache::AutoDiscovery::Node.new('mycluster.0003.cache.amazonaws.com',
'10.112.21.3',
11_211)
]
end
let(:mock_socket) { instance_double(TCPSocket) }
before do
allow(TCPSocket).to receive(:new).with(host, port).and_return(mock_socket)
allow(mock_socket).to receive(:close)
allow(mock_socket).to receive(:puts).with(cmd)
allow(mock_socket).to receive(:readline).and_return(*socket_response_lines)
end
context 'when the engine_version is 1.4.5' do
let(:engine_version) { '1.4.5' } # This is the only pre-1.4.14 version available on AWS
let(:cmd) { Dalli::Elasticache::AutoDiscovery::ConfigCommand::LEGACY_CONFIG_COMMAND }
context 'when the socket returns a valid response' do
before do
allow(mock_socket).to receive(:readline).and_return(*socket_response_lines)
end
it 'sends the legacy command and returns a ConfigResponse with expected values' do
response = command.response
expect(response).to be_a Dalli::Elasticache::AutoDiscovery::ConfigResponse
expect(response.version).to eq(12)
expect(response.nodes).to eq(expected_nodes)
expect(mock_socket).to have_received(:close)
end
end
end
context 'when the engine_version is greater than or equal to 1.4.14' do
let(:engine_version) { ['1.4.14', '1.5.6', '1.6.10'].sample }
let(:cmd) { Dalli::Elasticache::AutoDiscovery::ConfigCommand::CONFIG_COMMAND }
context 'when the socket returns a valid response' do
before do
allow(mock_socket).to receive(:readline).and_return(*socket_response_lines)
end
it 'sends the current command and returns a ConfigResponse with expected values' do
response = command.response
expect(response).to be_a Dalli::Elasticache::AutoDiscovery::ConfigResponse
expect(response.version).to eq(12)
expect(response.nodes).to eq(expected_nodes)
expect(mock_socket).to have_received(:close)
end
end
end
context 'when the engine_version is UNKNOWN or some other string' do
let(:engine_version) { ['UNKNOWN', SecureRandom.hex(4), nil].sample }
let(:cmd) { Dalli::Elasticache::AutoDiscovery::ConfigCommand::CONFIG_COMMAND }
context 'when the socket returns a valid response' do
before do
allow(mock_socket).to receive(:readline).and_return(*socket_response_lines)
end
it 'sends the current command and returns a ConfigResponse with expected values' do
response = command.response
expect(response).to be_a Dalli::Elasticache::AutoDiscovery::ConfigResponse
expect(response.version).to eq(12)
expect(response.nodes).to eq(expected_nodes)
expect(mock_socket).to have_received(:close)
end
end
end
end
| ruby | MIT | 100fe160eca65a4fa9f81ce607b4190b1f73687c | 2026-01-04T17:51:34.942242Z | false |
ktheory/dalli-elasticache | https://github.com/ktheory/dalli-elasticache/blob/100fe160eca65a4fa9f81ce607b4190b1f73687c/spec/stats_command_spec.rb | spec/stats_command_spec.rb | # frozen_string_literal: true
require_relative 'spec_helper'
describe 'Dalli::Elasticache::AutoDiscovery::StatsCommand' do
let(:host) { 'example.com' }
let(:port) { 12_345 }
let(:command) { Dalli::Elasticache::AutoDiscovery::StatsCommand.new(host, port) }
let(:engine_version) { ['1.4.5', '1.4.14', '1.5.6', '1.6.10'].sample }
let(:cmd) { "stats\r\n" }
let(:socket_response_lines) do
[
"STAT pid 1\r\n",
"STAT uptime 68717\r\n",
"STAT time 1398885375\r\n",
"STAT version #{engine_version}\r\n",
"STAT libevent 1.4.13-stable\r\n",
"STAT pointer_size 64\r\n",
"STAT rusage_user 0.136008\r\n",
"STAT rusage_system 0.424026\r\n",
"STAT curr_connections 5\r\n",
"STAT total_connections 1159\r\n",
"STAT connection_structures 6\r\n",
"STAT reserved_fds 5\r\n",
"STAT cmd_get 0\r\n",
"STAT cmd_set 0\r\n",
"STAT cmd_flush 0\r\n",
"STAT cmd_touch 0\r\n",
"STAT cmd_config_get 4582\r\n",
"STAT cmd_config_set 2\r\n",
"STAT get_hits 0\r\n",
"STAT get_misses 0\r\n",
"STAT delete_misses 0\r\n",
"STAT delete_hits 0\r\n",
"STAT incr_misses 0\r\n",
"STAT incr_hits 0\r\n",
"STAT decr_misses 0\r\n",
"STAT decr_hits 0\r\n",
"STAT cas_misses 0\r\n",
"STAT cas_hits 0\r\n",
"STAT cas_badval 0\r\n",
"STAT touch_hits 0\r\n",
"STAT touch_misses 0\r\n",
"STAT auth_cmds 0\r\n",
"STAT auth_errors 0\r\n",
"STAT bytes_read 189356\r\n",
"STAT bytes_written 2906615\r\n",
"STAT limit_maxbytes 209715200\r\n",
"STAT accepting_conns 1\r\n",
"STAT listen_disabled_num 0\r\n",
"STAT threads 1\r\n",
"STAT conn_yields 0\r\n",
"STAT curr_config 1\r\n",
"STAT hash_power_level 16\r\n",
"STAT hash_bytes 524288\r\n",
"STAT hash_is_expanding 0\r\n",
"STAT expired_unfetched 0\r\n",
"STAT evicted_unfetched 0\r\n",
"STAT bytes 0\r\n",
"STAT curr_items 0\r\n",
"STAT total_items 0\r\n",
"STAT evictions 0\r\n",
"STAT reclaimed 0\r\n",
"END\r\n"
]
end
let(:mock_socket) { instance_double(TCPSocket) }
before do
allow(TCPSocket).to receive(:new).with(host, port).and_return(mock_socket)
allow(mock_socket).to receive(:close)
allow(mock_socket).to receive(:puts).with(cmd)
allow(mock_socket).to receive(:readline).and_return(*socket_response_lines)
end
context 'when the socket returns a valid response' do
before do
allow(mock_socket).to receive(:readline).and_return(*socket_response_lines)
end
it 'sends the command and parses out the engine version' do
response = command.response
expect(response.engine_version).to eq(engine_version)
expect(mock_socket).to have_received(:close)
expect(mock_socket).to have_received(:puts).with(cmd)
end
end
end
| ruby | MIT | 100fe160eca65a4fa9f81ce607b4190b1f73687c | 2026-01-04T17:51:34.942242Z | false |
ktheory/dalli-elasticache | https://github.com/ktheory/dalli-elasticache/blob/100fe160eca65a4fa9f81ce607b4190b1f73687c/spec/config_response_spec.rb | spec/config_response_spec.rb | # frozen_string_literal: true
require_relative 'spec_helper'
describe 'Dalli::Elasticache::AutoDiscovery::ConfigResponse' do
let :response do
text = "CONFIG cluster 0 141\r\n12\nmycluster.0001.cache.amazonaws.com|10.112.21.1|11211 " \
'mycluster.0002.cache.amazonaws.com|10.112.21.2|11211 ' \
"mycluster.0003.cache.amazonaws.com|10.112.21.3|11211\n\r\n"
Dalli::Elasticache::AutoDiscovery::ConfigResponse.new(text)
end
describe '#version' do
it 'parses version' do
expect(response.version).to eq 12
end
end
describe '#nodes' do
it 'parses hosts' do
expect(response.nodes.map(&:host)).to eq [
'mycluster.0001.cache.amazonaws.com',
'mycluster.0002.cache.amazonaws.com',
'mycluster.0003.cache.amazonaws.com'
]
end
it 'parses ip addresses' do
expect(response.nodes.map(&:ip)).to eq ['10.112.21.1', '10.112.21.2', '10.112.21.3']
end
it 'parses ports' do
expect(response.nodes.map(&:port)).to eq [11_211, 11_211, 11_211]
end
end
end
| ruby | MIT | 100fe160eca65a4fa9f81ce607b4190b1f73687c | 2026-01-04T17:51:34.942242Z | false |
ktheory/dalli-elasticache | https://github.com/ktheory/dalli-elasticache/blob/100fe160eca65a4fa9f81ce607b4190b1f73687c/spec/elasticache_spec.rb | spec/elasticache_spec.rb | # frozen_string_literal: true
require_relative 'spec_helper'
describe 'Dalli::ElastiCache::Endpoint' do
let(:dalli_options) do
{
expires_in: 24 * 60 * 60,
namespace: 'my_app',
compress: true
}
end
let(:host) { 'my-cluster.cfg.use1.cache.amazonaws.com' }
let(:port) { 11_211 }
let(:config_endpoint) { "#{host}:#{port}" }
let(:cache) do
Dalli::ElastiCache.new(config_endpoint, dalli_options)
end
let(:config_text) do
"CONFIG cluster 0 141\r\n12\nmycluster.0001.cache.amazonaws.com|10.112.21.1|11211 " \
'mycluster.0002.cache.amazonaws.com|10.112.21.2|11211 ' \
"mycluster.0003.cache.amazonaws.com|10.112.21.3|11211\n\r\n"
end
let(:response) { Dalli::Elasticache::AutoDiscovery::ConfigResponse.new(config_text) }
describe '.new' do
it 'builds endpoint' do
expect(cache.endpoint.host).to eq 'my-cluster.cfg.use1.cache.amazonaws.com'
expect(cache.endpoint.port).to eq 11_211
end
it 'stores Dalli options' do
expect(cache.options[:expires_in]).to eq 24 * 60 * 60
expect(cache.options[:namespace]).to eq 'my_app'
expect(cache.options[:compress]).to be true
end
end
describe '#client' do
let(:client) { cache.client }
let(:stub_endpoint) { Dalli::Elasticache::AutoDiscovery::Endpoint.new(config_endpoint) }
let(:mock_dalli) { instance_double(Dalli::Client) }
before do
allow(Dalli::Elasticache::AutoDiscovery::Endpoint).to receive(:new)
.with(config_endpoint).and_return(stub_endpoint)
allow(stub_endpoint).to receive(:config).and_return(response)
allow(Dalli::Client).to receive(:new)
.with(['mycluster.0001.cache.amazonaws.com:11211',
'mycluster.0002.cache.amazonaws.com:11211',
'mycluster.0003.cache.amazonaws.com:11211'],
dalli_options).and_return(mock_dalli)
end
it 'builds with node list and dalli options' do
expect(client).to eq(mock_dalli)
expect(stub_endpoint).to have_received(:config)
expect(Dalli::Client).to have_received(:new)
.with(['mycluster.0001.cache.amazonaws.com:11211',
'mycluster.0002.cache.amazonaws.com:11211',
'mycluster.0003.cache.amazonaws.com:11211'],
dalli_options)
end
end
describe '#servers' do
let(:stub_endpoint) { Dalli::Elasticache::AutoDiscovery::Endpoint.new(config_endpoint) }
before do
allow(Dalli::Elasticache::AutoDiscovery::Endpoint).to receive(:new)
.with(config_endpoint).and_return(stub_endpoint)
allow(stub_endpoint).to receive(:config).and_return(response)
end
it 'lists addresses and ports' do
expect(cache.servers).to eq ['mycluster.0001.cache.amazonaws.com:11211',
'mycluster.0002.cache.amazonaws.com:11211',
'mycluster.0003.cache.amazonaws.com:11211']
expect(stub_endpoint).to have_received(:config)
expect(Dalli::Elasticache::AutoDiscovery::Endpoint).to have_received(:new).with(config_endpoint)
end
end
describe '#version' do
let(:mock_config) { instance_double(Dalli::Elasticache::AutoDiscovery::ConfigResponse) }
let(:version) { rand(1..20) }
before do
allow(cache.endpoint).to receive(:config).and_return(mock_config)
allow(mock_config).to receive(:version).and_return(version)
end
it 'delegates the call to the config on the endpoint' do
expect(cache.version).to eq(version)
expect(cache.endpoint).to have_received(:config)
expect(mock_config).to have_received(:version)
end
end
describe '#engine_version' do
let(:engine_version) { [Gem::Version.new('1.6.13'), Gem::Version.new('1.4.14')].sample }
before do
allow(cache.endpoint).to receive(:engine_version).and_return(engine_version)
end
it 'delegates the call to the endpoint' do
expect(cache.engine_version).to eq(engine_version)
expect(cache.endpoint).to have_received(:engine_version)
end
end
describe '#refresh' do
it 'clears endpoint configuration' do
stale_endpoint = cache.endpoint
expect(cache.refresh.endpoint).not_to eq stale_endpoint
end
it 'builds endpoint with same configuration' do
stale_endpoint = cache.endpoint
cache.refresh
expect(cache.endpoint.host).to eq(stale_endpoint.host)
expect(cache.endpoint.port).to eq(stale_endpoint.port)
end
end
end
| ruby | MIT | 100fe160eca65a4fa9f81ce607b4190b1f73687c | 2026-01-04T17:51:34.942242Z | false |
ktheory/dalli-elasticache | https://github.com/ktheory/dalli-elasticache/blob/100fe160eca65a4fa9f81ce607b4190b1f73687c/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
require 'bundler/setup'
require 'dalli/elasticache'
require 'securerandom'
require 'faker'
RSpec.configure
| ruby | MIT | 100fe160eca65a4fa9f81ce607b4190b1f73687c | 2026-01-04T17:51:34.942242Z | false |
ktheory/dalli-elasticache | https://github.com/ktheory/dalli-elasticache/blob/100fe160eca65a4fa9f81ce607b4190b1f73687c/spec/node_spec.rb | spec/node_spec.rb | # frozen_string_literal: true
require_relative 'spec_helper'
describe 'Dalli::Elasticache::AutoDiscovery::Node' do
context 'when comparing with equals' do
let(:host1) { Faker::Internet.domain_name(subdomain: true) }
let(:ip1) { Faker::Internet.public_ip_v4_address }
let(:port1) { rand(1024..16_023) }
let(:host2) { Faker::Internet.domain_name(subdomain: true) }
let(:ip2) { Faker::Internet.public_ip_v4_address }
let(:port2) { rand(1024..16_023) }
let(:node1a) { Dalli::Elasticache::AutoDiscovery::Node.new(host1, ip1, port1) }
let(:node1b) { Dalli::Elasticache::AutoDiscovery::Node.new(host1, ip1, port1) }
let(:node_with_different_host) { Dalli::Elasticache::AutoDiscovery::Node.new(host2, ip1, port1) }
let(:node_with_different_ip) { Dalli::Elasticache::AutoDiscovery::Node.new(host1, ip2, port1) }
let(:node_with_different_port) { Dalli::Elasticache::AutoDiscovery::Node.new(host1, ip1, port2) }
it 'is equal to a value with the same values' do
expect(node1a).to eq(node1b)
expect(node1a.eql?(node1b)).to be(true)
end
it 'is not equal to a value with any differing values' do
expect(node1a).not_to eq(node_with_different_host)
expect(node1a.eql?(node_with_different_host)).to be(false)
expect(node1a).not_to eq(node_with_different_ip)
expect(node1a.eql?(node_with_different_ip)).to be(false)
expect(node1a).not_to eq(node_with_different_port)
expect(node1a.eql?(node_with_different_port)).to be(false)
end
end
context 'when used as a hash key' do
let(:host1) { Faker::Internet.domain_name(subdomain: true) }
let(:ip1) { Faker::Internet.public_ip_v4_address }
let(:port1) { rand(1024..16_023) }
let(:host2) { Faker::Internet.domain_name(subdomain: true) }
let(:ip2) { Faker::Internet.public_ip_v4_address }
let(:port2) { rand(1024..16_023) }
let(:node1a) { Dalli::Elasticache::AutoDiscovery::Node.new(host1, ip1, port1) }
let(:node1b) { Dalli::Elasticache::AutoDiscovery::Node.new(host1, ip1, port1) }
let(:node_with_different_host) { Dalli::Elasticache::AutoDiscovery::Node.new(host2, ip1, port1) }
let(:node_with_different_ip) { Dalli::Elasticache::AutoDiscovery::Node.new(host1, ip2, port1) }
let(:node_with_different_port) { Dalli::Elasticache::AutoDiscovery::Node.new(host1, ip1, port2) }
let(:test_val) { 'abcd' }
let(:test_hash) do
{ node1a => test_val }
end
it 'computes the same hash key' do
expect(node1a.hash).to eq(node1b.hash)
end
it 'matches when an equivalent object is used' do
expect(test_hash.key?(node1b)).to be(true)
end
it 'does not match when an non-equivalent object is used' do
expect(test_hash.key?(node_with_different_host)).to be(false)
expect(test_hash.key?(node_with_different_ip)).to be(false)
expect(test_hash.key?(node_with_different_port)).to be(false)
end
end
describe '#to_s' do
let(:host) { Faker::Internet.domain_name(subdomain: true) }
let(:ip) { Faker::Internet.public_ip_v4_address }
let(:port) { rand(1024..16_023) }
let(:node) { Dalli::Elasticache::AutoDiscovery::Node.new(host, ip, port) }
it 'returns the expected string value' do
expect(node.to_s).to eq("#{host}:#{port}")
end
end
end
| ruby | MIT | 100fe160eca65a4fa9f81ce607b4190b1f73687c | 2026-01-04T17:51:34.942242Z | false |
ktheory/dalli-elasticache | https://github.com/ktheory/dalli-elasticache/blob/100fe160eca65a4fa9f81ce607b4190b1f73687c/lib/dalli-elasticache.rb | lib/dalli-elasticache.rb | # frozen_string_literal: true
# Support default bundler require path
require_relative 'dalli/elasticache'
| ruby | MIT | 100fe160eca65a4fa9f81ce607b4190b1f73687c | 2026-01-04T17:51:34.942242Z | false |
ktheory/dalli-elasticache | https://github.com/ktheory/dalli-elasticache/blob/100fe160eca65a4fa9f81ce607b4190b1f73687c/lib/dalli/elasticache.rb | lib/dalli/elasticache.rb | # frozen_string_literal: true
require 'dalli'
require 'socket'
require_relative 'elasticache/version'
require_relative 'elasticache/auto_discovery/endpoint'
require_relative 'elasticache/auto_discovery/base_command'
require_relative 'elasticache/auto_discovery/node'
require_relative 'elasticache/auto_discovery/config_response'
require_relative 'elasticache/auto_discovery/config_command'
require_relative 'elasticache/auto_discovery/stats_response'
require_relative 'elasticache/auto_discovery/stats_command'
module Dalli
##
# Dalli::Elasticache provides an interface for providing a configuration
# endpoint for a memcached cluster on ElasticCache and retrieving the
# list of addresses (hostname and port) for the individual nodes of that cluster.
#
# This allows the caller to pass that server list to Dalli, which then
# distributes cached items consistently over the nodes.
##
class ElastiCache
attr_reader :endpoint, :options
##
# Creates a new Dalli::ElasticCache instance.
#
# config_endpoint - a String containing the host and (optionally) port of the
# configuration endpoint for the cluster. If not specified the port will
# default to 11211. The host must be either a DNS name or an IPv4 address. IPv6
# addresses are not handled at this time.
# dalli_options - a set of options passed to the Dalli::Client that is returned
# by the client method. Otherwise unused.
##
def initialize(config_endpoint, dalli_options = {})
@endpoint = Dalli::Elasticache::AutoDiscovery::Endpoint.new(config_endpoint)
@options = dalli_options
end
# Dalli::Client configured to connect to the cluster's nodes
def client
Dalli::Client.new(servers, options)
end
# The number of times the cluster configuration has been changed
#
# Returns an integer
def version
endpoint.config.version
end
# The cache engine version of the cluster
#
# Returns a string
def engine_version
endpoint.engine_version
end
# List of cluster server nodes with ip addresses and ports
# Always use host name instead of private elasticache IPs as internal IPs can change after a node is rebooted
def servers
endpoint.config.nodes.map(&:to_s)
end
# Clear all cached data from the cluster endpoint
def refresh
config_endpoint = "#{endpoint.host}:#{endpoint.port}"
@endpoint = Dalli::Elasticache::AutoDiscovery::Endpoint.new(config_endpoint)
self
end
end
end
| ruby | MIT | 100fe160eca65a4fa9f81ce607b4190b1f73687c | 2026-01-04T17:51:34.942242Z | false |
ktheory/dalli-elasticache | https://github.com/ktheory/dalli-elasticache/blob/100fe160eca65a4fa9f81ce607b4190b1f73687c/lib/dalli/elasticache/version.rb | lib/dalli/elasticache/version.rb | # frozen_string_literal: true
module Dalli
class ElastiCache
VERSION = '1.0.1'
end
end
| ruby | MIT | 100fe160eca65a4fa9f81ce607b4190b1f73687c | 2026-01-04T17:51:34.942242Z | false |
ktheory/dalli-elasticache | https://github.com/ktheory/dalli-elasticache/blob/100fe160eca65a4fa9f81ce607b4190b1f73687c/lib/dalli/elasticache/auto_discovery/base_command.rb | lib/dalli/elasticache/auto_discovery/base_command.rb | # frozen_string_literal: true
module Dalli
module Elasticache
module AutoDiscovery
##
# Base command class for configuration endpoint
# command. Contains the network logic.
##
class BaseCommand
attr_reader :host, :port
def initialize(host, port)
@host = host
@port = port
end
# Send an ASCII command to the endpoint
#
# Returns the raw response as a String
def send_command
socket = TCPSocket.new(@host, @port)
begin
socket.puts command
response_from_socket(socket)
ensure
socket.close
end
end
def response_from_socket(socket)
data = +''
until (line = socket.readline).include?('END')
data << line
end
data
end
end
end
end
end
| ruby | MIT | 100fe160eca65a4fa9f81ce607b4190b1f73687c | 2026-01-04T17:51:34.942242Z | false |
ktheory/dalli-elasticache | https://github.com/ktheory/dalli-elasticache/blob/100fe160eca65a4fa9f81ce607b4190b1f73687c/lib/dalli/elasticache/auto_discovery/node.rb | lib/dalli/elasticache/auto_discovery/node.rb | # frozen_string_literal: true
module Dalli
module Elasticache
module AutoDiscovery
##
# Represents a single memcached node in the
# cluster.
##
class Node
attr_reader :host, :ip, :port
def initialize(host, ip, port)
@host = host
@ip = ip
@port = port
end
def ==(other)
host == other.host &&
ip == other.ip &&
port == other.port
end
def eql?(other)
self == other
end
def hash
[host, ip, port].hash
end
def to_s
"#{@host}:#{@port}"
end
end
end
end
end
| ruby | MIT | 100fe160eca65a4fa9f81ce607b4190b1f73687c | 2026-01-04T17:51:34.942242Z | false |
ktheory/dalli-elasticache | https://github.com/ktheory/dalli-elasticache/blob/100fe160eca65a4fa9f81ce607b4190b1f73687c/lib/dalli/elasticache/auto_discovery/config_response.rb | lib/dalli/elasticache/auto_discovery/config_response.rb | # frozen_string_literal: true
module Dalli
module Elasticache
module AutoDiscovery
# This class wraps the raw ASCII response from an Auto Discovery endpoint
# and provides methods for extracting data from that response.
#
# http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/AutoDiscovery.AddingToYourClientLibrary.html
class ConfigResponse
# The raw response text
attr_reader :text
# Matches the version line of the response
VERSION_REGEX = /^(\d+)\r?\n/.freeze
# Matches strings like "my-cluster.001.cache.aws.com|10.154.182.29|11211"
NODE_REGEX = /(([-.a-zA-Z0-9]+)\|(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b)\|(\d+))/.freeze
NODE_LIST_REGEX = /^(#{NODE_REGEX}\s*)+$/.freeze
def initialize(response_text)
@text = response_text.to_s
end
# The number of times the configuration has been changed
#
# Returns an integer
def version
m = VERSION_REGEX.match(@text)
return -1 unless m
m[1].to_i
end
# Node hosts, ip addresses, and ports
#
# Returns an Array of Hashes with values for :host, :ip and :port
def nodes
NODE_LIST_REGEX.match(@text).to_s.scan(NODE_REGEX).map do |match|
Node.new(match[1], match[2], match[3].to_i)
end
end
end
end
end
end
| ruby | MIT | 100fe160eca65a4fa9f81ce607b4190b1f73687c | 2026-01-04T17:51:34.942242Z | false |
ktheory/dalli-elasticache | https://github.com/ktheory/dalli-elasticache/blob/100fe160eca65a4fa9f81ce607b4190b1f73687c/lib/dalli/elasticache/auto_discovery/stats_command.rb | lib/dalli/elasticache/auto_discovery/stats_command.rb | # frozen_string_literal: true
module Dalli
module Elasticache
module AutoDiscovery
##
# Encapsulates execution of the 'stats' command, which is used to
# extract the engine_version
##
class StatsCommand < BaseCommand
STATS_COMMAND = "stats\r\n"
def response
StatsResponse.new(send_command)
end
def command
STATS_COMMAND
end
end
end
end
end
| ruby | MIT | 100fe160eca65a4fa9f81ce607b4190b1f73687c | 2026-01-04T17:51:34.942242Z | false |
ktheory/dalli-elasticache | https://github.com/ktheory/dalli-elasticache/blob/100fe160eca65a4fa9f81ce607b4190b1f73687c/lib/dalli/elasticache/auto_discovery/config_command.rb | lib/dalli/elasticache/auto_discovery/config_command.rb | # frozen_string_literal: true
module Dalli
module Elasticache
module AutoDiscovery
##
# Encapsulates execution of the 'config' command, which is used to
# extract the list of nodes and determine if that list of nodes has changed.
##
class ConfigCommand < BaseCommand
attr_reader :engine_version
CONFIG_COMMAND = "config get cluster\r\n"
# Legacy command for version < 1.4.14
LEGACY_CONFIG_COMMAND = "get AmazonElastiCache:cluster\r\n"
def initialize(host, port, engine_version)
super(host, port)
@engine_version = engine_version
end
def response
ConfigResponse.new(send_command)
end
def command
return LEGACY_CONFIG_COMMAND if legacy_config?
CONFIG_COMMAND
end
def legacy_config?
return false unless engine_version
return false if engine_version.casecmp('unknown').zero?
Gem::Version.new(engine_version) < Gem::Version.new('1.4.14')
rescue ArgumentError
# Just assume false if we can't parse the engine_version
false
end
end
end
end
end
| ruby | MIT | 100fe160eca65a4fa9f81ce607b4190b1f73687c | 2026-01-04T17:51:34.942242Z | false |
ktheory/dalli-elasticache | https://github.com/ktheory/dalli-elasticache/blob/100fe160eca65a4fa9f81ce607b4190b1f73687c/lib/dalli/elasticache/auto_discovery/endpoint.rb | lib/dalli/elasticache/auto_discovery/endpoint.rb | # frozen_string_literal: true
module Dalli
module Elasticache
module AutoDiscovery
##
# This is a representation of the configuration endpoint for
# a memcached cluster. It encapsulates information returned from
# that endpoint.
##
class Endpoint
# Endpoint configuration
attr_reader :host, :port
# Matches Strings like "my-host.cache.aws.com:11211"
ENDPOINT_REGEX = /^([-_.a-zA-Z0-9]+)(?::(\d+))?$/.freeze
def initialize(addr)
@host, @port = parse_endpoint_address(addr)
end
DEFAULT_PORT = 11_211
def parse_endpoint_address(addr)
m = ENDPOINT_REGEX.match(addr)
raise ArgumentError, "Unable to parse configuration endpoint address - #{addr}" unless m
[m[1], (m[2] || DEFAULT_PORT).to_i]
end
# A cached ElastiCache::StatsResponse
def stats
@stats ||= StatsCommand.new(@host, @port).response
end
# A cached ElastiCache::ConfigResponse
def config
@config ||= ConfigCommand.new(@host, @port, engine_version).response
end
# The memcached engine version
def engine_version
stats.engine_version
end
end
end
end
end
| ruby | MIT | 100fe160eca65a4fa9f81ce607b4190b1f73687c | 2026-01-04T17:51:34.942242Z | false |
ktheory/dalli-elasticache | https://github.com/ktheory/dalli-elasticache/blob/100fe160eca65a4fa9f81ce607b4190b1f73687c/lib/dalli/elasticache/auto_discovery/stats_response.rb | lib/dalli/elasticache/auto_discovery/stats_response.rb | # frozen_string_literal: true
module Dalli
module Elasticache
module AutoDiscovery
# This class wraps the raw ASCII response from a stats call to an
# Auto Discovery endpoint and provides methods for extracting data
# from that response.
#
# http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/AutoDiscovery.AddingToYourClientLibrary.html
class StatsResponse
# The raw response text
attr_reader :text
# Matches the version line of the response
VERSION_REGEX = /^STAT version ([0-9.]+|unknown)\s*/i.freeze
def initialize(response_text)
@text = response_text.to_s
end
# Extract the engine version stat
#
# Returns a string
def engine_version
m = VERSION_REGEX.match(@text)
return '' unless m && m[1]
m[1]
end
end
end
end
end
| ruby | MIT | 100fe160eca65a4fa9f81ce607b4190b1f73687c | 2026-01-04T17:51:34.942242Z | false |
tmiyamon/acts-as-taggable-array-on | https://github.com/tmiyamon/acts-as-taggable-array-on/blob/16078cd5b8d2db60f64bbfc443d773879fe10e4f/spec_helper.rb | spec_helper.rb | require "rubygems"
RSpec::Matchers.define :my_matcher do |expected|
match do |actual|
true
end
end
| ruby | MIT | 16078cd5b8d2db60f64bbfc443d773879fe10e4f | 2026-01-04T17:51:37.298787Z | false |
tmiyamon/acts-as-taggable-array-on | https://github.com/tmiyamon/acts-as-taggable-array-on/blob/16078cd5b8d2db60f64bbfc443d773879fe10e4f/spec/spec_helper.rb | spec/spec_helper.rb | $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib"))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require "rspec"
require "active_record/railtie"
ActiveRecord::Base.logger = Logger.new(STDERR)
ActiveRecord::Base.logger.level = 3
require "acts-as-taggable-array-on"
# Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}
ActiveRecord::Migration.verbose = false
class User < ActiveRecord::Base; end
class Admin < User; end
RSpec.configure do |config|
config.before(:all) do
ActiveRecord::Base.establish_connection(
adapter: "postgresql",
encoding: "unicode",
database: "acts-as-taggable-array-on_test",
username: "acts-as-taggable-array-on"
)
create_database
end
config.after(:all) do
drop_database
end
config.after(:each) do
User.delete_all
end
end
def create_database
ActiveRecord::Schema.define(version: 1) do
enable_extension("citext") unless extensions.include?("citext")
enable_extension("uuid-ossp") unless extensions.include?("uuid-ossp")
create_table :users do |t|
t.string :name
t.string :type
t.string :colors, array: true, default: []
t.text :sizes, array: true, default: []
t.integer :codes, array: true, default: []
t.citext :roles, array: true, default: []
t.uuid :references, array: true, default: []
t.timestamps null: true
end
end
end
def drop_database
ActiveRecord::Base.connection.tables.each do |table|
ActiveRecord::Base.connection.drop_table(table)
end
end
| ruby | MIT | 16078cd5b8d2db60f64bbfc443d773879fe10e4f | 2026-01-04T17:51:37.298787Z | false |
tmiyamon/acts-as-taggable-array-on | https://github.com/tmiyamon/acts-as-taggable-array-on/blob/16078cd5b8d2db60f64bbfc443d773879fe10e4f/spec/acts_as_tag_pgarray/taggable_spec.rb | spec/acts_as_tag_pgarray/taggable_spec.rb | require "spec_helper"
describe ActsAsTaggableArrayOn::Taggable do
before do
@user1 = User.create name: "Tom", colors: ["red", "blue"], sizes: ["medium", "large"], codes: [456, 789], roles: ["user"], references: ["308f35c6-f819-4faa-9bba-2457de1dde25"]
@user2 = User.create name: "Ken", colors: ["black", "white", "red"], sizes: ["small", "large"], codes: [123, 789], roles: ["User"], references: ["e32434a0-39c2-44cc-9c1e-f4c7eebaafb3"]
@user3 = User.create name: "Joe", colors: ["black", "blue"], sizes: ["small", "medium", "large"], codes: [123, 456, 789], roles: ["login"], references: ["41d9033b-80e1-4784-90f6-0c9eb7537cac"]
@admin1 = Admin.create name: "Dick", colors: ["purple", "orange"], sizes: ["medium", "large"], codes: [123, 456, 789], roles: ["USER", "Admin"], references: ["308f35c6-f819-4faa-9bba-2457de1dde25", "e32434a0-39c2-44cc-9c1e-f4c7eebaafb3"]
@admin2 = Admin.create name: "Harry", colors: ["white", "blue"], sizes: ["small", "large"], codes: [456, 123], roles: ["Admin"], references: ["41d9033b-80e1-4784-90f6-0c9eb7537cac"]
User.acts_as_taggable_array_on :colors
User.acts_as_taggable_array_on :sizes
User.acts_as_taggable_array_on :roles
User.acts_as_taggable_array_on :references
User.taggable_array :codes
end
context "without database table" do
it "doesn't fail on class method call" do
class Dummy < ActiveRecord::Base; end
Dummy.acts_as_taggable_array_on :tags
end
end
describe "#acts_as_taggable_array_on" do
it "defines named scope to match any tags" do
expect(User).to respond_to(:with_any_colors)
end
it "defines named scope to match all tags" do
expect(User).to respond_to(:with_all_colors)
end
it "defines named scope not to match any tags" do
expect(User).to respond_to(:without_any_colors)
end
it "defines named scope not to match all tags" do
expect(User).to respond_to(:without_all_colors)
end
end
describe "#taggable_array_on" do
it "defines named scope to match any tags" do
expect(User).to respond_to(:with_any_codes)
end
it "defines named scope to match all tags" do
expect(User).to respond_to(:with_all_codes)
end
it "defines named scope not to match any tags" do
expect(User).to respond_to(:without_any_codes)
end
it "defines named scope not to match all tags" do
expect(User).to respond_to(:without_all_codes)
end
end
it "should define table name un-ambiguously" do
sql = User.with_any_sizes(["small"]).to_sql
expect(sql).to eql("SELECT \"users\".* FROM \"users\" WHERE (users.sizes && ARRAY['small']::text[])")
sql = User.with_all_sizes(["small"]).to_sql
expect(sql).to eql("SELECT \"users\".* FROM \"users\" WHERE (users.sizes @> ARRAY['small']::text[])")
sql = User.without_any_sizes(["small"]).to_sql
expect(sql).to eql("SELECT \"users\".* FROM \"users\" WHERE NOT (users.sizes && ARRAY['small']::text[])")
sql = User.without_all_sizes(["small"]).to_sql
expect(sql).to eql("SELECT \"users\".* FROM \"users\" WHERE NOT (users.sizes @> ARRAY['small']::text[])")
end
it "should work with ::text typed array" do
expect(User.with_any_sizes(["small"])).to match_array([@user2, @user3, @admin2])
expect(User.with_all_sizes(["small", "large"])).to match_array([@user2, @user3, @admin2])
expect(User.without_any_sizes("medium")).to match_array([@user2, @admin2])
expect(User.without_all_sizes("medium")).to match_array([@user2, @admin2])
end
it "should work with ::citext typed array" do
expect(User.with_any_roles(["admin"])).to match_array([@admin1, @admin2])
expect(User.with_all_roles(["User", "Admin"])).to match_array([@admin1])
expect(User.without_any_roles("USER")).to match_array([@user3, @admin2])
expect(User.without_all_roles("UseR")).to match_array([@user3, @admin2])
end
it "should work with ::uuid typed array" do
expect(User.with_any_references(["308f35c6-f819-4faa-9bba-2457de1dde25"])).to match_array([@user1, @admin1])
expect(User.with_all_references(["308f35c6-f819-4faa-9bba-2457de1dde25", "e32434a0-39c2-44cc-9c1e-f4c7eebaafb3"])).to match_array([@admin1])
expect(User.without_any_references("308f35c6-f819-4faa-9bba-2457de1dde25")).to match_array([@user2, @user3, @admin2])
expect(User.without_all_references(["308f35c6-f819-4faa-9bba-2457de1dde25", "e32434a0-39c2-44cc-9c1e-f4c7eebaafb3"])).to match_array([@user1, @user2, @user3, @admin2])
end
it "should work with ::integer typed array" do
expect(User.with_any_codes([123])).to match_array([@user2, @user3, @admin1, @admin2])
expect(User.with_all_codes([123, 789])).to match_array([@user2, @user3, @admin1])
expect(User.without_any_codes(456)).to match_array([@user2])
expect(User.without_all_codes(456)).to match_array([@user2])
end
describe "#with_any_tags" do
it "returns users having any tags of args" do
expect(User.with_any_colors(["red", "blue"])).to match_array([@user1, @user2, @user3, @admin2])
expect(User.with_any_colors("red, blue")).to match_array([@user1, @user2, @user3, @admin2])
end
end
describe "#with_all_tags" do
it "returns users having all tags of args" do
expect(User.with_all_colors(["red", "blue"])).to match_array([@user1])
expect(User.with_all_colors("red, blue")).to match_array([@user1])
end
end
describe "#without_any_tags" do
it "returns users not having any tags of args" do
expect(User.without_any_colors(["red", "blue"])).to match_array([@admin1])
expect(User.without_any_colors("red, blue")).to match_array([@admin1])
end
end
describe "#without_all_tags" do
it "returns users not having all tags of args" do
expect(User.without_all_colors(["red", "blue"])).to match_array([@user2, @user3, @admin1, @admin2])
expect(User.without_all_colors("red, blue")).to match_array([@user2, @user3, @admin1, @admin2])
end
end
describe "#all_colors" do
it "returns all of tag_name" do
expect(User.all_colors).to match_array([@user1, @user2, @user3, @admin1, @admin2].map(&:colors).flatten.uniq)
expect(Admin.all_colors).to match_array([@admin1, @admin2].map(&:colors).flatten.uniq)
end
it "returns filtered tags for tag_name with block" do
expect(User.all_colors { where(name: ["Ken", "Joe"]) }).to match_array([@user2, @user3].map(&:colors).flatten.uniq)
expect(Admin.all_colors { where(name: ["Dick", "Harry"]) }).to match_array([@admin1, @admin2].map(&:colors).flatten.uniq)
end
it "returns filtered tags for tag_name with prepended scope" do
expect(User.where("tag like ?", "bl%").all_colors).to match_array([@user1, @user2, @user3].map(&:colors).flatten.uniq.select { |name| name.start_with? "bl" })
expect(Admin.where("tag like ?", "bl%").all_colors).to match_array([@admin2].map(&:colors).flatten.uniq.select { |name| name.start_with? "bl" })
end
it "returns filtered tags for tag_name with prepended scope and bock" do
expect(User.where("tag like ?", "bl%").all_colors { where(name: ["Ken", "Joe"]) }).to match_array([@user2, @user3].map(&:colors).flatten.uniq.select { |name| name.start_with? "bl" })
end
end
describe "#colors_cloud" do
it "returns tag cloud for tag_name" do
expect(User.colors_cloud).to match_array(
[@user1, @user2, @user3, @admin1, @admin2].map(&:colors).flatten.group_by(&:to_s).map { |k, v| [k, v.count] }
)
end
it "returns filtered tag cloud for tag_name with block" do
expect(User.colors_cloud { where(name: ["Ken", "Joe"]) }).to match_array(
[@user2, @user3].map(&:colors).flatten.group_by(&:to_s).map { |k, v| [k, v.count] }
)
end
it "returns filtered tag cloud for tag_name with prepended scope" do
expect(User.where("tag like ?", "bl%").colors_cloud).to match_array(
[@user1, @user2, @user3, @admin2].map(&:colors).flatten.group_by(&:to_s).map { |k, v| [k, v.count] }.select { |name, count| name.start_with? "bl" }
)
end
it "returns filtered tag cloud for tag_name with prepended scope and block" do
expect(User.where("tag like ?", "bl%").colors_cloud { where(name: ["Ken", "Joe"]) }).to match_array(
[@user2, @user3].map(&:colors).flatten.group_by(&:to_s).map { |k, v| [k, v.count] }.select { |name, count| name.start_with? "bl" }
)
end
end
describe "with complex scope" do
it "works properly" do
expect(User.without_any_colors("white").with_any_colors("blue").order(:created_at).limit(10)).to eq [@user1, @user3]
end
end
end
| ruby | MIT | 16078cd5b8d2db60f64bbfc443d773879fe10e4f | 2026-01-04T17:51:37.298787Z | false |
tmiyamon/acts-as-taggable-array-on | https://github.com/tmiyamon/acts-as-taggable-array-on/blob/16078cd5b8d2db60f64bbfc443d773879fe10e4f/spec/acts_as_tag_pgarray/parser_spec.rb | spec/acts_as_tag_pgarray/parser_spec.rb | require "spec_helper"
describe ActsAsTaggableArrayOn::Parser do
let(:parser) { ActsAsTaggableArrayOn.parser }
describe "#parse" do
it "return unprocessed tags if array" do
tags = %w[red green]
expect(parser.parse(tags)).to eq tags
end
it "return parsed tags if comma separated string" do
tags = "red,green"
expect(parser.parse(tags)).to eq %w[red green]
end
it "return parsed tags if comma separated string including white spaces" do
tags = "red , gre en"
expect(parser.parse(tags)).to eq ["red", "gre en"]
end
end
end
| ruby | MIT | 16078cd5b8d2db60f64bbfc443d773879fe10e4f | 2026-01-04T17:51:37.298787Z | false |
tmiyamon/acts-as-taggable-array-on | https://github.com/tmiyamon/acts-as-taggable-array-on/blob/16078cd5b8d2db60f64bbfc443d773879fe10e4f/lib/acts-as-taggable-array-on.rb | lib/acts-as-taggable-array-on.rb | require "active_record"
require "acts-as-taggable-array-on/version"
require "acts-as-taggable-array-on/taggable"
require "acts-as-taggable-array-on/parser"
ActiveSupport.on_load(:active_record) do
include ActsAsTaggableArrayOn::Taggable
end
| ruby | MIT | 16078cd5b8d2db60f64bbfc443d773879fe10e4f | 2026-01-04T17:51:37.298787Z | false |
tmiyamon/acts-as-taggable-array-on | https://github.com/tmiyamon/acts-as-taggable-array-on/blob/16078cd5b8d2db60f64bbfc443d773879fe10e4f/lib/acts-as-taggable-array-on/version.rb | lib/acts-as-taggable-array-on/version.rb | module ActsAsTagPgarray
VERSION = "0.7.0"
end
| ruby | MIT | 16078cd5b8d2db60f64bbfc443d773879fe10e4f | 2026-01-04T17:51:37.298787Z | false |
tmiyamon/acts-as-taggable-array-on | https://github.com/tmiyamon/acts-as-taggable-array-on/blob/16078cd5b8d2db60f64bbfc443d773879fe10e4f/lib/acts-as-taggable-array-on/parser.rb | lib/acts-as-taggable-array-on/parser.rb | # frozen_string_literal: true
module ActsAsTaggableArrayOn
class Parser
def parse tags
case tags
when String
tags.split(/ *, */)
else
tags
end
end
end
def self.parser
@parser ||= Parser.new
end
end
| ruby | MIT | 16078cd5b8d2db60f64bbfc443d773879fe10e4f | 2026-01-04T17:51:37.298787Z | false |
tmiyamon/acts-as-taggable-array-on | https://github.com/tmiyamon/acts-as-taggable-array-on/blob/16078cd5b8d2db60f64bbfc443d773879fe10e4f/lib/acts-as-taggable-array-on/taggable.rb | lib/acts-as-taggable-array-on/taggable.rb | # frozen_string_literal: true
module ActsAsTaggableArrayOn
module Taggable
def self.included(base)
base.extend(ClassMethod)
end
TYPE_MATCHER = {string: "varchar", text: "text", integer: "integer", citext: "citext", uuid: "uuid"}
module ClassMethod
def acts_as_taggable_array_on(tag_name, *)
tag_array_type_fetcher = -> { TYPE_MATCHER[columns_hash[tag_name.to_s].type] }
parser = ActsAsTaggableArrayOn.parser
scope :"with_any_#{tag_name}", ->(tags) { where("#{table_name}.#{tag_name} && ARRAY[?]::#{tag_array_type_fetcher.call}[]", parser.parse(tags)) }
scope :"with_all_#{tag_name}", ->(tags) { where("#{table_name}.#{tag_name} @> ARRAY[?]::#{tag_array_type_fetcher.call}[]", parser.parse(tags)) }
scope :"without_any_#{tag_name}", ->(tags) { where.not("#{table_name}.#{tag_name} && ARRAY[?]::#{tag_array_type_fetcher.call}[]", parser.parse(tags)) }
scope :"without_all_#{tag_name}", ->(tags) { where.not("#{table_name}.#{tag_name} @> ARRAY[?]::#{tag_array_type_fetcher.call}[]", parser.parse(tags)) }
self.class.class_eval do
define_method :"all_#{tag_name}" do |options = {}, &block|
subquery_scope = unscoped.select("unnest(#{table_name}.#{tag_name}) as tag").distinct
subquery_scope = subquery_scope.instance_eval(&block) if block
# Remove the STI inheritance type from the outer query since it is in the subquery
unscope(where: :type).from(subquery_scope).pluck(:tag)
end
define_method :"#{tag_name}_cloud" do |options = {}, &block|
subquery_scope = unscoped.select("unnest(#{table_name}.#{tag_name}) as tag")
subquery_scope = subquery_scope.instance_eval(&block) if block
# Remove the STI inheritance type from the outer query since it is in the subquery
unscope(where: :type).from(subquery_scope).group(:tag).order(:tag).count(:tag)
end
end
end
alias_method :taggable_array, :acts_as_taggable_array_on
end
end
end
| ruby | MIT | 16078cd5b8d2db60f64bbfc443d773879fe10e4f | 2026-01-04T17:51:37.298787Z | false |
papertrail/remote_syslog_logger | https://github.com/papertrail/remote_syslog_logger/blob/506bba071f09082106aacd6d3cc3e17423d99dac/test/test_remote_syslog_logger.rb | test/test_remote_syslog_logger.rb | require File.expand_path('../helper', __FILE__)
class TestRemoteSyslogLogger < Test::Unit::TestCase
def setup
@server_port = rand(50000) + 1024
@socket = UDPSocket.new
@socket.bind('127.0.0.1', @server_port)
end
def test_logger
@logger = RemoteSyslogLogger.new('127.0.0.1', @server_port)
@logger.info "This is a test"
message, _ = *@socket.recvfrom(1024)
assert_match "This is a test", message
end
def test_logger_multiline
@logger = RemoteSyslogLogger.new('127.0.0.1', @server_port)
@logger.info "This is a test\nThis is the second line"
message, _ = *@socket.recvfrom(1024)
assert_match "This is a test", message
message, _ = *@socket.recvfrom(1024)
assert_match "This is the second line", message
end
end
| ruby | MIT | 506bba071f09082106aacd6d3cc3e17423d99dac | 2026-01-04T17:51:42.772724Z | false |
papertrail/remote_syslog_logger | https://github.com/papertrail/remote_syslog_logger/blob/506bba071f09082106aacd6d3cc3e17423d99dac/test/helper.rb | test/helper.rb | $:.unshift File.expand_path('../../lib', __FILE__)
unless ENV['BUNDLE_GEMFILE']
require 'rubygems'
require 'bundler'
Bundler.setup
Bundler.require
end
require 'remote_syslog_logger'
require 'test/unit'
| ruby | MIT | 506bba071f09082106aacd6d3cc3e17423d99dac | 2026-01-04T17:51:42.772724Z | false |
papertrail/remote_syslog_logger | https://github.com/papertrail/remote_syslog_logger/blob/506bba071f09082106aacd6d3cc3e17423d99dac/lib/remote_syslog_logger.rb | lib/remote_syslog_logger.rb |
require 'remote_syslog_logger/udp_sender'
require 'logger'
module RemoteSyslogLogger
VERSION = '1.0.4'
def self.new(remote_hostname, remote_port, options = {})
Logger.new(RemoteSyslogLogger::UdpSender.new(remote_hostname, remote_port, options))
end
end
| ruby | MIT | 506bba071f09082106aacd6d3cc3e17423d99dac | 2026-01-04T17:51:42.772724Z | false |
papertrail/remote_syslog_logger | https://github.com/papertrail/remote_syslog_logger/blob/506bba071f09082106aacd6d3cc3e17423d99dac/lib/remote_syslog_logger/udp_sender.rb | lib/remote_syslog_logger/udp_sender.rb | require 'socket'
require 'syslog_protocol'
module RemoteSyslogLogger
class UdpSender
def initialize(remote_hostname, remote_port, options = {})
@remote_hostname = remote_hostname
@remote_port = remote_port
@whinyerrors = options[:whinyerrors]
@max_size = options[:max_size]
@socket = UDPSocket.new
@packet = SyslogProtocol::Packet.new
local_hostname = options[:local_hostname] || (Socket.gethostname rescue `hostname`.chomp)
local_hostname = 'localhost' if local_hostname.nil? || local_hostname.empty?
@packet.hostname = local_hostname
@packet.facility = options[:facility] || 'user'
@packet.severity = options[:severity] || 'notice'
@packet.tag = options[:program] || "#{File.basename($0)}[#{$$}]"
end
def transmit(message)
message.split(/\r?\n/).each do |line|
begin
next if line =~ /^\s*$/
packet = @packet.dup
packet.content = line
payload = @max_size ? packet.assemble(@max_size) : packet.assemble
@socket.send(payload, 0, @remote_hostname, @remote_port)
rescue
$stderr.puts "#{self.class} error: #{$!.class}: #{$!}\nOriginal message: #{line}"
raise if @whinyerrors
end
end
end
# Make this act a little bit like an `IO` object
alias_method :write, :transmit
def close
@socket.close
end
end
end
| ruby | MIT | 506bba071f09082106aacd6d3cc3e17423d99dac | 2026-01-04T17:51:42.772724Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tk.rb | lib/tk.rb | #
# tk.rb - Tk interface module using tcltklib
# by Yukihiro Matsumoto <matz@netlab.jp>
# use Shigehiro's tcltklib
require 'tcltklib'
require 'tkutil'
# autoload
require 'tk/autoload'
# for Mutex
require 'thread'
class TclTkIp
# backup original (without encoding) _eval and _invoke
alias _eval_without_enc _eval
alias __eval__ _eval
alias _invoke_without_enc _invoke
alias __invoke__ _invoke
def _ip_id_
# for RemoteTkIp
''
end
alias __initialize__ initialize
private :__initialize__
def initialize(*args)
__initialize__(*args)
@force_default_encoding ||= TkUtil.untrust([false])
@encoding ||= TkUtil.untrust([nil])
def @encoding.to_s; self.join(nil); end
end
end
# define TkComm module (step 1: basic functions)
module TkComm
include TkUtil
extend TkUtil
WidgetClassNames = TkUtil.untrust({})
TkExtlibAutoloadModule = TkUtil.untrust([])
# None = Object.new ### --> definition is moved to TkUtil module
# def None.to_s
# 'None'
# end
# None.freeze
#Tk_CMDTBL = {}
#Tk_WINDOWS = {}
Tk_IDs = [
TkUtil.untrust("00000"), # [0]-cmdid
TkUtil.untrust("00000") # [1]-winid
]
Tk_IDs.instance_eval{
@mutex = Mutex.new
def mutex; @mutex; end
freeze
}
# for backward compatibility
Tk_CMDTBL = Object.new
def Tk_CMDTBL.method_missing(id, *args)
TkCore::INTERP.tk_cmd_tbl.__send__(id, *args)
end
Tk_CMDTBL.freeze
Tk_WINDOWS = Object.new
def Tk_WINDOWS.method_missing(id, *args)
TkCore::INTERP.tk_windows.__send__(id, *args)
end
Tk_WINDOWS.freeze
self.instance_eval{
@cmdtbl = TkUtil.untrust([])
}
unless const_defined?(:GET_CONFIGINFO_AS_ARRAY)
# GET_CONFIGINFO_AS_ARRAY = false => returns a Hash { opt =>val, ... }
# true => returns an Array [[opt,val], ... ]
# val is a list which includes resource info.
GET_CONFIGINFO_AS_ARRAY = true
end
unless const_defined?(:GET_CONFIGINFOwoRES_AS_ARRAY)
# for configinfo without resource info; list of [opt, value] pair
# false => returns a Hash { opt=>val, ... }
# true => returns an Array [[opt,val], ... ]
GET_CONFIGINFOwoRES_AS_ARRAY = true
end
# *** ATTENTION ***
# 'current_configinfo' method always returns a Hash under all cases of above.
def error_at
frames = caller()
frames.delete_if do |c|
c =~ %r!/tk(|core|thcore|canvas|text|entry|scrollbox)\.rb:\d+!
end
frames
end
private :error_at
def _genobj_for_tkwidget(path)
return TkRoot.new if path == '.'
begin
#tk_class = TkCore::INTERP._invoke('winfo', 'class', path)
tk_class = Tk.ip_invoke_without_enc('winfo', 'class', path)
rescue
return path
end
if ruby_class = WidgetClassNames[tk_class]
ruby_class_name = ruby_class.name
# gen_class_name = ruby_class_name + 'GeneratedOnTk'
gen_class_name = ruby_class_name
classname_def = ''
else # ruby_class == nil
if Tk.const_defined?(tk_class)
Tk.const_get(tk_class) # auto_load
ruby_class = WidgetClassNames[tk_class]
end
unless ruby_class
mods = TkExtlibAutoloadModule.find_all{|m| m.const_defined?(tk_class)}
mods.each{|mod|
begin
mod.const_get(tk_class) # auto_load
break if (ruby_class = WidgetClassNames[tk_class])
rescue LoadError
# ignore load error
end
}
end
unless ruby_class
std_class = 'Tk' << tk_class
if Object.const_defined?(std_class)
Object.const_get(std_class) # auto_load
ruby_class = WidgetClassNames[tk_class]
end
end
unless ruby_class
if Tk.const_defined?('TOPLEVEL_ALIASES') &&
Tk::TOPLEVEL_ALIASES.const_defined?(std_class)
Tk::TOPLEVEL_ALIASES.const_get(std_class) # auto_load
ruby_class = WidgetClassNames[tk_class]
end
end
if ruby_class
# found
ruby_class_name = ruby_class.name
gen_class_name = ruby_class_name
classname_def = ''
else
# unknown
ruby_class_name = 'TkWindow'
gen_class_name = 'TkWidget_' + tk_class
classname_def = "WidgetClassName = '#{tk_class}'.freeze"
end
end
###################################
=begin
if ruby_class = WidgetClassNames[tk_class]
ruby_class_name = ruby_class.name
# gen_class_name = ruby_class_name + 'GeneratedOnTk'
gen_class_name = ruby_class_name
classname_def = ''
else
mod = TkExtlibAutoloadModule.find{|m| m.const_defined?(tk_class)}
if mod
ruby_class_name = mod.name + '::' + tk_class
gen_class_name = ruby_class_name
classname_def = ''
elsif Object.const_defined?('Tk' + tk_class)
ruby_class_name = 'Tk' + tk_class
# gen_class_name = ruby_class_name + 'GeneratedOnTk'
gen_class_name = ruby_class_name
classname_def = ''
else
ruby_class_name = 'TkWindow'
# gen_class_name = ruby_class_name + tk_class + 'GeneratedOnTk'
gen_class_name = 'TkWidget_' + tk_class
classname_def = "WidgetClassName = '#{tk_class}'.freeze"
end
end
=end
=begin
unless Object.const_defined? gen_class_name
Object.class_eval "class #{gen_class_name}<#{ruby_class_name}
#{classname_def}
end"
end
Object.class_eval "#{gen_class_name}.new('widgetname'=>'#{path}',
'without_creating'=>true)"
=end
base = Object
gen_class_name.split('::').each{|klass|
next if klass == ''
if base.const_defined?(klass)
base = base.class_eval klass
else
base = base.class_eval "class #{klass}<#{ruby_class_name}
#{classname_def}
end
#{klass}"
end
}
base.class_eval "#{gen_class_name}.new('widgetname'=>'#{path}',
'without_creating'=>true)"
end
private :_genobj_for_tkwidget
module_function :_genobj_for_tkwidget
def _at(x,y=nil)
if y
"@#{Integer(x)},#{Integer(y)}"
else
"@#{Integer(x)}"
end
end
module_function :_at
def tk_tcl2ruby(val, enc_mode = false, listobj = true)
=begin
if val =~ /^rb_out\S* (c(_\d+_)?\d+)/
#return Tk_CMDTBL[$1]
return TkCore::INTERP.tk_cmd_tbl[$1]
#cmd_obj = TkCore::INTERP.tk_cmd_tbl[$1]
#if cmd_obj.kind_of?(Proc) || cmd_obj.kind_of?(Method)
# cmd_obj
#else
# cmd_obj.cmd
#end
end
=end
if val =~ /rb_out\S*(?:\s+(::\S*|[{](::.*)[}]|["](::.*)["]))? (c(_\d+_)?(\d+))/
return TkCore::INTERP.tk_cmd_tbl[$4]
end
#if val.include? ?\s
# return val.split.collect{|v| tk_tcl2ruby(v)}
#end
case val
when /\A@font\S+\z/
TkFont.get_obj(val)
when /\A-?\d+\z/
val.to_i
when /\A\.\S*\z/
#Tk_WINDOWS[val] ? Tk_WINDOWS[val] : _genobj_for_tkwidget(val)
TkCore::INTERP.tk_windows[val]?
TkCore::INTERP.tk_windows[val] : _genobj_for_tkwidget(val)
when /\Ai(_\d+_)?\d+\z/
TkImage::Tk_IMGTBL.mutex.synchronize{
TkImage::Tk_IMGTBL[val]? TkImage::Tk_IMGTBL[val] : val
}
when /\A-?\d+\.?\d*(e[-+]?\d+)?\z/
val.to_f
when /\\ /
val.gsub(/\\ /, ' ')
when /[^\\] /
if listobj
#tk_split_escstr(val).collect{|elt|
# tk_tcl2ruby(elt, enc_mode, listobj)
#}
val = _toUTF8(val) unless enc_mode
tk_split_escstr(val, false, false).collect{|elt|
tk_tcl2ruby(elt, true, listobj)
}
elsif enc_mode
_fromUTF8(val)
else
val
end
else
if enc_mode
_fromUTF8(val)
else
val
end
end
end
private :tk_tcl2ruby
module_function :tk_tcl2ruby
#private_class_method :tk_tcl2ruby
unless const_defined?(:USE_TCLs_LIST_FUNCTIONS)
USE_TCLs_LIST_FUNCTIONS = true
end
if USE_TCLs_LIST_FUNCTIONS
###########################################################################
# use Tcl function version of split_list
###########################################################################
def tk_split_escstr(str, src_enc=true, dst_enc=true)
str = _toUTF8(str) if src_enc
if dst_enc
TkCore::INTERP._split_tklist(str).map!{|s| _fromUTF8(s)}
else
TkCore::INTERP._split_tklist(str)
end
end
def tk_split_sublist(str, depth=-1, src_enc=true, dst_enc=true)
# return [] if str == ""
# list = TkCore::INTERP._split_tklist(str)
str = _toUTF8(str) if src_enc
if depth == 0
return "" if str == ""
list = [str]
else
return [] if str == ""
list = TkCore::INTERP._split_tklist(str)
end
if list.size == 1
# tk_tcl2ruby(list[0], nil, false)
tk_tcl2ruby(list[0], dst_enc, false)
else
list.collect{|token| tk_split_sublist(token, depth - 1, false, dst_enc)}
end
end
def tk_split_list(str, depth=0, src_enc=true, dst_enc=true)
return [] if str == ""
str = _toUTF8(str) if src_enc
TkCore::INTERP._split_tklist(str).map!{|token|
tk_split_sublist(token, depth - 1, false, dst_enc)
}
end
def tk_split_simplelist(str, src_enc=true, dst_enc=true)
#lst = TkCore::INTERP._split_tklist(str)
#if (lst.size == 1 && lst =~ /^\{.*\}$/)
# TkCore::INTERP._split_tklist(str[1..-2])
#else
# lst
#end
str = _toUTF8(str) if src_enc
if dst_enc
TkCore::INTERP._split_tklist(str).map!{|s| _fromUTF8(s)}
else
TkCore::INTERP._split_tklist(str)
end
end
def array2tk_list(ary, enc=nil)
return "" if ary.size == 0
sys_enc = TkCore::INTERP.encoding
sys_enc = TclTkLib.encoding_system unless sys_enc
dst_enc = (enc == nil)? sys_enc: enc
dst = ary.collect{|e|
if e.kind_of? Array
s = array2tk_list(e, enc)
elsif e.kind_of? Hash
tmp_ary = []
#e.each{|k,v| tmp_ary << k << v }
e.each{|k,v| tmp_ary << "-#{_get_eval_string(k)}" << v }
s = array2tk_list(tmp_ary, enc)
else
s = _get_eval_string(e, enc)
end
if dst_enc != true && dst_enc != false
if (s_enc = s.instance_variable_get(:@encoding))
s_enc = s_enc.to_s
elsif TkCore::WITH_ENCODING
s_enc = s.encoding.name
else
s_enc = sys_enc
end
dst_enc = true if s_enc != dst_enc
end
s
}
if sys_enc && dst_enc
dst.map!{|s| _toUTF8(s)}
ret = TkCore::INTERP._merge_tklist(*dst)
if TkCore::WITH_ENCODING
if dst_enc.kind_of?(String)
ret = _fromUTF8(ret, dst_enc)
ret.force_encoding(dst_enc)
else
ret.force_encoding('utf-8')
end
else # without encoding
if dst_enc.kind_of?(String)
ret = _fromUTF8(ret, dst_enc)
ret.instance_variable_set(:@encoding, dst_enc)
else
ret.instance_variable_set(:@encoding, 'utf-8')
end
end
ret
else
TkCore::INTERP._merge_tklist(*dst)
end
end
else
###########################################################################
# use Ruby script version of split_list (traditional methods)
###########################################################################
def tk_split_escstr(str, src_enc=true, dst_enc=true)
return [] if str == ""
list = []
token = nil
escape = false
brace = 0
str.split('').each {|c|
brace += 1 if c == '{' && !escape
brace -= 1 if c == '}' && !escape
if brace == 0 && c == ' ' && !escape
list << token.gsub(/^\{(.*)\}$/, '\1') if token
token = nil
else
token = (token || "") << c
end
escape = (c == '\\' && !escape)
}
list << token.gsub(/^\{(.*)\}$/, '\1') if token
list
end
def tk_split_sublist(str, depth=-1, src_enc=true, dst_enc=true)
#return [] if str == ""
#return [tk_split_sublist(str[1..-2])] if str =~ /^\{.*\}$/
#list = tk_split_escstr(str)
if depth == 0
return "" if str == ""
str = str[1..-2] if str =~ /^\{.*\}$/
list = [str]
else
return [] if str == []
return [tk_split_sublist(str[1..-2], depth - 1)] if str =~ /^\{.*\}$/
list = tk_split_escstr(str)
end
if list.size == 1
tk_tcl2ruby(list[0], nil, false)
else
list.collect{|token| tk_split_sublist(token, depth - 1)}
end
end
def tk_split_list(str, depth=0, src_enc=true, dst_enc=true)
return [] if str == ""
tk_split_escstr(str).collect{|token|
tk_split_sublist(token, depth - 1)
}
end
def tk_split_simplelist(str, src_enc=true, dst_enc=true)
return [] if str == ""
list = []
token = nil
escape = false
brace = 0
str.split('').each {|c|
if c == '\\' && !escape
escape = true
token = (token || "") << c if brace > 0
next
end
brace += 1 if c == '{' && !escape
brace -= 1 if c == '}' && !escape
if brace == 0 && c == ' ' && !escape
list << token.gsub(/^\{(.*)\}$/, '\1') if token
token = nil
else
token = (token || "") << c
end
escape = false
}
list << token.gsub(/^\{(.*)\}$/, '\1') if token
list
end
def array2tk_list(ary, enc=nil)
ary.collect{|e|
if e.kind_of? Array
"{#{array2tk_list(e, enc)}}"
elsif e.kind_of? Hash
# "{#{e.to_a.collect{|ee| array2tk_list(ee)}.join(' ')}}"
e.each{|k,v| tmp_ary << "-#{_get_eval_string(k)}" << v }
array2tk_list(tmp_ary, enc)
else
s = _get_eval_string(e, enc)
(s.index(/\s/) || s.size == 0)? "{#{s}}": s
end
}.join(" ")
end
end
private :tk_split_escstr, :tk_split_sublist
private :tk_split_list, :tk_split_simplelist
private :array2tk_list
module_function :tk_split_escstr, :tk_split_sublist
module_function :tk_split_list, :tk_split_simplelist
module_function :array2tk_list
private_class_method :tk_split_escstr, :tk_split_sublist
private_class_method :tk_split_list, :tk_split_simplelist
# private_class_method :array2tk_list
=begin
### --> definition is moved to TkUtil module
def _symbolkey2str(keys)
h = {}
keys.each{|key,value| h[key.to_s] = value}
h
end
private :_symbolkey2str
module_function :_symbolkey2str
=end
=begin
### --> definition is moved to TkUtil module
# def hash_kv(keys, enc_mode = nil, conf = [], flat = false)
def hash_kv(keys, enc_mode = nil, conf = nil)
# Hash {key=>val, key=>val, ... } or Array [ [key, val], [key, val], ... ]
# ==> Array ['-key', val, '-key', val, ... ]
dst = []
if keys and keys != None
keys.each{|k, v|
#dst.push("-#{k}")
dst.push('-' + k.to_s)
if v != None
# v = _get_eval_string(v, enc_mode) if (enc_mode || flat)
v = _get_eval_string(v, enc_mode) if enc_mode
dst.push(v)
end
}
end
if conf
conf + dst
else
dst
end
end
private :hash_kv
module_function :hash_kv
=end
=begin
### --> definition is moved to TkUtil module
def bool(val)
case val
when "1", 1, 'yes', 'true'
true
else
false
end
end
def number(val)
case val
when /^-?\d+$/
val.to_i
when /^-?\d+\.?\d*(e[-+]?\d+)?$/
val.to_f
else
fail(ArgumentError, "invalid value for Number:'#{val}'")
end
end
def string(val)
if val == "{}"
''
elsif val[0] == ?{ && val[-1] == ?}
val[1..-2]
else
val
end
end
def num_or_str(val)
begin
number(val)
rescue ArgumentError
string(val)
end
end
=end
def list(val, depth=0, enc=true)
tk_split_list(val, depth, enc, enc)
end
def simplelist(val, src_enc=true, dst_enc=true)
tk_split_simplelist(val, src_enc, dst_enc)
end
def window(val)
if val =~ /^\./
#Tk_WINDOWS[val]? Tk_WINDOWS[val] : _genobj_for_tkwidget(val)
TkCore::INTERP.tk_windows[val]?
TkCore::INTERP.tk_windows[val] : _genobj_for_tkwidget(val)
else
nil
end
end
def image_obj(val)
if val =~ /^i(_\d+_)?\d+$/
TkImage::Tk_IMGTBL.mutex.synchronize{
TkImage::Tk_IMGTBL[val]? TkImage::Tk_IMGTBL[val] : val
}
else
val
end
end
def procedure(val)
=begin
if val =~ /^rb_out\S* (c(_\d+_)?\d+)/
#Tk_CMDTBL[$1]
#TkCore::INTERP.tk_cmd_tbl[$1]
TkCore::INTERP.tk_cmd_tbl[$1].cmd
=end
if val =~ /rb_out\S*(?:\s+(::\S*|[{](::.*)[}]|["](::.*)["]))? (c(_\d+_)?(\d+))/
return TkCore::INTERP.tk_cmd_tbl[$4].cmd
else
#nil
val
end
end
private :bool, :number, :num_or_str, :num_or_nil, :string
private :list, :simplelist, :window, :image_obj, :procedure
module_function :bool, :number, :num_or_str, :num_or_nil, :string
module_function :list, :simplelist, :window, :image_obj, :procedure
if (RUBY_VERSION.split('.').map{|n| n.to_i} <=> [1,8,7]) < 0
def slice_ary(ary, size)
sliced = []
wk_ary = ary.dup
until wk_ary.size.zero?
sub_ary = []
size.times{ sub_ary << wk_ary.shift }
yield(sub_ary) if block_given?
sliced << sub_ary
end
(block_given?)? ary: sliced
end
else
def slice_ary(ary, size, &b)
if b
ary.each_slice(size, &b)
else
ary.each_slice(size).to_a
end
end
end
private :slice_ary
module_function :slice_ary
def subst(str, *opts)
# opts := :nobackslashes | :nocommands | novariables
tk_call('subst',
*(opts.collect{|opt|
opt = opt.to_s
(opt[0] == ?-)? opt: '-' << opt
} << str))
end
def _toUTF8(str, encoding = nil)
TkCore::INTERP._toUTF8(str, encoding)
end
def _fromUTF8(str, encoding = nil)
TkCore::INTERP._fromUTF8(str, encoding)
end
private :_toUTF8, :_fromUTF8
module_function :_toUTF8, :_fromUTF8
def _callback_entry_class?(cls)
cls <= Proc || cls <= Method || cls <= TkCallbackEntry
end
private :_callback_entry_class?
module_function :_callback_entry_class?
def _callback_entry?(obj)
obj.kind_of?(Proc) || obj.kind_of?(Method) || obj.kind_of?(TkCallbackEntry)
end
private :_callback_entry?
module_function :_callback_entry?
=begin
### --> definition is moved to TkUtil module
def _get_eval_string(str, enc_mode = nil)
return nil if str == None
if str.kind_of?(TkObject)
str = str.path
elsif str.kind_of?(String)
str = _toUTF8(str) if enc_mode
elsif str.kind_of?(Symbol)
str = str.id2name
str = _toUTF8(str) if enc_mode
elsif str.kind_of?(Hash)
str = hash_kv(str, enc_mode).join(" ")
elsif str.kind_of?(Array)
str = array2tk_list(str)
str = _toUTF8(str) if enc_mode
elsif str.kind_of?(Proc)
str = install_cmd(str)
elsif str == nil
str = ""
elsif str == false
str = "0"
elsif str == true
str = "1"
elsif (str.respond_to?(:to_eval))
str = str.to_eval()
str = _toUTF8(str) if enc_mode
else
str = str.to_s() || ''
unless str.kind_of? String
fail RuntimeError, "fail to convert the object to a string"
end
str = _toUTF8(str) if enc_mode
end
return str
end
=end
=begin
def _get_eval_string(obj, enc_mode = nil)
case obj
when Numeric
obj.to_s
when String
(enc_mode)? _toUTF8(obj): obj
when Symbol
(enc_mode)? _toUTF8(obj.id2name): obj.id2name
when TkObject
obj.path
when Hash
hash_kv(obj, enc_mode).join(' ')
when Array
(enc_mode)? _toUTF8(array2tk_list(obj)): array2tk_list(obj)
when Proc, Method, TkCallbackEntry
install_cmd(obj)
when false
'0'
when true
'1'
when nil
''
when None
nil
else
if (obj.respond_to?(:to_eval))
(enc_mode)? _toUTF8(obj.to_eval): obj.to_eval
else
begin
obj = obj.to_s || ''
rescue
fail RuntimeError, "fail to convert object '#{obj}' to string"
end
(enc_mode)? _toUTF8(obj): obj
end
end
end
private :_get_eval_string
module_function :_get_eval_string
=end
=begin
### --> definition is moved to TkUtil module
def _get_eval_enc_str(obj)
return obj if obj == None
_get_eval_string(obj, true)
end
private :_get_eval_enc_str
module_function :_get_eval_enc_str
=end
=begin
### --> obsolete
def ruby2tcl(v, enc_mode = nil)
if v.kind_of?(Hash)
v = hash_kv(v)
v.flatten!
v.collect{|e|ruby2tcl(e, enc_mode)}
else
_get_eval_string(v, enc_mode)
end
end
private :ruby2tcl
=end
=begin
### --> definition is moved to TkUtil module
def _conv_args(args, enc_mode, *src_args)
conv_args = []
src_args.each{|arg|
conv_args << _get_eval_string(arg, enc_mode) unless arg == None
# if arg.kind_of?(Hash)
# arg.each{|k, v|
# args << '-' + k.to_s
# args << _get_eval_string(v, enc_mode)
# }
# elsif arg != None
# args << _get_eval_string(arg, enc_mode)
# end
}
args + conv_args
end
private :_conv_args
=end
def _curr_cmd_id
#id = format("c%.4d", Tk_IDs[0])
id = "c" + TkCore::INTERP._ip_id_ + TkComm::Tk_IDs[0]
end
def _next_cmd_id
TkComm::Tk_IDs.mutex.synchronize{
id = _curr_cmd_id
#Tk_IDs[0] += 1
TkComm::Tk_IDs[0].succ!
id
}
end
private :_curr_cmd_id, :_next_cmd_id
module_function :_curr_cmd_id, :_next_cmd_id
def TkComm.install_cmd(cmd, local_cmdtbl=nil)
return '' if cmd == ''
begin
ns = TkCore::INTERP._invoke_without_enc('namespace', 'current')
ns = nil if ns == '::' # for backward compatibility
rescue
# probably, Tcl7.6
ns = nil
end
id = _next_cmd_id
#Tk_CMDTBL[id] = cmd
if cmd.kind_of?(TkCallbackEntry)
TkCore::INTERP.tk_cmd_tbl[id] = cmd
else
TkCore::INTERP.tk_cmd_tbl[id] = TkCore::INTERP.get_cb_entry(cmd)
end
@cmdtbl = [] unless defined? @cmdtbl
TkUtil.untrust(@cmdtbl) unless @cmdtbl.tainted?
@cmdtbl.push id
if local_cmdtbl && local_cmdtbl.kind_of?(Array)
begin
local_cmdtbl << id
rescue Exception
# ignore
end
end
#return Kernel.format("rb_out %s", id);
if ns
'rb_out' << TkCore::INTERP._ip_id_ << ' ' << ns << ' ' << id
else
'rb_out' << TkCore::INTERP._ip_id_ << ' ' << id
end
end
def TkComm.uninstall_cmd(id, local_cmdtbl=nil)
#id = $1 if /rb_out\S* (c(_\d+_)?\d+)/ =~ id
id = $4 if id =~ /rb_out\S*(?:\s+(::\S*|[{](::.*)[}]|["](::.*)["]))? (c(_\d+_)?(\d+))/
if local_cmdtbl && local_cmdtbl.kind_of?(Array)
begin
local_cmdtbl.delete(id)
rescue Exception
# ignore
end
end
@cmdtbl.delete(id)
#Tk_CMDTBL.delete(id)
TkCore::INTERP.tk_cmd_tbl.delete(id)
end
# private :install_cmd, :uninstall_cmd
# module_function :install_cmd, :uninstall_cmd
def install_cmd(cmd)
TkComm.install_cmd(cmd, @cmdtbl)
end
def uninstall_cmd(id)
TkComm.uninstall_cmd(id, @cmdtbl)
end
=begin
def install_win(ppath,name=nil)
if !name or name == ''
#name = format("w%.4d", Tk_IDs[1])
#Tk_IDs[1] += 1
name = "w" + Tk_IDs[1]
Tk_IDs[1].succ!
end
if name[0] == ?.
@path = name.dup
elsif !ppath or ppath == "."
@path = Kernel.format(".%s", name);
else
@path = Kernel.format("%s.%s", ppath, name)
end
#Tk_WINDOWS[@path] = self
TkCore::INTERP.tk_windows[@path] = self
end
=end
def install_win(ppath,name=nil)
if name
if name == ''
raise ArgumentError, "invalid wiget-name '#{name}'"
end
if name[0] == ?.
@path = '' + name
@path.freeze
return TkCore::INTERP.tk_windows[@path] = self
end
else
Tk_IDs.mutex.synchronize{
name = "w" + TkCore::INTERP._ip_id_ + Tk_IDs[1]
Tk_IDs[1].succ!
}
end
if !ppath or ppath == '.'
@path = '.' + name
else
@path = ppath + '.' + name
end
@path.freeze
TkCore::INTERP.tk_windows[@path] = self
end
def uninstall_win()
#Tk_WINDOWS.delete(@path)
TkCore::INTERP.tk_windows.delete(@path)
end
private :install_win, :uninstall_win
def _epath(win)
if win.kind_of?(TkObject)
win.epath
elsif win.respond_to?(:epath)
win.epath
else
win
end
end
private :_epath
end
# define TkComm module (step 2: event binding)
module TkComm
include TkEvent
extend TkEvent
def tk_event_sequence(context)
if context.kind_of? TkVirtualEvent
context = context.path
end
if context.kind_of? Array
context = context.collect{|ev|
if ev.kind_of? TkVirtualEvent
ev.path
else
ev
end
}.join("><")
end
if /,/ =~ context
context = context.split(/\s*,\s*/).join("><")
else
context
end
end
def _bind_core(mode, what, context, cmd, *args)
id = install_bind(cmd, *args) if cmd
begin
tk_call_without_enc(*(what + ["<#{tk_event_sequence(context)}>",
mode + id]))
rescue
uninstall_cmd(id) if cmd
fail
end
end
def _bind(what, context, cmd, *args)
_bind_core('', what, context, cmd, *args)
end
def _bind_append(what, context, cmd, *args)
_bind_core('+', what, context, cmd, *args)
end
def _bind_remove(what, context)
tk_call_without_enc(*(what + ["<#{tk_event_sequence(context)}>", '']))
end
def _bindinfo(what, context=nil)
if context
if TkCore::WITH_RUBY_VM ### Ruby 1.9 !!!!
enum_obj = tk_call_without_enc(*what+["<#{tk_event_sequence(context)}>"]).each_line
else
enum_obj = tk_call_without_enc(*what+["<#{tk_event_sequence(context)}>"])
end
enum_obj.collect {|cmdline|
=begin
if cmdline =~ /^rb_out\S* (c(?:_\d+_)?\d+)\s+(.*)$/
#[Tk_CMDTBL[$1], $2]
[TkCore::INTERP.tk_cmd_tbl[$1], $2]
=end
if cmdline =~ /rb_out\S*(?:\s+(::\S*|[{](::.*)[}]|["](::.*)["]))? (c(_\d+_)?(\d+))/
[TkCore::INTERP.tk_cmd_tbl[$4], $5]
else
cmdline
end
}
else
tk_split_simplelist(tk_call_without_enc(*what)).collect!{|seq|
l = seq.scan(/<*[^<>]+>*/).collect!{|subseq|
case (subseq)
when /^<<[^<>]+>>$/
TkVirtualEvent.getobj(subseq[1..-2])
when /^<[^<>]+>$/
subseq[1..-2]
else
subseq.split('')
end
}.flatten
(l.size == 1) ? l[0] : l
}
end
end
def _bind_core_for_event_class(klass, mode, what, context, cmd, *args)
id = install_bind_for_event_class(klass, cmd, *args) if cmd
begin
tk_call_without_enc(*(what + ["<#{tk_event_sequence(context)}>",
mode + id]))
rescue
uninstall_cmd(id) if cmd
fail
end
end
def _bind_for_event_class(klass, what, context, cmd, *args)
_bind_core_for_event_class(klass, '', what, context, cmd, *args)
end
def _bind_append_for_event_class(klass, what, context, cmd, *args)
_bind_core_for_event_class(klass, '+', what, context, cmd, *args)
end
def _bind_remove_for_event_class(klass, what, context)
_bind_remove(what, context)
end
def _bindinfo_for_event_class(klass, what, context=nil)
_bindinfo(what, context)
end
private :tk_event_sequence
private :_bind_core, :_bind, :_bind_append, :_bind_remove, :_bindinfo
private :_bind_core_for_event_class, :_bind_for_event_class,
:_bind_append_for_event_class, :_bind_remove_for_event_class,
:_bindinfo_for_event_class
#def bind(tagOrClass, context, cmd=Proc.new, *args)
# _bind(["bind", tagOrClass], context, cmd, *args)
# tagOrClass
#end
def bind(tagOrClass, context, *args)
# if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
if TkComm._callback_entry?(args[0]) || !block_given?
cmd = args.shift
else
cmd = Proc.new
end
_bind(["bind", tagOrClass], context, cmd, *args)
tagOrClass
end
#def bind_append(tagOrClass, context, cmd=Proc.new, *args)
# _bind_append(["bind", tagOrClass], context, cmd, *args)
# tagOrClass
#end
def bind_append(tagOrClass, context, *args)
# if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
if TkComm._callback_entry?(args[0]) || !block_given?
cmd = args.shift
else
cmd = Proc.new
end
_bind_append(["bind", tagOrClass], context, cmd, *args)
tagOrClass
end
def bind_remove(tagOrClass, context)
_bind_remove(['bind', tagOrClass], context)
tagOrClass
end
def bindinfo(tagOrClass, context=nil)
_bindinfo(['bind', tagOrClass], context)
end
#def bind_all(context, cmd=Proc.new, *args)
# _bind(['bind', 'all'], context, cmd, *args)
# TkBindTag::ALL
#end
def bind_all(context, *args)
# if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
if TkComm._callback_entry?(args[0]) || !block_given?
cmd = args.shift
else
cmd = Proc.new
end
_bind(['bind', 'all'], context, cmd, *args)
TkBindTag::ALL
end
#def bind_append_all(context, cmd=Proc.new, *args)
# _bind_append(['bind', 'all'], context, cmd, *args)
# TkBindTag::ALL
#end
def bind_append_all(context, *args)
# if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
if TkComm._callback_entry?(args[0]) || !block_given?
cmd = args.shift
else
cmd = Proc.new
end
_bind_append(['bind', 'all'], context, cmd, *args)
TkBindTag::ALL
end
def bind_remove_all(context)
_bind_remove(['bind', 'all'], context)
TkBindTag::ALL
end
def bindinfo_all(context=nil)
_bindinfo(['bind', 'all'], context)
end
end
module TkCore
include TkComm
extend TkComm
WITH_RUBY_VM = Object.const_defined?(:RubyVM) && ::RubyVM.class == Class
WITH_ENCODING = defined?(::Encoding.default_external) && true
#WITH_ENCODING = Object.const_defined?(:Encoding) && ::Encoding.class == Class
unless self.const_defined? :INTERP
if self.const_defined? :IP_NAME
name = IP_NAME.to_s
else
#name = nil
name = $0
end
if self.const_defined? :IP_OPTS
if IP_OPTS.kind_of?(Hash)
opts = hash_kv(IP_OPTS).join(' ')
else
opts = IP_OPTS.to_s
end
else
opts = ''
end
# RUN_EVENTLOOP_ON_MAIN_THREAD = true
unless self.const_defined? :RUN_EVENTLOOP_ON_MAIN_THREAD
if WITH_RUBY_VM ### check Ruby 1.9 !!!!!!!
# *** NEED TO FIX ***
case RUBY_PLATFORM
when /cygwin/
RUN_EVENTLOOP_ON_MAIN_THREAD = true
when /darwin/ # MacOS X
=begin
ip = TclTkIp.new(name, opts)
if ip._invoke_without_enc('tk', 'windowingsystem') == 'aqua' &&
(TclTkLib.get_version<=>[8,4,TclTkLib::RELEASE_TYPE::FINAL,6]) > 0
=end
if TclTkLib::WINDOWING_SYSTEM == 'aqua' &&
(TclTkLib.get_version<=>[8,4,TclTkLib::RELEASE_TYPE::FINAL,6]) > 0
# *** KNOWN BUG ***
# Main event loop thread of TkAqua (> Tk8.4.9) must be the main
# application thread. So, ruby1.9 users must call Tk.mainloop on
# the main application thread.
#
# *** ADD (2009/05/10) ***
# In some cases (I don't know the description of conditions),
# TkAqua 8.4.7 has a same kind of hang-up trouble.
# So, if 8.4.7 or later, set RUN_EVENTLOOP_ON_MAIN_THREAD to true.
# When you want to control this mode, please call the following
# (set true/false as you want) before "require 'tk'".
# ----------------------------------------------------------
# module TkCore; RUN_EVENTLOOP_ON_MAIN_THREAD = true; end
# ----------------------------------------------------------
#
# *** ADD (2010/07/05) ***
# The value of TclTkLib::WINDOWING_SYSTEM is defined at compiling.
# If it is inconsistent with linked DLL, please call the following
# before "require 'tk'".
# ----------------------------------------------------------
# require 'tcltklib'
# module TclTkLib
# remove_const :WINDOWING_SYSTEM
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | true |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/abbrev.rb | lib/abbrev.rb | #!/usr/bin/env ruby
#--
# Copyright (c) 2001,2003 Akinori MUSHA <knu@iDaemons.org>
#
# All rights reserved. You can redistribute and/or modify it under
# the same terms as Ruby.
#
# $Idaemons: /home/cvs/rb/abbrev.rb,v 1.2 2001/05/30 09:37:45 knu Exp $
# $RoughId: abbrev.rb,v 1.4 2003/10/14 19:45:42 knu Exp $
# $Id: abbrev.rb 39362 2013-02-21 17:35:32Z zzak $
#++
##
# Calculates the set of unique abbreviations for a given set of strings.
#
# require 'abbrev'
# require 'pp'
#
# pp Abbrev.abbrev(['ruby', 'rules'])
#
# Generates:
#
# { "rub" => "ruby",
# "ruby" => "ruby",
# "rul" => "rules",
# "rule" => "rules",
# "rules" => "rules" }
#
# It also provides an array core extension, Array#abbrev.
#
# pp %w{summer winter}.abbrev
# #=> {"summe"=>"summer",
# "summ"=>"summer",
# "sum"=>"summer",
# "su"=>"summer",
# "s"=>"summer",
# "winte"=>"winter",
# "wint"=>"winter",
# "win"=>"winter",
# "wi"=>"winter",
# "w"=>"winter",
# "summer"=>"summer",
# "winter"=>"winter"}
module Abbrev
# Given a set of strings, calculate the set of unambiguous
# abbreviations for those strings, and return a hash where the keys
# are all the possible abbreviations and the values are the full
# strings.
#
# Thus, given +words+ is "car" and "cone", the keys pointing to "car" would
# be "ca" and "car", while those pointing to "cone" would be "co", "con", and
# "cone".
#
# require 'abbrev'
#
# Abbrev.abbrev(['car', 'cone'])
# #=> {"ca"=>"car", "con"=>"cone", "co"=>"cone", "car"=>"car", "cone"=>"cone"}
#
# The optional +pattern+ parameter is a pattern or a string. Only
# input strings that match the pattern or start with the string
# are included in the output hash.
#
# Abbrev.abbrev(%w{car box cone}, /b/)
# #=> {"bo"=>"box", "b"=>"box", "box"=>"box"}
def abbrev(words, pattern = nil)
table = {}
seen = Hash.new(0)
if pattern.is_a?(String)
pattern = /\A#{Regexp.quote(pattern)}/ # regard as a prefix
end
words.each do |word|
next if word.empty?
word.size.downto(1) { |len|
abbrev = word[0...len]
next if pattern && pattern !~ abbrev
case seen[abbrev] += 1
when 1
table[abbrev] = word
when 2
table.delete(abbrev)
else
break
end
}
end
words.each do |word|
next if pattern && pattern !~ word
table[word] = word
end
table
end
module_function :abbrev
end
class Array
# Calculates the set of unambiguous abbreviations for the strings in
# +self+.
#
# require 'abbrev'
# %w{ car cone }.abbrev
# #=> {"ca" => "car", "con"=>"cone", "co" => "cone",
# "car"=>"car", "cone" => "cone"}
#
# The optional +pattern+ parameter is a pattern or a string. Only
# input strings that match the pattern or start with the string
# are included in the output hash.
#
# %w{ fast boat day }.abbrev(/^.a/)
# #=> {"fas"=>"fast", "fa"=>"fast", "da"=>"day",
# "fast"=>"fast", "day"=>"day"}
#
# See also Abbrev.abbrev
def abbrev(pattern = nil)
Abbrev::abbrev(self, pattern)
end
end
if $0 == __FILE__
while line = gets
hash = line.split.abbrev
hash.sort.each do |k, v|
puts "#{k} => #{v}"
end
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/find.rb | lib/find.rb | #
# find.rb: the Find module for processing all files under a given directory.
#
#
# The +Find+ module supports the top-down traversal of a set of file paths.
#
# For example, to total the size of all files under your home directory,
# ignoring anything in a "dot" directory (e.g. $HOME/.ssh):
#
# require 'find'
#
# total_size = 0
#
# Find.find(ENV["HOME"]) do |path|
# if FileTest.directory?(path)
# if File.basename(path)[0] == ?.
# Find.prune # Don't look any further into this directory.
# else
# next
# end
# else
# total_size += FileTest.size(path)
# end
# end
#
module Find
#
# Calls the associated block with the name of every file and directory listed
# as arguments, then recursively on their subdirectories, and so on.
#
# Returns an enumerator if no block is given.
#
# See the +Find+ module documentation for an example.
#
def find(*paths) # :yield: path
block_given? or return enum_for(__method__, *paths)
fs_encoding = Encoding.find("filesystem")
paths.collect!{|d| raise Errno::ENOENT unless File.exist?(d); d.dup}.each do |path|
enc = path.encoding == Encoding::US_ASCII ? fs_encoding : path.encoding
ps = [path]
while file = ps.shift
catch(:prune) do
yield file.dup.taint
begin
s = File.lstat(file)
rescue Errno::ENOENT, Errno::EACCES, Errno::ENOTDIR, Errno::ELOOP, Errno::ENAMETOOLONG
next
end
if s.directory? then
begin
fs = Dir.entries(file, encoding: enc)
rescue Errno::ENOENT, Errno::EACCES, Errno::ENOTDIR, Errno::ELOOP, Errno::ENAMETOOLONG
next
end
fs.sort!
fs.reverse_each {|f|
next if f == "." or f == ".."
f = File.join(file, f)
ps.unshift f.untaint
}
end
end
end
end
nil
end
#
# Skips the current file or directory, restarting the loop with the next
# entry. If the current file is a directory, that directory will not be
# recursively entered. Meaningful only within the block associated with
# Find::find.
#
# See the +Find+ module documentation for an example.
#
def prune
throw :prune
end
module_function :find, :prune
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/tsort.rb | lib/tsort.rb | #--
# tsort.rb - provides a module for topological sorting and strongly connected components.
#++
#
#
# TSort implements topological sorting using Tarjan's algorithm for
# strongly connected components.
#
# TSort is designed to be able to be used with any object which can be
# interpreted as a directed graph.
#
# TSort requires two methods to interpret an object as a graph,
# tsort_each_node and tsort_each_child.
#
# * tsort_each_node is used to iterate for all nodes over a graph.
# * tsort_each_child is used to iterate for child nodes of a given node.
#
# The equality of nodes are defined by eql? and hash since
# TSort uses Hash internally.
#
# == A Simple Example
#
# The following example demonstrates how to mix the TSort module into an
# existing class (in this case, Hash). Here, we're treating each key in
# the hash as a node in the graph, and so we simply alias the required
# #tsort_each_node method to Hash's #each_key method. For each key in the
# hash, the associated value is an array of the node's child nodes. This
# choice in turn leads to our implementation of the required #tsort_each_child
# method, which fetches the array of child nodes and then iterates over that
# array using the user-supplied block.
#
# require 'tsort'
#
# class Hash
# include TSort
# alias tsort_each_node each_key
# def tsort_each_child(node, &block)
# fetch(node).each(&block)
# end
# end
#
# {1=>[2, 3], 2=>[3], 3=>[], 4=>[]}.tsort
# #=> [3, 2, 1, 4]
#
# {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}.strongly_connected_components
# #=> [[4], [2, 3], [1]]
#
# == A More Realistic Example
#
# A very simple `make' like tool can be implemented as follows:
#
# require 'tsort'
#
# class Make
# def initialize
# @dep = {}
# @dep.default = []
# end
#
# def rule(outputs, inputs=[], &block)
# triple = [outputs, inputs, block]
# outputs.each {|f| @dep[f] = [triple]}
# @dep[triple] = inputs
# end
#
# def build(target)
# each_strongly_connected_component_from(target) {|ns|
# if ns.length != 1
# fs = ns.delete_if {|n| Array === n}
# raise TSort::Cyclic.new("cyclic dependencies: #{fs.join ', '}")
# end
# n = ns.first
# if Array === n
# outputs, inputs, block = n
# inputs_time = inputs.map {|f| File.mtime f}.max
# begin
# outputs_time = outputs.map {|f| File.mtime f}.min
# rescue Errno::ENOENT
# outputs_time = nil
# end
# if outputs_time == nil ||
# inputs_time != nil && outputs_time <= inputs_time
# sleep 1 if inputs_time != nil && inputs_time.to_i == Time.now.to_i
# block.call
# end
# end
# }
# end
#
# def tsort_each_child(node, &block)
# @dep[node].each(&block)
# end
# include TSort
# end
#
# def command(arg)
# print arg, "\n"
# system arg
# end
#
# m = Make.new
# m.rule(%w[t1]) { command 'date > t1' }
# m.rule(%w[t2]) { command 'date > t2' }
# m.rule(%w[t3]) { command 'date > t3' }
# m.rule(%w[t4], %w[t1 t3]) { command 'cat t1 t3 > t4' }
# m.rule(%w[t5], %w[t4 t2]) { command 'cat t4 t2 > t5' }
# m.build('t5')
#
# == Bugs
#
# * 'tsort.rb' is wrong name because this library uses
# Tarjan's algorithm for strongly connected components.
# Although 'strongly_connected_components.rb' is correct but too long.
#
# == References
#
# R. E. Tarjan, "Depth First Search and Linear Graph Algorithms",
# <em>SIAM Journal on Computing</em>, Vol. 1, No. 2, pp. 146-160, June 1972.
#
module TSort
class Cyclic < StandardError
end
# Returns a topologically sorted array of nodes.
# The array is sorted from children to parents, i.e.
# the first element has no child and the last node has no parent.
#
# If there is a cycle, TSort::Cyclic is raised.
#
# class G
# include TSort
# def initialize(g)
# @g = g
# end
# def tsort_each_child(n, &b) @g[n].each(&b) end
# def tsort_each_node(&b) @g.each_key(&b) end
# end
#
# graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
# p graph.tsort #=> [4, 2, 3, 1]
#
# graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
# p graph.tsort # raises TSort::Cyclic
#
def tsort
each_node = method(:tsort_each_node)
each_child = method(:tsort_each_child)
TSort.tsort(each_node, each_child)
end
# Returns a topologically sorted array of nodes.
# The array is sorted from children to parents, i.e.
# the first element has no child and the last node has no parent.
#
# The graph is represented by _each_node_ and _each_child_.
# _each_node_ should have +call+ method which yields for each node in the graph.
# _each_child_ should have +call+ method which takes a node argument and yields for each child node.
#
# If there is a cycle, TSort::Cyclic is raised.
#
# g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
# each_node = lambda {|&b| g.each_key(&b) }
# each_child = lambda {|n, &b| g[n].each(&b) }
# p TSort.tsort(each_node, each_child) #=> [4, 2, 3, 1]
#
# g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
# each_node = lambda {|&b| g.each_key(&b) }
# each_child = lambda {|n, &b| g[n].each(&b) }
# p TSort.tsort(each_node, each_child) # raises TSort::Cyclic
#
def TSort.tsort(each_node, each_child)
result = []
TSort.tsort_each(each_node, each_child) {|element| result << element}
result
end
# The iterator version of the #tsort method.
# <tt><em>obj</em>.tsort_each</tt> is similar to <tt><em>obj</em>.tsort.each</tt>, but
# modification of _obj_ during the iteration may lead to unexpected results.
#
# #tsort_each returns +nil+.
# If there is a cycle, TSort::Cyclic is raised.
#
# class G
# include TSort
# def initialize(g)
# @g = g
# end
# def tsort_each_child(n, &b) @g[n].each(&b) end
# def tsort_each_node(&b) @g.each_key(&b) end
# end
#
# graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
# graph.tsort_each {|n| p n }
# #=> 4
# # 2
# # 3
# # 1
#
def tsort_each(&block) # :yields: node
each_node = method(:tsort_each_node)
each_child = method(:tsort_each_child)
TSort.tsort_each(each_node, each_child, &block)
end
# The iterator version of the TSort.tsort method.
#
# The graph is represented by _each_node_ and _each_child_.
# _each_node_ should have +call+ method which yields for each node in the graph.
# _each_child_ should have +call+ method which takes a node argument and yields for each child node.
#
# g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
# each_node = lambda {|&b| g.each_key(&b) }
# each_child = lambda {|n, &b| g[n].each(&b) }
# TSort.tsort_each(each_node, each_child) {|n| p n }
# #=> 4
# # 2
# # 3
# # 1
#
def TSort.tsort_each(each_node, each_child) # :yields: node
TSort.each_strongly_connected_component(each_node, each_child) {|component|
if component.size == 1
yield component.first
else
raise Cyclic.new("topological sort failed: #{component.inspect}")
end
}
end
# Returns strongly connected components as an array of arrays of nodes.
# The array is sorted from children to parents.
# Each elements of the array represents a strongly connected component.
#
# class G
# include TSort
# def initialize(g)
# @g = g
# end
# def tsort_each_child(n, &b) @g[n].each(&b) end
# def tsort_each_node(&b) @g.each_key(&b) end
# end
#
# graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
# p graph.strongly_connected_components #=> [[4], [2], [3], [1]]
#
# graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
# p graph.strongly_connected_components #=> [[4], [2, 3], [1]]
#
def strongly_connected_components
each_node = method(:tsort_each_node)
each_child = method(:tsort_each_child)
TSort.strongly_connected_components(each_node, each_child)
end
# Returns strongly connected components as an array of arrays of nodes.
# The array is sorted from children to parents.
# Each elements of the array represents a strongly connected component.
#
# The graph is represented by _each_node_ and _each_child_.
# _each_node_ should have +call+ method which yields for each node in the graph.
# _each_child_ should have +call+ method which takes a node argument and yields for each child node.
#
# g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
# each_node = lambda {|&b| g.each_key(&b) }
# each_child = lambda {|n, &b| g[n].each(&b) }
# p TSort.strongly_connected_components(each_node, each_child)
# #=> [[4], [2], [3], [1]]
#
# g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
# each_node = lambda {|&b| g.each_key(&b) }
# each_child = lambda {|n, &b| g[n].each(&b) }
# p TSort.strongly_connected_components(each_node, each_child)
# #=> [[4], [2, 3], [1]]
#
def TSort.strongly_connected_components(each_node, each_child)
result = []
TSort.each_strongly_connected_component(each_node, each_child) {|component| result << component}
result
end
# The iterator version of the #strongly_connected_components method.
# <tt><em>obj</em>.each_strongly_connected_component</tt> is similar to
# <tt><em>obj</em>.strongly_connected_components.each</tt>, but
# modification of _obj_ during the iteration may lead to unexpected results.
#
# #each_strongly_connected_component returns +nil+.
#
# class G
# include TSort
# def initialize(g)
# @g = g
# end
# def tsort_each_child(n, &b) @g[n].each(&b) end
# def tsort_each_node(&b) @g.each_key(&b) end
# end
#
# graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
# graph.each_strongly_connected_component {|scc| p scc }
# #=> [4]
# # [2]
# # [3]
# # [1]
#
# graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
# graph.each_strongly_connected_component {|scc| p scc }
# #=> [4]
# # [2, 3]
# # [1]
#
def each_strongly_connected_component(&block) # :yields: nodes
each_node = method(:tsort_each_node)
each_child = method(:tsort_each_child)
TSort.each_strongly_connected_component(each_node, each_child, &block)
end
# The iterator version of the TSort.strongly_connected_components method.
#
# The graph is represented by _each_node_ and _each_child_.
# _each_node_ should have +call+ method which yields for each node in the graph.
# _each_child_ should have +call+ method which takes a node argument and yields for each child node.
#
# g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
# each_node = lambda {|&b| g.each_key(&b) }
# each_child = lambda {|n, &b| g[n].each(&b) }
# TSort.each_strongly_connected_component(each_node, each_child) {|scc| p scc }
# #=> [4]
# # [2]
# # [3]
# # [1]
#
# g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
# each_node = lambda {|&b| g.each_key(&b) }
# each_child = lambda {|n, &b| g[n].each(&b) }
# TSort.each_strongly_connected_component(each_node, each_child) {|scc| p scc }
# #=> [4]
# # [2, 3]
# # [1]
#
def TSort.each_strongly_connected_component(each_node, each_child) # :yields: nodes
id_map = {}
stack = []
each_node.call {|node|
unless id_map.include? node
TSort.each_strongly_connected_component_from(node, each_child, id_map, stack) {|c|
yield c
}
end
}
nil
end
# Iterates over strongly connected component in the subgraph reachable from
# _node_.
#
# Return value is unspecified.
#
# #each_strongly_connected_component_from doesn't call #tsort_each_node.
#
# class G
# include TSort
# def initialize(g)
# @g = g
# end
# def tsort_each_child(n, &b) @g[n].each(&b) end
# def tsort_each_node(&b) @g.each_key(&b) end
# end
#
# graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
# graph.each_strongly_connected_component_from(2) {|scc| p scc }
# #=> [4]
# # [2]
#
# graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
# graph.each_strongly_connected_component_from(2) {|scc| p scc }
# #=> [4]
# # [2, 3]
#
def each_strongly_connected_component_from(node, id_map={}, stack=[], &block) # :yields: nodes
TSort.each_strongly_connected_component_from(node, method(:tsort_each_child), id_map, stack, &block)
end
# Iterates over strongly connected components in a graph.
# The graph is represented by _node_ and _each_child_.
#
# _node_ is the first node.
# _each_child_ should have +call+ method which takes a node argument
# and yields for each child node.
#
# Return value is unspecified.
#
# #TSort.each_strongly_connected_component_from is a class method and
# it doesn't need a class to represent a graph which includes TSort.
#
# graph = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
# each_child = lambda {|n, &b| graph[n].each(&b) }
# TSort.each_strongly_connected_component_from(1, each_child) {|scc|
# p scc
# }
# #=> [4]
# # [2, 3]
# # [1]
#
def TSort.each_strongly_connected_component_from(node, each_child, id_map={}, stack=[]) # :yields: nodes
minimum_id = node_id = id_map[node] = id_map.size
stack_length = stack.length
stack << node
each_child.call(node) {|child|
if id_map.include? child
child_id = id_map[child]
minimum_id = child_id if child_id && child_id < minimum_id
else
sub_minimum_id =
TSort.each_strongly_connected_component_from(child, each_child, id_map, stack) {|c|
yield c
}
minimum_id = sub_minimum_id if sub_minimum_id < minimum_id
end
}
if node_id == minimum_id
component = stack.slice!(stack_length .. -1)
component.each {|n| id_map[n] = nil}
yield component
end
minimum_id
end
# Should be implemented by a extended class.
#
# #tsort_each_node is used to iterate for all nodes over a graph.
#
def tsort_each_node # :yields: node
raise NotImplementedError.new
end
# Should be implemented by a extended class.
#
# #tsort_each_child is used to iterate for child nodes of _node_.
#
def tsort_each_child(node) # :yields: child
raise NotImplementedError.new
end
end
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | false |
grubby/grubby | https://github.com/grubby/grubby/blob/e582a835a585db590ca5df80aca3d5f1cbd1e774/lib/multi-tk.rb | lib/multi-tk.rb | #
# multi-tk.rb - supports multi Tk interpreters
# by Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
require 'tcltklib'
require 'tkutil'
require 'thread'
if defined? Tk
fail RuntimeError,"'multi-tk' library must be required before requiring 'tk'"
end
################################################
# ignore exception on the mainloop?
TclTkLib.mainloop_abort_on_exception = true
# TclTkLib.mainloop_abort_on_exception = false
# TclTkLib.mainloop_abort_on_exception = nil
################################################
# add ThreadGroup check to TclTkIp.new
class << TclTkIp
alias __new__ new
private :__new__
def new(*args)
if Thread.current.group != ThreadGroup::Default
raise SecurityError, 'only ThreadGroup::Default can call TclTkIp.new'
end
obj = __new__(*args)
obj.instance_eval{
@force_default_encoding ||= TkUtil.untrust([false])
@encoding ||= TkUtil.untrust([nil])
def @encoding.to_s; self.join(nil); end
}
obj
end
end
################################################
# exceptiopn to treat the return value from IP
class MultiTkIp_OK < Exception
def self.send(thread, ret=nil)
thread.raise self.new(ret)
end
def initialize(ret=nil)
super('succeed')
@return_value = ret
end
attr_reader :return_value
alias value return_value
end
MultiTkIp_OK.freeze
################################################
# methods for construction
class MultiTkIp
class Command_Queue < Queue
def initialize(interp)
@interp = interp
super()
end
def push(value)
if !@interp || @interp.deleted?
fail RuntimeError, "Tk interpreter is already deleted"
end
super(value)
end
alias << push
alias enq push
def close
@interp = nil
end
end
Command_Queue.freeze
BASE_DIR = File.dirname(__FILE__)
WITH_RUBY_VM = Object.const_defined?(:RubyVM) && ::RubyVM.class == Class
WITH_ENCODING = defined?(::Encoding.default_external)
#WITH_ENCODING = Object.const_defined?(:Encoding) && ::Encoding.class == Class
(@@SLAVE_IP_ID = ['slave'.freeze, TkUtil.untrust('0')]).instance_eval{
@mutex = Mutex.new
def mutex; @mutex; end
freeze
}
@@IP_TABLE = TkUtil.untrust({}) unless defined?(@@IP_TABLE)
@@INIT_IP_ENV = TkUtil.untrust([]) unless defined?(@@INIT_IP_ENV) # table of Procs
@@ADD_TK_PROCS = TkUtil.untrust([]) unless defined?(@@ADD_TK_PROCS) # table of [name, args, body]
@@TK_TABLE_LIST = TkUtil.untrust([]) unless defined?(@@TK_TABLE_LIST)
unless defined?(@@TK_CMD_TBL)
@@TK_CMD_TBL = TkUtil.untrust(Object.new)
# @@TK_CMD_TBL.instance_variable_set('@tbl', {}.taint)
tbl_obj = TkUtil.untrust(Hash.new{|hash,key|
fail IndexError, "unknown command ID '#{key}'"
})
@@TK_CMD_TBL.instance_variable_set('@tbl', tbl_obj)
class << @@TK_CMD_TBL
allow = [
'__send__', '__id__', 'freeze', 'inspect', 'kind_of?', 'object_id',
'[]', '[]=', 'delete', 'each', 'has_key?'
]
instance_methods.each{|m| undef_method(m) unless allow.index(m.to_s)}
def kind_of?(klass)
@tbl.kind_of?(klass)
end
def inspect
if Thread.current.group == ThreadGroup::Default
@tbl.inspect
else
ip = MultiTkIp.__getip
@tbl.reject{|idx, ent| ent.respond_to?(:ip) && ent.ip != ip}.inspect
end
end
def [](idx)
return unless (ent = @tbl[idx])
if Thread.current.group == ThreadGroup::Default
ent
elsif ent.respond_to?(:ip)
(ent.ip == MultiTkIp.__getip)? ent: nil
else
ent
end
end
def []=(idx,val)
if self.has_key?(idx) && Thread.current.group != ThreadGroup::Default
fail SecurityError,"cannot change the entried command"
end
@tbl[idx] = val
end
def delete(idx, &blk)
# if gets an entry, is permited to delete
if self[idx]
@tbl.delete(idx)
elsif blk
blk.call(idx)
else
nil
end
end
def each(&blk)
if Thread.current.group == ThreadGroup::Default
@tbl.each(&blk)
else
ip = MultiTkIp.__getip
@tbl.each{|idx, ent|
blk.call(idx, ent) unless ent.respond_to?(:ip) && ent.ip != ip
}
end
self
end
def has_key?(k)
@tbl.has_key?(k)
end
alias include? has_key?
alias key? has_key?
alias member? has_key?
end
@@TK_CMD_TBL.freeze
end
######################################
@@CB_ENTRY_CLASS = Class.new(TkCallbackEntry){
def initialize(ip, cmd)
@ip = ip
@safe = safe = $SAFE
# @cmd = cmd
cmd = MultiTkIp._proc_on_safelevel(&cmd)
@cmd = proc{|*args| cmd.call(safe, *args)}
self.freeze
end
attr_reader :ip, :cmd
def inspect
cmd.inspect
end
def call(*args)
unless @ip.deleted?
current = Thread.current
backup_ip = current[:callback_ip]
current[:callback_ip] = @ip
begin
ret = @ip.cb_eval(@cmd, *args)
fail ret if ret.kind_of?(Exception)
ret
rescue TkCallbackBreak, TkCallbackContinue => e
fail e
rescue SecurityError => e
# in 'exit', 'exit!', and 'abort' : security error --> delete IP
if e.backtrace[0] =~ /^(.+?):(\d+):in `(exit|exit!|abort)'/
@ip.delete
elsif @ip.safe?
if @ip.respond_to?(:cb_error)
@ip.cb_error(e)
else
nil # ignore
end
else
fail e
end
rescue Exception => e
fail e if e.message =~ /^TkCallback/
if @ip.safe?
if @ip.respond_to?(:cb_error)
@ip.cb_error(e)
else
nil # ignore
end
else
fail e
end
ensure
current[:callback_ip] = backup_ip
end
end
end
}.freeze
######################################
def _keys2opts(src_keys)
return nil if src_keys == nil
keys = {}; src_keys.each{|k, v| keys[k.to_s] = v}
#keys.collect{|k,v| "-#{k} #{v}"}.join(' ')
keys.collect{|k,v| "-#{k} #{TclTkLib._conv_listelement(TkComm::_get_eval_string(v))}"}.join(' ')
end
private :_keys2opts
def _check_and_return(thread, exception, wait=0)
unless thread
unless exception.kind_of?(MultiTkIp_OK)
msg = "#{exception.class}: #{exception.message}"
if @interp.deleted?
warn("Warning (#{self}): " + msg)
return nil
end
if safe?
warn("Warning (#{self}): " + msg) if $DEBUG
return nil
end
begin
@interp._eval_without_enc(@interp._merge_tklist('bgerror', msg))
rescue Exception => e
warn("Warning (#{self}): " + msg)
end
end
return nil
end
if wait == 0
# no wait
Thread.pass
if thread.stop?
thread.raise exception
end
return thread
end
# wait to stop the caller thread
wait.times{
if thread.stop?
# ready to send exception
thread.raise exception
return thread
end
# wait
Thread.pass
}
# unexpected error
thread.raise RuntimeError, "the thread may not wait for the return value"
return thread
end
######################################
def set_cb_error(cmd = Proc.new)
@cb_error_proc[0] = cmd
end
def cb_error(e)
if @cb_error_proc[0].respond_to?(:call)
@cb_error_proc[0].call(e)
end
end
######################################
def set_safe_level(safe)
if safe > @safe_level[0]
@safe_level[0] = safe
@cmd_queue.enq([@system, 'set_safe_level', safe])
end
@safe_level[0]
end
def safe_level=(safe)
set_safe_level(safe)
end
def self.set_safe_level(safe)
__getip.set_safe_level(safe)
end
def self.safe_level=(safe)
self.set_safe_level(safe)
end
def safe_level
@safe_level[0]
end
def self.safe_level
__getip.safe_level
end
def wait_on_mainloop?
@wait_on_mainloop[0]
end
def wait_on_mainloop=(bool)
@wait_on_mainloop[0] = bool
end
def running_mainloop?
@wait_on_mainloop[1] > 0
end
def _destroy_slaves_of_slaveIP(ip)
unless ip.deleted?
# ip._split_tklist(ip._invoke('interp', 'slaves')).each{|name|
ip._split_tklist(ip._invoke_without_enc('interp', 'slaves')).each{|name|
name = _fromUTF8(name)
begin
# ip._eval_without_enc("#{name} eval {foreach i [after info] {after cancel $i}}")
after_ids = ip._eval_without_enc("#{name} eval {after info}")
ip._eval_without_enc("#{name} eval {foreach i {#{after_ids}} {after cancel $i}}")
rescue Exception
end
begin
# ip._invoke('interp', 'eval', name, 'destroy', '.')
ip._invoke(name, 'eval', 'destroy', '.')
rescue Exception
end
# safe_base?
if ip._eval_without_enc("catch {::safe::interpConfigure #{name}}") == '0'
begin
ip._eval_without_enc("::safe::interpDelete #{name}")
rescue Exception
end
end
=begin
if ip._invoke('interp', 'exists', name) == '1'
begin
ip._invoke(name, 'eval', 'exit')
rescue Exception
end
end
=end
unless ip.deleted?
if ip._invoke('interp', 'exists', name) == '1'
begin
ip._invoke('interp', 'delete', name)
rescue Exception
end
end
end
}
end
end
def _receiver_eval_proc_core(safe_level, thread, cmd, *args)
begin
#ret = proc{$SAFE = safe_level; cmd.call(*args)}.call
#ret = cmd.call(safe_level, *args)
normal_ret = false
ret = catch(:IRB_EXIT) do # IRB hack
retval = cmd.call(safe_level, *args)
normal_ret = true
retval
end
unless normal_ret
# catch IRB_EXIT
exit(ret)
end
ret
rescue SystemExit => e
# delete IP
unless @interp.deleted?
@slave_ip_tbl.each{|name, subip|
_destroy_slaves_of_slaveIP(subip)
begin
# subip._eval_without_enc("foreach i [after info] {after cancel $i}")
after_ids = subip._eval_without_enc("after info")
subip._eval_without_enc("foreach i {#{after_ids}} {after cancel $i}")
rescue Exception
end
=begin
begin
subip._invoke('destroy', '.') unless subip.deleted?
rescue Exception
end
=end
# safe_base?
if @interp._eval_without_enc("catch {::safe::interpConfigure #{name}}") == '0'
begin
@interp._eval_without_enc("::safe::interpDelete #{name}")
rescue Exception
else
next if subip.deleted?
end
end
if subip.respond_to?(:safe_base?) && subip.safe_base? &&
!subip.deleted?
# do 'exit' to call the delete_hook procedure
begin
subip._eval_without_enc('exit')
rescue Exception
end
else
begin
subip.delete unless subip.deleted?
rescue Exception
end
end
}
begin
# @interp._eval_without_enc("foreach i [after info] {after cancel $i}")
after_ids = @interp._eval_without_enc("after info")
@interp._eval_without_enc("foreach i {#{after_ids}} {after cancel $i}")
rescue Exception
end
begin
@interp._invoke('destroy', '.') unless @interp.deleted?
rescue Exception
end
if @safe_base && !@interp.deleted?
# do 'exit' to call the delete_hook procedure
@interp._eval_without_enc('exit')
else
@interp.delete unless @interp.deleted?
end
end
if e.backtrace[0] =~ /^(.+?):(\d+):in `(exit|exit!|abort)'/
_check_and_return(thread, MultiTkIp_OK.new($3 == 'exit'))
else
_check_and_return(thread, MultiTkIp_OK.new(nil))
end
# if master? && !safe? && allow_ruby_exit?
if !@interp.deleted? && master? && !safe? && allow_ruby_exit?
=begin
ObjectSpace.each_object(TclTkIp){|obj|
obj.delete unless obj.deleted?
}
=end
#exit(e.status)
fail e
end
# break
rescue SecurityError => e
# in 'exit', 'exit!', and 'abort' : security error --> delete IP
if e.backtrace[0] =~ /^(.+?):(\d+):in `(exit|exit!|abort)'/
ret = ($3 == 'exit')
unless @interp.deleted?
@slave_ip_tbl.each{|name, subip|
_destroy_slaves_of_slaveIP(subip)
begin
# subip._eval_without_enc("foreach i [after info] {after cancel $i}")
after_ids = subip._eval_without_enc("after info")
subip._eval_without_enc("foreach i {#{after_ids}} {after cancel $i}")
rescue Exception
end
=begin
begin
subip._invoke('destroy', '.') unless subip.deleted?
rescue Exception
end
=end
# safe_base?
if @interp._eval_without_enc("catch {::safe::interpConfigure #{name}}") == '0'
begin
@interp._eval_without_enc("::safe::interpDelete #{name}")
rescue Exception
else
next if subip.deleted?
end
end
if subip.respond_to?(:safe_base?) && subip.safe_base? &&
!subip.deleted?
# do 'exit' to call the delete_hook procedure
begin
subip._eval_without_enc('exit')
rescue Exception
end
else
begin
subip.delete unless subip.deleted?
rescue Exception
end
end
}
begin
# @interp._eval_without_enc("foreach i [after info] {after cancel $i}")
after_ids = @interp._eval_without_enc("after info")
@interp._eval_without_enc("foreach i {#{after_ids}} {after cancel $i}")
rescue Exception
end
=begin
begin
@interp._invoke('destroy', '.') unless @interp.deleted?
rescue Exception
end
=end
if @safe_base && !@interp.deleted?
# do 'exit' to call the delete_hook procedure
@interp._eval_without_enc('exit')
else
@interp.delete unless @interp.deleted?
end
end
_check_and_return(thread, MultiTkIp_OK.new(ret))
# break
else
# raise security error
_check_and_return(thread, e)
end
rescue Exception => e
# raise exception
begin
bt = _toUTF8(e.backtrace.join("\n"))
if MultiTkIp::WITH_ENCODING
bt.force_encoding('utf-8')
else
bt.instance_variable_set(:@encoding, 'utf-8')
end
rescue Exception
bt = e.backtrace.join("\n")
end
begin
@interp._set_global_var('errorInfo', bt)
rescue Exception
end
_check_and_return(thread, e)
else
# no exception
_check_and_return(thread, MultiTkIp_OK.new(ret))
end
end
def _receiver_eval_proc(last_thread, safe_level, thread, cmd, *args)
if thread
Thread.new{
last_thread.join if last_thread
unless @interp.deleted?
_receiver_eval_proc_core(safe_level, thread, cmd, *args)
end
}
else
Thread.new{
unless @interp.deleted?
_receiver_eval_proc_core(safe_level, thread, cmd, *args)
end
}
last_thread
end
end
private :_receiver_eval_proc, :_receiver_eval_proc_core
def _receiver_mainloop(check_root)
if @evloop_thread[0] && @evloop_thread[0].alive?
@evloop_thread[0]
else
@evloop_thread[0] = Thread.new{
while !@interp.deleted?
#if check_root
# inf = @interp._invoke_without_enc('info', 'command', '.')
# break if !inf.kind_of?(String) || inf != '.'
#end
break if check_root && !@interp.has_mainwindow?
sleep 0.5
end
}
@evloop_thread[0]
end
end
def _create_receiver_and_watchdog(lvl = $SAFE)
lvl = $SAFE if lvl < $SAFE
# command-procedures receiver
receiver = Thread.new(lvl){|safe_level|
last_thread = {}
loop do
break if @interp.deleted?
thread, cmd, *args = @cmd_queue.deq
if thread == @system
# control command
case cmd
when 'set_safe_level'
begin
safe_level = args[0] if safe_level < args[0]
rescue Exception
end
when 'call_mainloop'
thread = args.shift
_check_and_return(thread,
MultiTkIp_OK.new(_receiver_mainloop(*args)))
else
# ignore
end
else
# procedure
last_thread[thread] = _receiver_eval_proc(last_thread[thread],
safe_level, thread,
cmd, *args)
end
end
}
# watchdog of receiver
watchdog = Thread.new{
begin
loop do
sleep 1
if @interp.deleted?
receiver.kill
@cmd_queue.close
end
break unless receiver.alive?
end
rescue Exception
# ignore all kind of Exception
end
# receiver is dead
retry_count = 3
loop do
Thread.pass
begin
thread, cmd, *args = @cmd_queue.deq(true) # non-block
rescue ThreadError
# queue is empty
retry_count -= 1
break if retry_count <= 0
sleep 0.5
retry
end
next unless thread
if thread.alive?
if @interp.deleted?
thread.raise RuntimeError, 'the interpreter is already deleted'
else
thread.raise RuntimeError,
'the interpreter no longer receives command procedures'
end
end
end
}
# return threads
[receiver, watchdog]
end
private :_check_and_return, :_create_receiver_and_watchdog
######################################
unless self.const_defined? :RUN_EVENTLOOP_ON_MAIN_THREAD
### Ruby 1.9 !!!!!!!!!!!!!!!!!!!!!!!!!!
RUN_EVENTLOOP_ON_MAIN_THREAD = false
end
if self.const_defined? :DEFAULT_MASTER_NAME
name = DEFAULT_MASTER_NAME.to_s
else
name = nil
end
if self.const_defined?(:DEFAULT_MASTER_OPTS) &&
DEFAULT_MASTER_OPTS.kind_of?(Hash)
keys = DEFAULT_MASTER_OPTS
else
keys = {}
end
@@DEFAULT_MASTER = self.allocate
@@DEFAULT_MASTER.instance_eval{
@tk_windows = TkUtil.untrust({})
@tk_table_list = TkUtil.untrust([])
@slave_ip_tbl = TkUtil.untrust({})
@slave_ip_top = TkUtil.untrust({})
@evloop_thread = TkUtil.untrust([])
unless keys.kind_of? Hash
fail ArgumentError, "expecting a Hash object for the 2nd argument"
end
if !WITH_RUBY_VM || RUN_EVENTLOOP_ON_MAIN_THREAD ### check Ruby 1.9 !!!!!!!
@interp = TclTkIp.new(name, _keys2opts(keys))
else ### Ruby 1.9 !!!!!!!!!!!
@interp_thread = Thread.new{
current = Thread.current
begin
current[:interp] = interp = TclTkIp.new(name, _keys2opts(keys))
rescue e
current[:interp] = e
raise e
end
#sleep
current[:mutex] = mutex = Mutex.new
current[:root_check] = cond_var = ConditionVariable.new
status = [nil]
def status.value
self[0]
end
def status.value=(val)
self[0] = val
end
current[:status] = status
begin
begin
#TclTkLib.mainloop_abort_on_exception = false
#Thread.current[:status].value = TclTkLib.mainloop(true)
interp.mainloop_abort_on_exception = true
current[:status].value = interp.mainloop(true)
rescue SystemExit=>e
current[:status].value = e
rescue Exception=>e
current[:status].value = e
retry if interp.has_mainwindow?
ensure
mutex.synchronize{ cond_var.broadcast }
end
#Thread.current[:status].value = TclTkLib.mainloop(false)
current[:status].value = interp.mainloop(false)
ensure
# interp must be deleted before the thread for interp is dead.
# If not, raise Tcl_Panic on Tcl_AsyncDelete because async handler
# deleted by the wrong thread.
interp.delete
end
}
until @interp_thread[:interp]
Thread.pass
end
# INTERP_THREAD.run
raise @interp_thread[:interp] if @interp_thread[:interp].kind_of? Exception
@interp = @interp_thread[:interp]
# delete the interpreter and kill the eventloop thread at exit
interp = @interp
interp_thread = @interp_thread
END{
if interp_thread.alive?
interp.delete
interp_thread.kill
end
}
def self.mainloop(check_root = true)
begin
TclTkLib.set_eventloop_window_mode(true)
@interp_thread.value
ensure
TclTkLib.set_eventloop_window_mode(false)
end
end
end
@interp.instance_eval{
@force_default_encoding ||= TkUtil.untrust([false])
@encoding ||= TkUtil.untrust([nil])
def @encoding.to_s; self.join(nil); end
}
@ip_name = nil
@callback_status = TkUtil.untrust([])
@system = Object.new
@wait_on_mainloop = TkUtil.untrust([true, 0])
@threadgroup = Thread.current.group
@safe_base = false
@safe_level = [$SAFE]
@cmd_queue = MultiTkIp::Command_Queue.new(@interp)
@cmd_receiver, @receiver_watchdog = _create_receiver_and_watchdog(@safe_level[0])
@threadgroup.add @cmd_receiver
@threadgroup.add @receiver_watchdog
# NOT enclose @threadgroup for @@DEFAULT_MASTER
@@IP_TABLE[ThreadGroup::Default] = self
@@IP_TABLE[@threadgroup] = self
#################################
@pseudo_toplevel = [false, nil]
def self.__pseudo_toplevel
Thread.current.group == ThreadGroup::Default &&
MultiTkIp.__getip == @@DEFAULT_MASTER &&
self.__pseudo_toplevel_evaluable? && @pseudo_toplevel[1]
end
def self.__pseudo_toplevel=(m)
unless (Thread.current.group == ThreadGroup::Default &&
MultiTkIp.__getip == @@DEFAULT_MASTER)
fail SecurityError, "no permission to manipulate"
end
# if m.kind_of?(Module) && m.respond_to?(:pseudo_toplevel_evaluable?)
if m.respond_to?(:pseudo_toplevel_evaluable?)
@pseudo_toplevel[0] = true
@pseudo_toplevel[1] = m
else
fail ArgumentError, 'fail to set pseudo-toplevel'
end
self
end
def self.__pseudo_toplevel_evaluable?
begin
@pseudo_toplevel[0] && @pseudo_toplevel[1].pseudo_toplevel_evaluable?
rescue Exception
false
end
end
def self.__pseudo_toplevel_evaluable=(mode)
unless (Thread.current.group == ThreadGroup::Default &&
MultiTkIp.__getip == @@DEFAULT_MASTER)
fail SecurityError, "no permission to manipulate"
end
@pseudo_toplevel[0] = (mode)? true: false
end
#################################
@assign_request = Class.new(Exception){
def self.new(target, ret)
obj = super()
obj.target = target
obj.ret = ret
obj
end
attr_accessor :target, :ret
}
@assign_thread = Thread.new{
loop do
begin
Thread.stop
rescue @assign_request=>req
begin
req.ret[0] = req.target.instance_eval{
@cmd_receiver, @receiver_watchdog =
_create_receiver_and_watchdog(@safe_level[0])
@threadgroup.add @cmd_receiver
@threadgroup.add @receiver_watchdog
@threadgroup.enclose
true
}
rescue Exception=>e
begin
req.ret[0] = e
rescue Exception
# ignore
end
end
rescue Exception
# ignore
end
end
}
def self.assign_receiver_and_watchdog(target)
ret = [nil]
@assign_thread.raise(@assign_request.new(target, ret))
while ret[0] == nil
unless @assign_thread.alive?
raise RuntimeError, 'lost the thread to assign a receiver and a watchdog thread'
end
end
if ret[0].kind_of?(Exception)
raise ret[0]
else
ret[0]
end
end
#################################
@init_ip_env_queue = Queue.new
Thread.new{
current = Thread.current
loop {
mtx, cond, ret, table, script = @init_ip_env_queue.deq
begin
ret[0] = table.each{|tg, ip| ip._init_ip_env(script) }
rescue Exception => e
ret[0] = e
ensure
mtx.synchronize{ cond.signal }
end
mtx = cond = ret = table = script = nil # clear variables for GC
}
}
def self.__init_ip_env__(table, script)
ret = []
mtx = (Thread.current[:MultiTk_ip_Mutex] ||= Mutex.new)
cond = (Thread.current[:MultiTk_ip_CondVar] ||= ConditionVariable.new)
mtx.synchronize{
@init_ip_env_queue.enq([mtx, cond, ret, table, script])
cond.wait(mtx)
}
if ret[0].kind_of?(Exception)
raise ret[0]
else
ret[0]
end
end
#################################
class << self
undef :instance_eval
end
}
@@DEFAULT_MASTER.freeze # defend against modification
######################################
def self.inherited(subclass)
# trust if on ThreadGroup::Default or @@DEFAULT_MASTER's ThreadGroup
if @@IP_TABLE[Thread.current.group] == @@DEFAULT_MASTER
begin
class << subclass
self.methods.each{|m|
name = m.to_s
begin
unless name == '__id__' || name == '__send__' || name == 'freeze'
undef_method(m)
end
rescue Exception
# ignore all exceptions
end
}
end
ensure
subclass.freeze
fail SecurityError,
"cannot create subclass of MultiTkIp on a untrusted ThreadGroup"
end
end
end
######################################
@@SAFE_OPT_LIST = [
'accessPath'.freeze,
'statics'.freeze,
'nested'.freeze,
'deleteHook'.freeze
].freeze
def _parse_slaveopts(keys)
name = nil
safe = false
safe_opts = {}
tk_opts = {}
keys.each{|k,v|
k_str = k.to_s
if k_str == 'name'
name = v
elsif k_str == 'safe'
safe = v
elsif @@SAFE_OPT_LIST.member?(k_str)
safe_opts[k_str] = v
else
tk_opts[k_str] = v
end
}
if keys['without_tk'] || keys[:without_tk]
[name, safe, safe_opts, nil]
else
[name, safe, safe_opts, tk_opts]
end
end
private :_parse_slaveopts
def _create_slave_ip_name
@@SLAVE_IP_ID.mutex.synchronize{
name = @@SLAVE_IP_ID.join('')
@@SLAVE_IP_ID[1].succ!
name.freeze
}
end
private :_create_slave_ip_name
######################################
def __check_safetk_optkeys(optkeys)
# based on 'safetk.tcl'
new_keys = {}
optkeys.each{|k,v| new_keys[k.to_s] = v}
# check 'display'
if !new_keys.key?('display')
begin
#new_keys['display'] = @interp._invoke('winfo screen .')
new_keys['display'] = @interp._invoke('winfo', 'screen', '.')
rescue
if ENV[DISPLAY]
new_keys['display'] = ENV[DISPLAY]
elsif !new_keys.key?('use')
warn "Warning: no screen info or ENV[DISPLAY], so use ':0.0'"
new_keys['display'] = ':0.0'
end
end
end
# check 'use'
if new_keys.key?('use')
# given 'use'
case new_keys['use']
when TkWindow
new_keys['use'] = TkWinfo.id(new_keys['use'])
#assoc_display = @interp._eval('winfo screen .')
assoc_display = @interp._invoke('winfo', 'screen', '.')
when /^\..*/
new_keys['use'] = @interp._invoke('winfo', 'id', new_keys['use'])
assoc_display = @interp._invoke('winfo', 'screen', new_keys['use'])
else
begin
pathname = @interp._invoke('winfo', 'pathname', new_keys['use'])
assoc_display = @interp._invoke('winfo', 'screen', pathname)
rescue
assoc_display = new_keys['display']
end
end
# match display?
if assoc_display != new_keys['display']
if optkeys.key?(:display) || optkeys.key?('display')
fail RuntimeError,
"conflicting 'display'=>#{new_keys['display']} " +
"and display '#{assoc_display}' on 'use'=>#{new_keys['use']}"
else
new_keys['display'] = assoc_display
end
end
end
# return
new_keys
end
private :__check_safetk_optkeys
def __create_safetk_frame(slave_ip, slave_name, app_name, keys)
# display option is used by ::safe::loadTk
loadTk_keys = {}
loadTk_keys['display'] = keys['display']
dup_keys = keys.dup
# keys for toplevel : allow followings
toplevel_keys = {}
['height', 'width', 'background', 'menu'].each{|k|
toplevel_keys[k] = dup_keys.delete(k) if dup_keys.key?(k)
}
toplevel_keys['classname'] = 'SafeTk'
toplevel_keys['screen'] = dup_keys.delete('display')
# other keys used by pack option of container frame
# create toplevel widget
begin
top = TkToplevel.new(toplevel_keys)
rescue NameError => e
fail e unless @interp.safe?
fail SecurityError, "unable create toplevel on the safe interpreter"
end
msg = "Untrusted Ruby/Tk applet (#{slave_name})"
if app_name.kind_of?(String)
top.title "#{app_name} (#{slave_name})"
else
top.title msg
end
# procedure to delete slave interpreter
slave_delete_proc = proc{
unless slave_ip.deleted?
#if slave_ip._invoke('info', 'command', '.') != ""
# slave_ip._invoke('destroy', '.')
#end
#slave_ip.delete
slave_ip._eval_without_enc('exit')
end
begin
top.destroy if top.winfo_exist?
rescue
# ignore
end
}
tag = TkBindTag.new.bind('Destroy', slave_delete_proc)
top.bindtags = top.bindtags.unshift(tag)
# create control frame
TkFrame.new(top, :bg=>'red', :borderwidth=>3, :relief=>'ridge') {|fc|
fc.bindtags = fc.bindtags.unshift(tag)
TkFrame.new(fc, :bd=>0){|f|
TkButton.new(f,
:text=>'Delete', :bd=>1, :padx=>2, :pady=>0,
:highlightthickness=>0, :command=>slave_delete_proc
).pack(:side=>:right, :fill=>:both)
f.pack(:side=>:right, :fill=>:both, :expand=>true)
}
TkLabel.new(fc, :text=>msg, :padx=>2, :pady=>0,
:anchor=>:w).pack(:side=>:left, :fill=>:both, :expand=>true)
fc.pack(:side=>:bottom, :fill=>:x)
}
# container frame for slave interpreter
dup_keys['fill'] = :both unless dup_keys.key?('fill')
dup_keys['expand'] = true unless dup_keys.key?('expand')
c = TkFrame.new(top, :container=>true).pack(dup_keys)
c.bind('Destroy', proc{top.destroy})
# return keys
loadTk_keys['use'] = TkWinfo.id(c)
[loadTk_keys, top.path]
end
private :__create_safetk_frame
def __create_safe_slave_obj(safe_opts, app_name, tk_opts)
raise SecurityError, "no permission to manipulate" unless self.manipulable?
# safe interpreter
ip_name = _create_slave_ip_name
slave_ip = @interp.create_slave(ip_name, true)
slave_ip.instance_eval{
@force_default_encoding ||= TkUtil.untrust([false])
@encoding ||= TkUtil.untrust([nil])
def @encoding.to_s; self.join(nil); end
}
@slave_ip_tbl[ip_name] = slave_ip
def slave_ip.safe_base?
true
end
@interp._eval("::safe::interpInit #{ip_name}")
slave_ip._invoke('set', 'argv0', app_name) if app_name.kind_of?(String)
if tk_opts
| ruby | MIT | e582a835a585db590ca5df80aca3d5f1cbd1e774 | 2026-01-04T17:51:36.659653Z | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.