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 |
|---|---|---|---|---|---|---|---|---|
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/app/_plugins/generators/alias.rb | app/_plugins/generators/alias.rb | # frozen_string_literal: true
module Jekyll
class Alias < Jekyll::Generator
priority :lowest
def generate(site)
static_files = [
'app/_headers'
]
static_files.each do |path|
content = File.read(path)
page = PageWithoutAFile.new(site, __dir__, '', path.sub('app/', ''))
page.content = content
page.data['layout'] = nil
site.pages << page
end
end
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/app/_plugins/generators/versions.rb | app/_plugins/generators/versions.rb | # frozen_string_literal: true
module Jekyll
class Versions < Jekyll::Generator
priority :normal
def generate(site)
latest_version = latest_version(site.data['versions'])
site.data['latest_version'] = latest_version
# Add a `version` property to every versioned page
# TODO: Also create aliases under /latest/ for all x.x.x doc pages
site.pages.each do |page|
next unless page.url.start_with?('/docs/')
release = release_for(page)
page.data['nav_items'] = {}
next unless release
page.data['doc'] = true
page.data['has_version'] = true
page.data['release'] ||= release.to_liquid
page.data['version'] ||= release.default_version
page.data['version_data'] = release.to_h
page.data['latest_version'] = edition(site).latest_release.to_h
# This will be removed once jekyll-single-site-generator stops discarding very new versions when use `{%version lte:unreleasedVersion %}`
page.data['nav_items'] = site.data["docs_nav_kuma_#{release.value.gsub('.', '')}"]
# Clean up nav_items for generated pages as there's an
# additional level of nesting
page.data['nav_items'] = page.data['nav_items']['items'] if page.data['nav_items'].is_a?(Hash)
end
end
private
def latest_version(versions)
latest_versions = versions.select { |v| v['latest'] }
raise "Exactly one entry in app/_data/versions.yml must be marked as 'latest: true' (#{latest_versions.size} found)" if latest_versions.size != 1
latest_versions.first
end
def edition(site)
@edition ||= Jekyll::GeneratorSingleSource::Product::Edition
.new(edition: 'kuma', site: site)
end
def release_for(page)
parts = Pathname(page.url).each_filename.to_a
edition(page.site).releases.detect { |r| r.to_s == parts[1] }
end
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/app/_plugins/generators/sitemap.rb | app/_plugins/generators/sitemap.rb | # frozen_string_literal: true
module Sitemap
class Generator < Jekyll::Generator
priority :lowest
def generate(site)
# What's our latest version?
latest = site.data['latest_version']
# Grab all pages that contain that version
all_pages = []
# Build a map of the latest available version of every URL
site.pages.each do |page|
# Skip if it's not the latest version of a page
next if versioned_url?(page['url']) && !version?(page['url'], latest)
all_pages << page
end
# Build a map of the latest available version of every URL
site.posts.docs.each do |post|
all_pages << {
'url' => post.url
}
end
# Save the data to generate a sitemap later
site.data['sitemap_pages'] = build_sitemap(all_pages)
end
def build_sitemap(pages)
# These files should NOT be in the sitemap
blocked_from_sitemap = [
'/_headers',
'/_redirects',
'/404.html'
]
# Remove any pages that should not be in the sitemap
pages = pages.filter do |p|
next false if blocked_from_sitemap.any? { |blocked| p['url'] == blocked }
true
end
# Set the frequency and priority values for the sitemap to use
pages.map do |p|
{
'url' => p['url'],
'changefreq' => 'weekly',
'priority' => '1.0'
}
end
end
def versioned_url?(url)
versioned = [
'/install/',
'/docs/'
]
versioned.each do |v|
return true if url.include?(v)
end
false
end
def version?(url, latest)
url.include?(latest['release'])
end
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/app/_plugins/filters/indent_filter.rb | app/_plugins/filters/indent_filter.rb | # frozen_string_literal: true
module IndentFilter
def indent(input)
input
.gsub("\n</code>", '</code>')
.split("\n")
.map { |l| l.prepend(' ') }
.join("\n")
end
end
Liquid::Template.register_filter(IndentFilter)
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/spec/spec_helper.rb | jekyll-kuma-plugins/spec/spec_helper.rb | # frozen_string_literal: true
require 'jekyll_kuma_plugins'
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = '.rspec_status'
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/spec/jekyll/kuma_plugins/plugins_spec.rb | jekyll-kuma-plugins/spec/jekyll/kuma_plugins/plugins_spec.rb | # frozen_string_literal: true
RSpec.describe Jekyll::KumaPlugins do
it 'has a version number' do
expect(Jekyll::KumaPlugins::VERSION).not_to be nil
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/spec/jekyll/kuma_plugins/common/params_spec.rb | jekyll-kuma-plugins/spec/jekyll/kuma_plugins/common/params_spec.rb | # frozen_string_literal: true
require 'rspec'
require 'jekyll/kuma_plugins/common/params'
# Assuming ParamsParser is mixed into a class for testing
class TestParser
include Jekyll::KumaPlugins::Common
end
RSpec.describe TestParser do
let(:parser) { TestParser.new }
let(:defaults) { { if_version: nil, init_value: 0, get_current: false } }
describe '#parse_name_and_params' do
context 'when name and parameters are provided' do
it 'parses name and parameters with default values' do
name, default_params, extra_params = parser.parse_name_and_params('my_var init_value=5 get_current=true',
defaults)
expect(name).to eq('my_var')
expect(default_params).to eq({ if_version: nil, init_value: 5, get_current: true })
expect(extra_params).to be_empty
end
it 'parses standalone keys as booleans if specified in defaults' do
name, default_params, extra_params = parser.parse_name_and_params('my_var get_current', defaults)
expect(name).to eq('my_var')
expect(default_params).to eq({ if_version: nil, init_value: 0, get_current: true })
expect(extra_params).to be_empty
end
it 'returns extra parameters separately' do
name, default_params, extra_params = parser.parse_name_and_params(
"my_var init_value=5 extra_param=10 another_param='hello'", defaults
)
expect(name).to eq('my_var')
expect(default_params).to eq({ if_version: nil, init_value: 5, get_current: false })
expect(extra_params).to eq({ extra_param: '10', another_param: 'hello' })
end
end
context 'when name is absent' do
it 'returns nil for name and parses parameters' do
name, default_params, extra_params = parser.parse_name_and_params('init_value=5 get_current=true', defaults)
expect(name).to be_nil
expect(default_params).to eq({ if_version: nil, init_value: 5, get_current: true })
expect(extra_params).to be_empty
end
end
context 'when default values are overridden' do
it 'maintains type enforcement for parameters' do
name, default_params, extra_params = parser.parse_name_and_params("my_var init_value='5' get_current=true",
defaults)
expect(name).to eq('my_var')
expect(default_params).to eq({ if_version: nil, init_value: 5, get_current: true })
expect(extra_params).to be_empty
end
end
context 'when parameters have incorrect types' do
it 'raises an error for incorrect integer type' do
expect do
parser.parse_name_and_params("my_var init_value='not_a_number'", defaults)
end.to raise_error(ArgumentError, 'Expected init_value to be a Integer, but got String')
end
it 'raises an error for incorrect boolean type' do
expect do
parser.parse_name_and_params("my_var get_current='not_a_boolean'", defaults)
end.to raise_error(ArgumentError,
"Invalid boolean value: expected 'true', 'false', or no value, but got 'not_a_boolean'.")
end
end
context 'when parameters are missing values' do
it 'raises an error for missing values' do
expect do
parser.parse_name_and_params('my_var init_value=', defaults)
end.to raise_error(ArgumentError, "Parameter 'init_value' is missing a value")
end
end
end
describe '#parse_params' do
it 'returns default params when no parameters provided' do
default_params, extra_params = parser.parse_params('', defaults)
expect(default_params).to eq(defaults)
expect(extra_params).to be_empty
end
it 'parses key-value pairs and maintains types' do
default_params, extra_params = parser.parse_params('init_value=5 get_current=true', defaults)
expect(default_params).to eq({ if_version: nil, init_value: 5, get_current: true })
expect(extra_params).to be_empty
end
it 'parses standalone boolean keys correctly' do
default_params, extra_params = parser.parse_params('get_current', defaults)
expect(default_params).to eq({ if_version: nil, init_value: 0, get_current: true })
expect(extra_params).to be_empty
end
it 'separates extra parameters not defined in defaults' do
default_params, extra_params = parser.parse_params("init_value=5 extra_param='hello'", defaults)
expect(default_params).to eq({ if_version: nil, init_value: 5, get_current: false })
expect(extra_params).to eq({ extra_param: 'hello' })
end
it 'raises an error when required parameter type is incorrect' do
expect do
parser.parse_params("init_value='string_instead_of_int'", defaults)
end.to raise_error(ArgumentError, 'Expected init_value to be a Integer, but got String')
end
it 'raises an error for parameters with empty values' do
expect do
parser.parse_params('get_current=', defaults)
end.to raise_error(ArgumentError, "Parameter 'get_current' is missing a value")
end
it 'raises an error for standalone keys not in defaults' do
expect do
parser.parse_params('unknown_key', defaults)
end.to raise_error(ArgumentError, "Parameter 'unknown_key' is missing a value")
end
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/spec/jekyll/kuma_plugins/liquid/tags/cpinstall_spec.rb | jekyll-kuma-plugins/spec/jekyll/kuma_plugins/liquid/tags/cpinstall_spec.rb | # frozen_string_literal: true
RSpec.describe Jekyll::KumaPlugins::Liquid::Tags::InstallCp do
subject do
described_class.parse('cpinstall', '', Liquid::Tokenizer.new("#{entry}{%endcpinstall%}"),
Liquid::ParseContext.new).render(Liquid::Context.new({
registers: {
site: {
config: {}
}
}
}))
end
context 'with nothing' do
let(:entry) { '' }
it 'is empty' do
expect(subject).to eq('')
end
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/spec/jekyll/kuma_plugins/liquid/tags/policyyaml_spec.rb | jekyll-kuma-plugins/spec/jekyll/kuma_plugins/liquid/tags/policyyaml_spec.rb | # frozen_string_literal: true
RSpec.describe Jekyll::KumaPlugins::Liquid::Tags::PolicyYaml do
subject do
described_class.parse('policy_yaml', '', Liquid::Tokenizer.new("#{entry}{%endpolicy_yaml%}"),
Liquid::ParseContext.new).render(Liquid::Context.new({
registers: {
site: {
config: {}
}
}
}))
end
context 'with nothing' do
let(:entry) { '' }
it 'is empty' do
expect(subject).to eq('')
end
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/spec/jekyll/kuma_plugins/liquid/tags/policyyaml/transformers_spec.rb | jekyll-kuma-plugins/spec/jekyll/kuma_plugins/liquid/tags/policyyaml/transformers_spec.rb | # frozen_string_literal: true
RSpec.describe Jekyll::KumaPlugins::Liquid::Tags::PolicyYamlTransformers do
describe Jekyll::KumaPlugins::Liquid::Tags::PolicyYamlTransformers::MeshServiceTargetRefTransformer do
subject { described_class.new }
describe '#matches?' do
it 'matches spec.to.targetRef with MeshService kind' do
expect(subject.matches?(%w[spec to targetRef], { 'kind' => 'MeshService' }, {})).to be true
end
it 'does not match wrong path' do
expect(subject.matches?(%w[spec from], { 'kind' => 'MeshService' }, {})).to be false
end
it 'does not match wrong kind' do
expect(subject.matches?(%w[spec to targetRef], { 'kind' => 'Mesh' }, {})).to be false
end
end
describe '#transform' do
let(:node) { { 'kind' => 'MeshService', 'name' => 'backend', 'namespace' => 'default', 'sectionName' => 'http' } }
context 'kubernetes legacy' do
let(:context) { { env: :kubernetes, legacy_output: true } }
it 'joins name parts with underscore' do
node_with_port = node.merge('_port' => '8080')
result = subject.transform(node_with_port, context)
expect(result['name']).to eq('backend_default_svc_8080')
end
end
context 'kubernetes modern' do
let(:context) { { env: :kubernetes, legacy_output: false } }
it 'keeps separate fields' do
result = subject.transform(node, context)
expect(result).to eq({
'kind' => 'MeshService',
'name' => 'backend',
'namespace' => 'default',
'sectionName' => 'http'
})
end
end
context 'universal legacy' do
let(:context) { { env: :universal, legacy_output: true } }
it 'returns only name' do
result = subject.transform(node, context)
expect(result).to eq({ 'kind' => 'MeshService', 'name' => 'backend' })
end
end
context 'universal modern' do
let(:context) { { env: :universal, legacy_output: false } }
it 'includes sectionName' do
result = subject.transform(node, context)
expect(result).to eq({
'kind' => 'MeshService',
'name' => 'backend',
'sectionName' => 'http'
})
end
end
end
end
describe Jekyll::KumaPlugins::Liquid::Tags::PolicyYamlTransformers::MeshServiceBackendRefTransformer do
subject { described_class.new }
describe '#matches?' do
it 'matches backendRefs path with MeshService' do
expect(subject.matches?(%w[spec to rules default backendRefs], { 'kind' => 'MeshService' }, {})).to be true
end
it 'matches requestMirror backendRef path' do
path = %w[spec to rules default filters requestMirror backendRef]
expect(subject.matches?(path, { 'kind' => 'MeshService' }, {})).to be true
end
it 'does not match wrong kind' do
expect(subject.matches?(%w[spec to rules default backendRefs], { 'kind' => 'Mesh' }, {})).to be false
end
end
describe '#transform' do
let(:node) { { 'kind' => 'MeshService', 'name' => 'backend', 'namespace' => 'default', 'port' => 8080 } }
context 'kubernetes legacy with version' do
let(:context) { { env: :kubernetes, legacy_output: true } }
it 'sets MeshServiceSubset kind and tags' do
node_with_version = node.merge('_version' => 'v1', 'weight' => 90)
result = subject.transform(node_with_version, context)
expect(result['kind']).to eq('MeshServiceSubset')
expect(result['tags']).to eq({ 'version' => 'v1' })
expect(result['weight']).to eq(90)
end
end
context 'kubernetes modern with version' do
let(:context) { { env: :kubernetes, legacy_output: false } }
it 'appends version to name' do
node_with_version = node.merge('_version' => 'v1')
result = subject.transform(node_with_version, context)
expect(result['name']).to eq('backend-v1')
end
end
context 'universal legacy' do
let(:context) { { env: :universal, legacy_output: true } }
it 'returns basic ref' do
result = subject.transform(node, context)
expect(result).to eq({ 'kind' => 'MeshService', 'name' => 'backend' })
end
end
context 'universal modern' do
let(:context) { { env: :universal, legacy_output: false } }
it 'includes port' do
result = subject.transform(node, context)
expect(result['port']).to eq(8080)
end
end
end
end
describe Jekyll::KumaPlugins::Liquid::Tags::PolicyYamlTransformers::NameTransformer do
subject { described_class.new }
describe '#matches?' do
it 'matches node with name_uni' do
expect(subject.matches?([], { 'name_uni' => 'test' }, {})).to be true
end
it 'matches node with name_kube' do
expect(subject.matches?([], { 'name_kube' => 'test' }, {})).to be true
end
it 'does not match node without name fields' do
expect(subject.matches?([], { 'name' => 'test' }, {})).to be false
end
it 'does not match non-hash' do
expect(subject.matches?([], 'string', {})).to be false
end
end
describe '#transform' do
let(:node) { { 'name_uni' => 'uni-name', 'name_kube' => 'kube-name', 'other' => 'value' } }
it 'uses name_kube for kubernetes' do
result = subject.transform(node, { env: :kubernetes })
expect(result['name']).to eq('kube-name')
expect(result).not_to have_key('name_uni')
expect(result).not_to have_key('name_kube')
end
it 'uses name_uni for universal' do
result = subject.transform(node, { env: :universal })
expect(result['name']).to eq('uni-name')
end
it 'preserves other fields' do
result = subject.transform(node, { env: :kubernetes })
expect(result['other']).to eq('value')
end
it 'does not mutate original node' do
original = node.dup
subject.transform(node, { env: :kubernetes })
expect(node).to eq(original)
end
end
end
describe Jekyll::KumaPlugins::Liquid::Tags::PolicyYamlTransformers::KubernetesRootTransformer do
subject { described_class.new('kuma.io/v1alpha1') }
describe '#matches?' do
it 'matches root path with kubernetes env' do
expect(subject.matches?([], {}, { env: :kubernetes })).to be true
end
it 'does not match non-root path' do
expect(subject.matches?(%w[spec], {}, { env: :kubernetes })).to be false
end
it 'does not match universal env' do
expect(subject.matches?([], {}, { env: :universal })).to be false
end
end
describe '#transform' do
let(:node) do
{
'type' => 'MeshTimeout',
'name' => 'my-timeout',
'mesh' => 'default',
'spec' => { 'targetRef' => {} }
}
end
let(:context) { { env: :kubernetes, namespace: 'kuma-system' } }
it 'creates kubernetes resource structure' do
result = subject.transform(node, context)
expect(result['apiVersion']).to eq('kuma.io/v1alpha1')
expect(result['kind']).to eq('MeshTimeout')
expect(result['metadata']['name']).to eq('my-timeout')
expect(result['metadata']['namespace']).to eq('kuma-system')
expect(result['spec']).to eq({ 'targetRef' => {} })
end
it 'adds mesh label' do
result = subject.transform(node, context)
expect(result['metadata']['labels']['kuma.io/mesh']).to eq('default')
end
it 'preserves existing labels' do
node_with_labels = node.merge('labels' => { 'app' => 'test' })
result = subject.transform(node_with_labels, context)
expect(result['metadata']['labels']['app']).to eq('test')
expect(result['metadata']['labels']['kuma.io/mesh']).to eq('default')
end
it 'does not mutate original labels' do
original_labels = { 'app' => 'test' }
node_with_labels = node.merge('labels' => original_labels)
subject.transform(node_with_labels, context)
expect(original_labels).not_to have_key('kuma.io/mesh')
end
it 'omits labels when neither labels nor mesh present' do
node_without_mesh = node.except('mesh')
result = subject.transform(node_without_mesh, context)
expect(result['metadata']).not_to have_key('labels')
end
end
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/lib/jekyll_kuma_plugins.rb | jekyll-kuma-plugins/lib/jekyll_kuma_plugins.rb | # frozen_string_literal: true
require 'jekyll'
require_relative 'jekyll/kuma_plugins'
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/lib/jekyll/kuma_plugins.rb | jekyll-kuma-plugins/lib/jekyll/kuma_plugins.rb | # frozen_string_literal: true
require_relative 'kuma_plugins/version'
require_relative 'kuma_plugins/liquid/tags/jsonschema'
require_relative 'kuma_plugins/liquid/tags/schema_viewer'
require_relative 'kuma_plugins/liquid/tags/embed'
require_relative 'kuma_plugins/liquid/tags/policyyaml'
require_relative 'kuma_plugins/liquid/tags/cpinstall'
require_relative 'kuma_plugins/liquid/tags/cpinstallfile'
require_relative 'kuma_plugins/liquid/tags/inc'
require_relative 'kuma_plugins/liquid/tags/rbacresources'
require_relative 'kuma_plugins/liquid/blocks/helmvalues'
require_relative 'kuma_plugins/generators/demourl'
# Load custom blocks from app/_plugins
require_relative '../../../app/_plugins/blocks/custom_block'
require_relative '../../../app/_plugins/blocks/mermaid'
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/lib/jekyll/kuma_plugins/version.rb | jekyll-kuma-plugins/lib/jekyll/kuma_plugins/version.rb | # frozen_string_literal: true
module Jekyll
module KumaPlugins
VERSION = '0.1.0'
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/lib/jekyll/kuma_plugins/generators/demourl.rb | jekyll-kuma-plugins/lib/jekyll/kuma_plugins/generators/demourl.rb | # frozen_string_literal: true
module Jekyll
module KumaPlugins
class Generator < Jekyll::Generator
priority :lowest
def generate(site)
demo_version = site.config.fetch('mesh_demo_version', 'main')
site.pages.each do |page|
page.content = page.content.gsub('kuma-demo://', "https://raw.githubusercontent.com/kumahq/kuma-counter-demo/refs/heads/#{demo_version}/")
end
end
end
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/lib/jekyll/kuma_plugins/common/path_helpers.rb | jekyll-kuma-plugins/lib/jekyll/kuma_plugins/common/path_helpers.rb | # frozen_string_literal: true
module Jekyll
module KumaPlugins
module Common
module PathHelpers
PATHS_CONFIG = 'mesh_raw_generated_paths'
DEFAULT_PATHS = ['app/assets'].freeze
def read_file(paths, file_name)
paths.each do |path|
file_path = File.join(path, file_name)
return File.open(file_path) if File.readable? file_path
end
raise "couldn't read #{file_name} in any of these paths: #{paths}"
end
end
end
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/lib/jekyll/kuma_plugins/common/params.rb | jekyll-kuma-plugins/lib/jekyll/kuma_plugins/common/params.rb | # frozen_string_literal: true
module Jekyll
module KumaPlugins
module Common
# Regex to capture key-value pairs, standalone keys, and parameters with missing values
PARAM_REGEX = /(\w+)=((["'])(.*?)\3|\S+)?|(\w+)/
def parse_name_and_params(markup, default = {})
# Ensure default_params keys are symbols
default = default.transform_keys(&:to_sym)
# Extract name and raw parameters, treating first word as name
name, raw_params = markup.strip.split(' ', 2)
# Set name to nil if it looks like a parameter or matches a default_params key
name = nil if name&.include?('=') || default.key?(name.to_sym)
# Parse parameters, treating entire markup as raw_params if name is nil
params, extra_params = parse_params(name ? raw_params : markup.strip, default)
[name, params, extra_params]
end
def parse_params(raw_params, default_params = {})
return [default_params, {}] if raw_params.nil? || raw_params.empty?
params = default_params.dup
extra_params = {}
raw_params.scan(PARAM_REGEX).each do |match|
process_param_match(match, params, extra_params, default_params)
end
[params, extra_params]
end
private
def process_param_match(match, params, extra_params, default_params)
key, full_value, quote, inner_value, standalone_key = match
key = key&.to_sym || standalone_key&.to_sym
value = quote ? inner_value : full_value
return handle_standalone_key(standalone_key.to_sym, params, default_params) if standalone_key
handle_key_with_value(key, value, params, extra_params, default_params)
end
def handle_standalone_key(key, params, default_params)
return params[key] = true if boolean_key?(key, default_params)
return params[key] = default_params.fetch(key, true) if default_params.key?(key)
raise ArgumentError, "Parameter '#{key}' is missing a value"
end
def handle_key_with_value(key, value, params, extra_params, default_params)
raise ArgumentError, "Parameter '#{key}' is missing a value" if value.nil?
return extra_params[key] = value unless default_params.key?(key)
params[key] = enforce_type(key, value, default_params[key])
end
def boolean_key?(key, default)
[TrueClass, FalseClass].include?(default[key].class)
end
def enforce_type(key, value, expected)
return Integer(value) if expected.is_a?(Integer)
return value.to_s.empty? ? expected : convert_to_boolean(value) if [TrueClass,
FalseClass].include?(expected.class)
value
rescue ArgumentError, TypeError
if expected.is_a?(Integer)
raise ArgumentError,
"Expected #{key} to be a #{expected.class}, but got #{value.class}"
end
raise
end
def convert_to_boolean(value)
case value.to_s.downcase
when 'true' then true
when 'false' then false
else
raise ArgumentError, "Invalid boolean value: expected 'true', 'false', or no value, but got '#{value}'."
end
end
end
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/blocks/helmvalues.rb | jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/blocks/helmvalues.rb | # frozen_string_literal: true
# This plugin generates a code block with YAML for Helm's values.yaml file,
# nesting the YAML content under the specified prefix path.
# For example, if the prefix path is "foo.bar.baz" and the YAML content is:
# ```yaml
# a:
# b:
# c: [d,e,f]
# ```
# The output will be:
# ```yaml
# foo:
# bar:
# baz:
# a:
# b:
# c: [d,e,f]
# ```
require 'yaml'
module Jekyll
module KumaPlugins
module Liquid
module Blocks
class HelmValues < ::Liquid::Block
def initialize(tag_name, markup, options)
super
@prefix = markup.strip
end
def render(context)
content = super
return '' if content.empty?
site = context.registers[:site]
site_prefix = site.config['set_flag_values_prefix']
prefix = (@prefix.empty? ? site_prefix : @prefix).strip.gsub(/^\.+|\.+$/, '')
::Liquid::Template.parse(render_yaml(prefix, content)).render(context)
end
private
def render_yaml(prefix, content)
yaml_raw = content.gsub(/```yaml\n|```/, '')
yaml_data = YAML.load_stream(yaml_raw).first
prefix.split('.').reverse_each { |part| yaml_data = { part => yaml_data } } unless prefix.empty?
<<~MARKDOWN
```yaml
#{YAML.dump(yaml_data).gsub(/^---\n/, '').chomp}
```
MARKDOWN
end
end
end
end
end
end
Liquid::Template.register_tag('helmvalues', Jekyll::KumaPlugins::Liquid::Blocks::HelmValues)
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/schema_viewer.rb | jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/schema_viewer.rb | # frozen_string_literal: true
require 'json'
require 'yaml'
require 'cgi'
require_relative '../../common/path_helpers'
require_relative 'schema_viewer/renderer'
module Jekyll
module KumaPlugins
module Liquid
module Tags
# Renders JSON schema as interactive HTML viewer
class SchemaViewer < ::Liquid::Tag
include Jekyll::KumaPlugins::Common::PathHelpers
TYPE_BADGES = %w[string boolean integer number object array enum].freeze
def initialize(tag_name, markup, options)
super
name, *params_list = @markup.split
params = { 'type' => 'policy' }
@filters = {}
@excluded_fields = []
@path_exclusions = {}
parse_parameters(params_list, params)
@load = create_loader(params['type'], name)
end
def render(context)
release = context.registers[:page]['release']
base_paths = context.registers[:site].config.fetch(PATHS_CONFIG, DEFAULT_PATHS)
data = @load.call(base_paths, release)
SchemaViewerComponents::Renderer.new(data, @filters, @excluded_fields, @path_exclusions).render
rescue StandardError => e
Jekyll.logger.warn('Failed reading schema_viewer', e)
"<div class='schema-viewer-error'>Error loading schema: #{CGI.escapeHTML(e.message)}</div>"
end
private
def parse_parameters(params_list, params)
params_list.each do |item|
key, value = item.split('=', 2)
next if value.to_s.empty?
handle_parameter(key, value, params)
end
end
def handle_parameter(key, value, params)
values = value.split(',').map(&:strip)
if key == 'exclude'
@excluded_fields = values
elsif key.start_with?('exclude.')
@path_exclusions[key.sub('exclude.', '')] = values
elsif key.include?('.')
@filters[key] = values
else
params[key] = value
end
end
def create_loader(type, name)
case type
when 'proto' then proto_loader(name)
when 'crd' then crd_loader(name)
when 'policy' then policy_loader(name)
else
raise "Invalid type: #{type}"
end
end
def proto_loader(name)
lambda do |paths, release|
JSON.parse(read_file(paths, File.join(release.to_s, 'raw', 'protos', "#{name}.json")).read)
end
end
def crd_loader(name)
lambda do |paths, release|
d = YAML.safe_load(read_file(paths, File.join(release.to_s, 'raw', 'crds', "#{name}.yaml")).read)
d['spec']['versions'][0]['schema']['openAPIV3Schema']
end
end
def policy_loader(name)
lambda do |paths, release|
d = YAML.safe_load(read_file(paths, File.join(release.to_s, 'raw', 'crds', "kuma.io_#{name.downcase}.yaml")).read)
d['spec']['versions'][0]['schema']['openAPIV3Schema']['properties']['spec']
end
end
end
end
end
end
end
Liquid::Template.register_tag('schema_viewer', Jekyll::KumaPlugins::Liquid::Tags::SchemaViewer)
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/cpinstall.rb | jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/cpinstall.rb | # frozen_string_literal: true
# This plugin adds key values to install and generates 2 tabs for helm and kumactl.
# It removes duplication of examples for both universal and kubernetes environments.
require 'yaml'
module Jekyll
module KumaPlugins
module Liquid
module Tags
class InstallCp < ::Liquid::Block
def initialize(tag_name, tabs_name, options)
super
@tabs_name = tabs_name
_, *params_list = @markup.split
params = { 'prefixed' => 'true' }
params_list.each do |item|
sp = item.split('=')
params[sp[0]] = sp[1] unless sp[1] == ''
end
@prefixed = params['prefixed'].downcase == 'true'
end
def render(context)
content = super
return '' if content.empty?
site_data = context.registers[:site].config
page = context.environments.first['page']
helm_flags = process_helm_flags(content, site_data)
html_content = generate_install_tabs(helm_flags, page)
::Liquid::Template.parse(html_content).render(context)
end
private
def process_helm_flags(content, site_data)
opts = content.strip.split("\n").map do |line|
line = site_data['set_flag_values_prefix'] + line if @prefixed
"--set \"#{line}\""
end
opts.join(" \\\n ")
end
def generate_install_tabs(helm_flags, page)
<<~LIQUID
{% tabs codeblock %}
{% tab kumactl %}
```shell
kumactl install control-plane \\
#{helm_flags} \\
| kubectl apply -f -
```
{:.no-line-numbers}
{% endtab %}
{% tab Helm %}
```shell
# Before installing {{ site.mesh_product_name }} with Helm, configure your local Helm repository:
# {{ site.links.web }}/#{product_url_segment(page)}/{{ page.release }}/production/cp-deployment/kubernetes/#helm
helm install \\
--create-namespace \\
--namespace {{ site.mesh_namespace }} \\
#{helm_flags} \\
{{ site.mesh_helm_install_name }} {{ site.mesh_helm_repo }}
```
{:.no-line-numbers}
{% endtab %}
{% endtabs %}
LIQUID
end
def product_url_segment(page)
page['dir'].split('/')[1]
end
end
end
end
end
end
Liquid::Template.register_tag('cpinstall', Jekyll::KumaPlugins::Liquid::Tags::InstallCp)
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/inc.rb | jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/inc.rb | # frozen_string_literal: true
require_relative '../../common/params'
module Jekyll
module KumaPlugins
module Liquid
module Tags
class Inc < ::Liquid::Tag
include Jekyll::KumaPlugins::Common
def initialize(_tag_name, markup, _parse_context)
super
# Parse parameters, separating recognized defaults and extras
default_params = { if_version: nil, init_value: 0, get_current: false }
@name, @params, @extra_params = parse_name_and_params(markup, default_params)
raise ArgumentError, "The 'inc' tag requires a variable name to increment" if @name.nil?
end
def render(context)
page = context.registers[:page]
# Ensure nested hash structure exists
increment_data = page[:plugins] ||= {}
increment_data = increment_data[:increment] ||= {}
# Set initial value if not already present
increment_data[@name] ||= @params[:init_value]
# Return current value without incrementing if `get_current` is true
return increment_data[@name] if @params[:get_current]
# Increment only if should_increment? condition is met
increment_data[@name] += 1 if should_increment?(context)
increment_data[@name]
end
private
def should_increment?(context)
!@params[:if_version] || render_template(context) == 'true'
end
def version_check_template
"{% if_version #{@params[:if_version]} %}true{% endif_version %}"
end
def render_template(context)
::Liquid::Template.parse(version_check_template).render(context).strip
rescue ::Liquid::SyntaxError
log_version_check_error(context)
''
end
def log_version_check_error(context)
page_path = context.registers[:page]['path']
Jekyll.logger.error(
'Increment Tag Warning:',
"The 'if_version' condition could not be evaluated in #{page_path}. " \
"Ensure the 'if_version' plugin is installed."
)
end
end
end
end
end
end
Liquid::Template.register_tag('inc', Jekyll::KumaPlugins::Liquid::Tags::Inc)
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/cpinstallfile.rb | jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/cpinstallfile.rb | # frozen_string_literal: true
# This plugin simplifies installation documentation by generating tabs for `kumactl`
# and Helm commands, using a set of customizable parameters. It reduces the need for
# duplicate installation examples across Universal and Kubernetes environments.
# The plugin requires a tabs name to be provided, otherwise it will raise an error.
require 'yaml'
module Jekyll
module KumaPlugins
module Liquid
module Tags
class CpInstallFile < ::Liquid::Tag
def initialize(tag_name, text, tokens)
super
@tabs_name, *params_list = @markup.split
@params = { 'filename' => 'values.yaml' }
raise ArgumentError, 'You must provide a valid tabs name for the cpinstallfile tag.' if @tabs_name.nil? || @tabs_name.strip.empty?
params_list.each do |item|
key, value = item.split('=')
@params[key] = value.strip.gsub(/^"+|"+$/, '') if value && !value.empty?
end
end
def render(context)
::Liquid::Template.parse(generate_install_tabs).render(context)
end
private
def generate_install_tabs
filename = @params['filename']
<<~LIQUID
{% tabs %}
#{kumactl_tab(filename)}
#{helm_tab(filename)}
{% endtabs %}
LIQUID
end
def kumactl_tab(filename)
<<~LIQUID.chomp
{% tab kumactl %}
```sh
kumactl install control-plane --values #{filename} | kubectl apply -f -
```
{% endtab %}
LIQUID
end
def helm_tab(filename)
<<~LIQUID.chomp
{% tab Helm %}
Before using {{site.mesh_product_name}} with Helm, ensure that you've followed [these steps](/docs/{{ page.release }}/production/cp-deployment/kubernetes/#helm) to configure your local Helm repository.
```sh
helm install \\
--create-namespace \\
--namespace {{site.mesh_namespace}} \\
--values #{filename} \\
{{site.mesh_helm_install_name}} {{site.mesh_helm_repo}}
```
{% endtab %}
LIQUID
end
end
end
end
end
end
Liquid::Template.register_tag('cpinstallfile', Jekyll::KumaPlugins::Liquid::Tags::CpInstallFile)
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/policyyaml.rb | jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/policyyaml.rb | # frozen_string_literal: true
# This plugins lets us to write the policy YAML only once.
# It removes duplication of examples for both universal and kubernetes environments.
# The expected format is universal. It only works for policies V2 with a `spec` blocks.
require 'yaml'
require 'rubygems' # Required for Gem::Version
require_relative 'policyyaml/transformers'
require_relative 'policyyaml/terraform_generator'
require_relative 'policyyaml/tab_generator'
module Jekyll
module KumaPlugins
module Liquid
module Tags
class PolicyYaml < ::Liquid::Block
TARGET_VERSION = Gem::Version.new('2.9.0')
TF_TARGET_VERSION = Gem::Version.new('2.10.0')
def initialize(tag_name, markup, options)
super
@params = { 'raw' => false, 'apiVersion' => 'kuma.io/v1alpha1', 'use_meshservice' => 'false' }
parse_markup(markup)
register_default_transformers
end
def deep_copy(original)
Marshal.load(Marshal.dump(original))
end
def process_node(node, context, path = [])
if node.is_a?(Hash)
@transformers.each do |transformer|
node = transformer.transform(node, context) if transformer.matches?(path, node, context)
end
node = node.transform_values.with_index { |v, k| process_node(v, context, path + [node.keys[k]]) }
elsif node.is_a?(Array)
node = node.map { |v| process_node(v, context, path) }
end
node
end
def snake_case(str)
str.gsub(/([a-z])([A-Z])/, '\1_\2').gsub(/([A-Z])([A-Z][a-z])/, '\1_\2').downcase
end
def render(context)
content = super
return '' if content == ''
render_context = build_render_context(context, content)
contents, terraform_content = process_yaml_content(render_context)
html = TabGenerator.new.generate(render_context, contents, terraform_content)
::Liquid::Template.parse(html).render(context)
end
private
def parse_markup(markup)
markup.strip.split.each do |item|
sp = item.split('=')
@params[sp[0]] = sp[1] unless sp[1] == ''
end
end
def register_default_transformers
@transformers = [
PolicyYamlTransformers::MeshServiceTargetRefTransformer.new,
PolicyYamlTransformers::MeshServiceBackendRefTransformer.new,
PolicyYamlTransformers::NameTransformer.new,
PolicyYamlTransformers::KubernetesRootTransformer.new(@params['apiVersion'])
]
end
def build_render_context(context, content)
has_raw = @body.nodelist.first { |x| x.has?('tag_name') and x.tag_name == 'raw' }
release = context.registers[:page]['release']
site_data = context.registers[:site].config
version = Gem::Version.new(release.value.dup.sub('x', '0'))
{
has_raw: has_raw,
release: release,
site_data: site_data,
version: version,
use_meshservice: @params['use_meshservice'] == 'true' && version >= TARGET_VERSION,
show_tf: version >= TF_TARGET_VERSION,
namespace: @params['namespace'] || site_data['mesh_namespace'],
content: content.gsub(/`{3}yaml\n/, '').gsub(/`{3}/, ''),
edition: context.registers[:page]['edition']
}
end
def process_yaml_content(render_context)
styles = build_styles(render_context[:namespace])
contents = styles.to_h { |style| [style[:name], ''] }
terraform_content = ''
terraform_generator = TerraformGenerator.new
YAML.load_stream(render_context[:content]) do |yaml_data|
styles.each do |style|
processed_data = process_node(deep_copy(yaml_data), style)
contents[style[:name]] += "\n---\n" unless contents[style[:name]] == ''
contents[style[:name]] += YAML.dump(processed_data).gsub(/^---\n/, '').chomp
terraform_content += terraform_generator.generate(processed_data) if style[:name] == :uni
end
end
contents = wrap_yaml_contents(contents, render_context[:has_raw])
terraform_content = wrap_terraform_content(terraform_content, render_context[:has_raw])
[contents, terraform_content]
end
def build_styles(namespace)
[
{ name: :uni_legacy, env: :universal, legacy_output: true },
{ name: :uni, env: :universal, legacy_output: false },
{ name: :kube_legacy, env: :kubernetes, legacy_output: true, namespace: namespace },
{ name: :kube, env: :kubernetes, legacy_output: false, namespace: namespace }
]
end
def wrap_yaml_contents(contents, has_raw)
contents.transform_values { |c| wrap_content(c, 'yaml', has_raw) }
end
def wrap_terraform_content(content, has_raw)
wrap_content(content, 'hcl', has_raw)
end
def wrap_content(content, lang, has_raw)
wrapped = "```#{lang}\n#{content}\n```\n"
has_raw ? "{% raw %}\n#{wrapped}{% endraw %}\n" : wrapped
end
end
end
end
end
end
Liquid::Template.register_tag('policy_yaml', Jekyll::KumaPlugins::Liquid::Tags::PolicyYaml)
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/embed.rb | jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/embed.rb | # frozen_string_literal: true
require_relative '../../common/path_helpers'
module Jekyll
module KumaPlugins
module Liquid
module Tags
class Embed < ::Liquid::Tag
include Jekyll::KumaPlugins::Common::PathHelpers
def initialize(tag_name, markup, options)
super
params = {}
@file, *params_list = @markup.split
params_list.each do |item|
sp = item.split('=')
params[sp[0]] = sp[1]
end
@versioned = params.key?('versioned')
end
def render(context)
site_config = context.registers[:site].config
release = context.registers[:page]['release']
read_and_filter_content(site_config, release)
rescue StandardError => e
Jekyll.logger.warn('Failed reading raw file', e)
nil
end
private
def read_and_filter_content(site_config, release)
file_path = resolve_embed_path(release)
base_paths = site_config.fetch(PATHS_CONFIG, DEFAULT_PATHS)
content = read_file(base_paths, file_path).read
apply_link_filter(content, site_config)
end
def resolve_embed_path(release)
version_prefix = @versioned ? release : ''
File.join(version_prefix, 'raw', @file)
end
def apply_link_filter(content, site_config)
ignored_links = site_config.fetch('mesh_ignored_links_regex', [])
ignored_links.each { |re| content = content.gsub(Regexp.new(re), '') }
content
end
end
end
end
end
end
Liquid::Template.register_tag('embed', Jekyll::KumaPlugins::Liquid::Tags::Embed)
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/rbacresources.rb | jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/rbacresources.rb | # frozen_string_literal: true
# This plugin generates tabbed tables for RBAC resources (ClusterRole, ClusterRoleBinding,
# Role, RoleBinding) from a given YAML file. Each tab corresponds to a resource kind,
# and each resource is shown in a nested tab with its name and YAML content.
#
# When no `filename` is provided, the plugin uses `rbac.yaml` by default.
# The plugin looks for the file using the following logic:
#
# 1. It reads the current release from `page.release`.
# 2. It looks for the file in each path configured in `mesh_raw_generated_paths`
# in the site's `_config.yml`. If not set, it defaults to: ['app/assets'].
# 3. For each base path, it checks if the file exists at:
# {{ base_path }}/{{ release }}/raw/{{ filename }}
# 4. If not found, it falls back to checking if the provided filename is an absolute or relative path.
# 5. If still not found, the plugin raises an error.
#
# Usage examples:
# {% rbacresources %} # uses default filename `rbac.yaml`
# {% rbacresources filename=custom-rbac.yaml %} # uses a custom filename
require 'yaml'
module Jekyll
module KumaPlugins
module Liquid
module Tags
class RbacResources < ::Liquid::Tag
PATHS_CONFIG = 'mesh_raw_generated_paths'
DEFAULT_PATHS = ['app/assets'].freeze
DEFAULT_FILENAME = 'rbac.yaml'
def initialize(tag_name, text, tokens)
super
@markup = text.strip
@params = { 'filename' => DEFAULT_FILENAME }
@markup.split.each do |item|
key, value = item.split('=')
@params[key] = value.strip.gsub(/^"+|"+$/, '') if key && value
end
end
RBAC_KINDS = %w[ClusterRole ClusterRoleBinding Role RoleBinding].freeze
def render(context)
filename = resolve_file_path(context)
yaml_content = YAML.load_stream(File.read(filename))
grouped = filter_rbac_resources(yaml_content)
tab_output = grouped.map { |kind, docs| generate_kind_tab(kind, docs) }.join("\n")
::Liquid::Template.parse(<<~MARKDOWN).render(context)
{% tabs %}
#{tab_output}
{% endtabs %}
MARKDOWN
end
private
def filter_rbac_resources(yaml_content)
yaml_content
.select { |doc| doc.is_a?(Hash) && RBAC_KINDS.include?(doc['kind']) }
.group_by { |doc| doc['kind'] }
end
def generate_kind_tab(kind, docs)
subtabs = docs.map { |doc| generate_resource_subtab(kind, doc) }.join("\n")
<<~TAB
{% tab #{kind} %}
{% tabs codeblock %}
#{subtabs}
{% endtabs %}
{% endtab %}
TAB
end
def generate_resource_subtab(kind, doc)
name = doc.dig('metadata', 'name')
raise ArgumentError, "RBAC resource of kind '#{kind}' is missing a non-empty metadata.name" if name.nil? || name.strip.empty?
yaml = YAML.dump(doc).lines.reject { |line| line.strip == '---' }.join.strip
<<~SUBTAB
{% tab #{name} %}
```yaml
#{yaml}
```
{:.no-line-numbers}
{% endtab %}
SUBTAB
end
def resolve_file_path(context)
site_config = context.registers[:site].config
page_data = context.registers[:page]
release = page_data['release'].to_s.strip
base_paths = site_config.fetch(PATHS_CONFIG, DEFAULT_PATHS)
base_paths.each do |base_path|
candidate = File.join(base_path, release, 'raw', @params['filename'])
return candidate if File.exist?(candidate)
end
fallback = @params['filename']
return fallback if File.exist?(fallback)
raise ArgumentError,
"File not found: #{@params['filename']} (searched in configured paths and as absolute path)"
end
end
end
end
end
end
Liquid::Template.register_tag('rbacresources', Jekyll::KumaPlugins::Liquid::Tags::RbacResources)
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/jsonschema.rb | jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/jsonschema.rb | # frozen_string_literal: true
require 'json'
require 'yaml'
require_relative '../../common/path_helpers'
module Jekyll
module KumaPlugins
module Liquid
module Tags
class JsonSchema < ::Liquid::Tag
include Jekyll::KumaPlugins::Common::PathHelpers
def initialize(tag_name, markup, options)
super
name, *params_list = @markup.split
params = { 'type' => 'policy' }
params_list.each do |item|
sp = item.split('=')
params[sp[0]] = sp[1] unless sp[1] == ''
end
@load = create_loader(params['type'], name)
end
def render(context)
release = context.registers[:page]['release']
base_paths = context.registers[:site].config.fetch(PATHS_CONFIG, DEFAULT_PATHS)
begin
data = @load.call(base_paths, release)
<<~TIP
<div id="markdown_html"></div>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.9.0/showdown.min.js"></script>
<script defer src="https://brianwendt.github.io/json-schema-md-doc/json-schema-md-doc.min.js"></script>
<script type="text/javascript">
const data = #{JSON.dump(data)};
document.addEventListener("DOMContentLoaded", function() {
function removeNewlinesFromDescriptions(obj) {
for (const key in obj) {
if (typeof obj[key] === 'object') {
// Recursively process nested objects
removeNewlinesFromDescriptions(obj[key]);
} else if (key === 'description' && typeof obj[key] === 'string') {
// Replace newlines in description values
obj[key] = obj[key].replace(/\\n/g, '');
}
}
}
// create an instance of JSONSchemaMarkdown
const Doccer = new JSONSchemaMarkdownDoc();
// don't include the path of the field in the output
Doccer.writePath = function() {};
// remove new lines in description
removeNewlinesFromDescriptions(data)
Doccer.load(data);
const converter = new showdown.Converter();
// use the converter to make html from the markdown
document.getElementById("markdown_html").innerHTML = converter.makeHtml(Doccer.generate());
});
</script>
TIP
rescue StandardError => e
Jekyll.logger.warn('Failed reading jsonschema', e)
nil
end
end
private
def create_loader(type, name)
case type
when 'proto' then proto_loader(name)
when 'crd' then crd_loader(name)
when 'policy' then policy_loader(name)
else
raise "Invalid type: #{type}"
end
end
def proto_loader(name)
lambda do |paths, release|
JSON.parse(read_file(paths, File.join(release.to_s, 'raw', 'protos', "#{name}.json")).read)
end
end
def crd_loader(name)
lambda do |paths, release|
d = YAML.safe_load(read_file(paths, File.join(release.to_s, 'raw', 'crds', "#{name}.yaml")).read)
d['spec']['versions'][0]['schema']['openAPIV3Schema']
end
end
def policy_loader(name)
lambda do |paths, release|
d = YAML.safe_load(read_file(paths, File.join(release.to_s, 'raw', 'crds', "kuma.io_#{name.downcase}.yaml")).read)
d['spec']['versions'][0]['schema']['openAPIV3Schema']['properties']['spec']
end
end
end
end
end
end
end
Liquid::Template.register_tag('json_schema', Jekyll::KumaPlugins::Liquid::Tags::JsonSchema)
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/policyyaml/terraform_generator.rb | jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/policyyaml/terraform_generator.rb | # frozen_string_literal: true
module Jekyll
module KumaPlugins
module Liquid
module Tags
# Generates Terraform HCL from YAML policy data
class TerraformGenerator
def generate(yaml_data)
type = yaml_data['type']
name = yaml_data['name']
resource_name = "konnect_#{snake_case(type)}"
build_resource(resource_name, name, yaml_data)
end
private
def build_resource(resource_name, name, yaml_data)
terraform = "resource \"#{resource_name}\" \"#{name.gsub('-', '_')}\" {\n"
terraform += resource_prefix
yaml_data.each do |key, value|
next if key == 'mesh'
terraform += convert_value(key, value, 1)
end
terraform += resource_suffix
terraform += "}\n"
terraform
end
def resource_prefix
<<-HEREDOC
provider = konnect-beta
HEREDOC
end
def resource_suffix
<<-HEREDOC
labels = {
"kuma.io/mesh" = konnect_mesh.my_mesh.name
}
cp_id = konnect_mesh_control_plane.my_meshcontrolplane.id
mesh = konnect_mesh.my_mesh.name
HEREDOC
end
def convert_value(key, value, indent_level, is_in_array: false, is_last: false)
key = snake_case(key) unless key.nil? || key.empty?
case value
when Hash
convert_hash(key, value, indent_level, is_in_array, is_last)
when Array
convert_array(key, value, indent_level, is_in_array, is_last)
else
convert_scalar(key, value, indent_level, is_in_array, is_last)
end
end
def convert_hash(key, value, indent_level, is_in_array, is_last)
indent = ' ' * indent_level
result = is_in_array ? "#{indent}{\n" : "#{indent}#{key} = {\n"
value.each_with_index do |(k, v), index|
result += convert_value(k, v, indent_level + 1, is_last: index == value.size - 1)
end
result += "#{indent}}#{trailing_comma(is_in_array, is_last)}\n"
end
def convert_array(key, value, indent_level, is_in_array, is_last)
indent = ' ' * indent_level
result = "#{indent}#{key} = [\n"
value.each_with_index do |v, index|
is_last_item = index == value.size - 1
result += convert_value('', v, indent_level + 1, is_in_array: true, is_last: is_last_item)
end
result += "#{indent}]#{trailing_comma(is_in_array, is_last)}\n"
end
def convert_scalar(key, value, indent_level, is_in_array, is_last)
indent = ' ' * indent_level
formatted_value = format_scalar_value(value)
"#{indent}#{key} = #{formatted_value}#{trailing_comma(is_in_array, is_last)}\n"
end
def format_scalar_value(value)
case value
when TrueClass, FalseClass, Integer, Float
value.to_s
else
"\"#{value}\""
end
end
def trailing_comma(is_in_array, is_last)
is_in_array && !is_last ? ',' : ''
end
def snake_case(str)
str.gsub(/([a-z])([A-Z])/, '\1_\2').gsub(/([A-Z])([A-Z][a-z])/, '\1_\2').downcase
end
end
end
end
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/policyyaml/transformers.rb | jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/policyyaml/transformers.rb | # frozen_string_literal: true
module Jekyll
module KumaPlugins
module Liquid
module Tags
module PolicyYamlTransformers
# Base class for YAML node transformers
class BaseTransformer
def matches?(_path, _node, _context)
raise NotImplementedError, 'Subclasses must implement #matches?'
end
def transform(_node, _context)
raise NotImplementedError, 'Subclasses must implement #transform'
end
private
def deep_copy(original)
Marshal.load(Marshal.dump(original))
end
end
# Transforms MeshService targetRef in spec.to.targetRef
class MeshServiceTargetRefTransformer < BaseTransformer
def matches?(path, node, _context)
path == %w[spec to targetRef] && node['kind'] == 'MeshService'
end
def transform(node, context)
case context[:env]
when :kubernetes
transform_kubernetes(node, context)
when :universal
transform_universal(node, context)
end
end
private
def transform_kubernetes(node, context)
if context[:legacy_output]
{
'kind' => 'MeshService',
'name' => [node['name'], node['namespace'], 'svc', node['_port']].compact.join('_')
}
else
{
'kind' => 'MeshService',
'name' => node['name'],
'namespace' => node['namespace'],
'sectionName' => node['sectionName']
}
end
end
def transform_universal(node, context)
if context[:legacy_output]
{
'kind' => 'MeshService',
'name' => node['name']
}
else
{
'kind' => 'MeshService',
'name' => node['name'],
'sectionName' => node['sectionName']
}
end
end
end
# Transforms MeshService backendRef in rules
class MeshServiceBackendRefTransformer < BaseTransformer
MATCHING_PATHS = [
%w[spec to rules default backendRefs],
%w[spec to rules default filters requestMirror backendRef]
].freeze
def matches?(path, node, _context)
MATCHING_PATHS.include?(path) && node['kind'] == 'MeshService'
end
def transform(node, context)
case context[:env]
when :kubernetes
transform_kubernetes(node, context)
when :universal
transform_universal(node, context)
end
end
private
def transform_kubernetes(node, context)
if context[:legacy_output]
build_legacy_kubernetes_ref(node)
else
build_modern_kubernetes_ref(node)
end
end
def build_legacy_kubernetes_ref(node)
{
'kind' => 'MeshService',
'name' => [node['name'], node['namespace'], 'svc', node['port']].compact.join('_')
}.tap do |hash|
hash['kind'] = 'MeshServiceSubset' if node.key?('_version')
hash['weight'] = node['weight'] if node.key?('weight')
hash['tags'] = { 'version' => node['_version'] } if node.key?('_version')
end
end
def build_modern_kubernetes_ref(node)
{
'kind' => 'MeshService',
'name' => node['name'],
'namespace' => node['namespace'],
'port' => node['port']
}.tap do |hash|
hash['weight'] = node['weight'] if node.key?('weight')
hash['name'] = "#{node['name']}-#{node['_version']}" if node.key?('_version')
end
end
def transform_universal(node, context)
if context[:legacy_output]
build_legacy_universal_ref(node)
else
build_modern_universal_ref(node)
end
end
def build_legacy_universal_ref(node)
{
'kind' => 'MeshService',
'name' => node['name']
}.tap do |hash|
hash['kind'] = 'MeshServiceSubset' if node.key?('_version')
hash['weight'] = node['weight'] if node.key?('weight')
hash['tags'] = { 'version' => node['_version'] } if node.key?('_version')
end
end
def build_modern_universal_ref(node)
{
'kind' => 'MeshService',
'name' => node['name'],
'port' => node['port']
}.tap do |hash|
hash['weight'] = node['weight'] if node.key?('weight')
hash['name'] = "#{node['name']}-#{node['_version']}" if node.key?('_version')
end
end
end
# Transforms nodes with name_uni/name_kube fields
class NameTransformer < BaseTransformer
def matches?(_path, node, _context)
node.is_a?(Hash) && (node.key?('name_uni') || node.key?('name_kube'))
end
def transform(node, context)
node_copy = deep_copy(node)
node_copy.delete('name_uni')
node_copy.delete('name_kube')
case context[:env]
when :kubernetes
node_copy['name'] = node['name_kube']
when :universal
node_copy['name'] = node['name_uni']
end
node_copy
end
end
# Transforms root node for Kubernetes format
class KubernetesRootTransformer < BaseTransformer
def initialize(api_version)
super()
@api_version = api_version
end
def matches?(path, _node, context)
path == [] && context[:env] == :kubernetes
end
def transform(node, context)
{
'apiVersion' => @api_version,
'kind' => node['type'],
'metadata' => build_metadata(node, context),
'spec' => node['spec']
}
end
private
def build_metadata(node, context)
metadata = {
'name' => node['name'],
'namespace' => context[:namespace]
}
metadata['labels'] = build_labels(node) if node['labels'] || node['mesh']
metadata
end
def build_labels(node)
labels = (node['labels'] || {}).dup
labels['kuma.io/mesh'] = node['mesh'] if node['mesh']
labels
end
end
end
end
end
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/policyyaml/tab_generator.rb | jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/policyyaml/tab_generator.rb | # frozen_string_literal: true
module Jekyll
module KumaPlugins
module Liquid
module Tags
# Generates HTML tabs for policy YAML display
class TabGenerator
def generate(render_context, contents, terraform_content)
docs_path = build_docs_path(render_context)
additional_classes = 'codeblock' unless render_context[:use_meshservice]
html = "{% tabs #{additional_classes} %}"
html += kubernetes_tab(contents, render_context, docs_path)
html += universal_tab(contents, render_context, docs_path)
html += terraform_tab(terraform_content, render_context)
html += '{% endtabs %}'
html
end
private
def build_docs_path(render_context)
version_path = render_context[:release].value
version_path = 'dev' if render_context[:release].label == 'dev'
edition = render_context[:edition]
docs_path = "/#{edition}/#{version_path}"
docs_path = "/docs/#{version_path}" if edition == 'kuma'
docs_path
end
def kubernetes_tab(contents, render_context, docs_path)
if render_context[:use_meshservice]
<<~TAB
{% tab Kubernetes %}
<div class="meshservice">
<label> <input type="checkbox"> I am using <a href="#{docs_path}/networking/meshservice/">MeshService</a> </label>
</div>
#{contents[:kube_legacy]}
#{contents[:kube]}
{% endtab %}
TAB
else
<<~TAB
{% tab Kubernetes %}
#{contents[:kube_legacy]}
{% endtab %}
TAB
end
end
def universal_tab(contents, render_context, docs_path)
if render_context[:use_meshservice]
<<~TAB
{% tab Universal %}
<div class="meshservice">
<label> <input type="checkbox"> I am using <a href="#{docs_path}/networking/meshservice/">MeshService</a> </label>
</div>
#{contents[:uni_legacy]}
#{contents[:uni]}
{% endtab %}
TAB
else
<<~TAB
{% tab Universal %}
#{contents[:uni_legacy]}
{% endtab %}
TAB
end
end
def terraform_tab(terraform_content, render_context)
return '' if render_context[:edition] == 'kuma' || !render_context[:show_tf]
<<~TAB
{% tab Terraform %}
<div style="margin-top: 4rem; padding: 0 1.3rem">
Please adjust <b>konnect_mesh_control_plane.my_meshcontrolplane.id</b> and
<b>konnect_mesh.my_mesh.name</b> according to your current configuration
</div>
#{terraform_content}
{% endtab %}
TAB
end
end
end
end
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/schema_viewer/renderer.rb | jekyll-kuma-plugins/lib/jekyll/kuma_plugins/liquid/tags/schema_viewer/renderer.rb | # frozen_string_literal: true
require 'json'
require 'cgi'
module Jekyll
module KumaPlugins
module Liquid
module Tags
module SchemaViewerComponents
# Renders schema data to HTML
class Renderer
DESCRIPTION_TRUNCATE_LENGTH = 100
def initialize(schema, filters = {}, excluded_fields = [], path_exclusions = {})
@definitions = schema['definitions'] || {}
@root_schema = resolve_ref(schema)
@filters = filters
@excluded_fields = excluded_fields
@path_exclusions = path_exclusions
end
def render
filtered_schema = apply_filters(@root_schema, [])
properties_html = render_properties(filtered_schema, 0, [])
"{::nomarkdown}\n<div class=\"schema-viewer\">#{properties_html}</div>\n{:/nomarkdown}"
end
private
def resolve_ref(schema)
return schema unless schema.is_a?(Hash) && schema['$ref']
ref_path = schema['$ref']
return schema unless ref_path.start_with?('#/definitions/')
def_name = ref_path.sub('#/definitions/', '')
@definitions[def_name] || schema
end
def extract_ref_name(schema)
return unless schema.is_a?(Hash) && schema['$ref']
ref_path = schema['$ref']
return unless ref_path.start_with?('#/definitions/')
def_name = ref_path.sub('#/definitions/', '')
# Simplify long definition names (e.g., "kuma.mesh.v1alpha1.Type" -> "Type")
def_name.split('.').last
end
def render_properties(schema, depth, path)
schema = resolve_ref(schema)
return '' unless schema.is_a?(Hash) && schema['properties'].is_a?(Hash)
required_fields = schema['required'] || []
sorted_properties = filter_excluded_properties(schema['properties'], depth, path)
props = sorted_properties.map do |name, prop|
render_property(name, prop, required_fields.include?(name), depth, path)
end
"<div class=\"schema-viewer__properties\">#{props.join}</div>"
end
def filter_excluded_properties(properties, depth, path)
# Filter out excluded fields (only at top level, depth 0)
filtered = depth.zero? ? properties.except(*@excluded_fields) : properties
# Apply path-based exclusions
path_str = path.join('.')
excluded_at_path = @path_exclusions[path_str] || []
filtered = filtered.except(*excluded_at_path) if excluded_at_path.any?
sort_properties(filtered, path)
end
def sort_properties(properties, path)
priority_order = %w[targetRef rules from to default]
target_ref_order = %w[kind name namespace labels sectionName]
order = path.last == 'targetRef' ? target_ref_order : priority_order
properties.sort_by do |name, _|
index = order.index(name)
index ? [0, index] : [1, name.downcase]
end
end
def render_property(name, prop, required, depth, path)
ref_name = extract_ref_name(prop)
resolved_prop = resolve_ref(prop)
return '' unless resolved_prop.is_a?(Hash)
# Build new path for this property
current_path = path + [name]
# Apply filters to this property
filtered_prop = apply_filters(resolved_prop, current_path)
metadata = { name: name, required: required, ref_name: ref_name }
build_property_html(filtered_prop, metadata, depth, current_path)
end
def build_property_html(prop, metadata, depth, path)
has_children = nested_properties?(prop)
html = [render_node_open(metadata[:name], prop, metadata, depth, has_children)]
html << render_content_section(prop)
html << render_children_section(prop, depth, path) if has_children
html << '</div>'
html.join
end
def render_node_open(name, prop, metadata, depth, has_children)
required = metadata[:required]
ref_name = metadata[:ref_name]
collapsed = depth.positive? ? 'schema-viewer__node--collapsed' : nil
expandable = has_children ? 'schema-viewer__node--expandable' : nil
arrow = has_children ? '<span class="schema-viewer__arrow"></span>' : '<span class="schema-viewer__arrow-placeholder"></span>'
required_badge = required ? '<span class="schema-viewer__required">required</span>' : nil
ref_badge = ref_name ? "<span class=\"schema-viewer__ref\">→ #{CGI.escapeHTML(ref_name)}</span>".force_encoding('UTF-8') : nil
header_attrs = build_header_attrs(has_children, depth)
<<~HTML.chomp
<div class="schema-viewer__node #{collapsed} #{expandable}" data-depth="#{depth}">
<div class="schema-viewer__header" #{header_attrs}>
#{arrow}
<span class="schema-viewer__name">#{CGI.escapeHTML(name)}</span>
#{render_type_badge(determine_type(prop))}
#{ref_badge}
#{required_badge}
</div>
HTML
end
def build_header_attrs(expandable, depth)
return unless expandable
%(tabindex="0" aria-expanded="#{depth.positive? ? 'false' : 'true'}")
end
def render_content_section(prop)
description = clean_description(prop['description'])
enum_values = extract_enum_values(prop)
default_value = prop['default']
return '' unless description || enum_values || default_value
content = []
content << render_description(description) if description
content << render_enum_values(enum_values) if enum_values
content << render_default_value(default_value) if default_value
"<div class=\"schema-viewer__content\">#{content.join}</div>"
end
def render_children_section(prop, depth, path)
"<div class=\"schema-viewer__children\">#{render_nested_content(prop, depth + 1, path)}</div>"
end
def determine_type(prop)
return 'enum' if prop['enum']
type = prop['type']
return type if type && SchemaViewer::TYPE_BADGES.include?(type)
return 'object' if prop['properties']
return 'array' if prop['items']
'any'
end
def render_type_badge(type)
badge_class = SchemaViewer::TYPE_BADGES.include?(type) ? "schema-viewer__type--#{type}" : 'schema-viewer__type--any'
"<span class=\"schema-viewer__type #{badge_class}\">#{CGI.escapeHTML(type)}</span>"
end
def nested_properties?(prop)
return true if prop['properties']
prop['items'] && resolve_ref(prop['items'])['properties']
end
def render_nested_content(prop, depth, path)
return render_properties(prop, depth, path) if prop['properties']
render_properties(resolve_ref(prop['items']), depth, path) if prop['items']
end
def apply_filters(schema, path)
return schema if @filters.empty?
return schema unless schema.is_a?(Hash)
# Make a deep copy to avoid mutating original and preserve encoding
filtered = Marshal.load(Marshal.dump(schema))
filter_path = path.join('.')
apply_filter_to_schema(filtered, filter_path) if @filters.key?(filter_path)
filtered
end
def apply_filter_to_schema(schema, filter_path)
allowed_values = @filters[filter_path]
filter_enum_values(schema, allowed_values)
filter_one_of_alternatives(schema, allowed_values)
filter_any_of_alternatives(schema, allowed_values)
end
def filter_enum_values(schema, allowed_values)
return unless schema['enum'].is_a?(Array)
schema['enum'] = schema['enum'].select { |v| allowed_values.include?(v.to_s) }
end
def filter_one_of_alternatives(schema, allowed_values)
return unless schema['oneOf'].is_a?(Array)
schema['oneOf'] = filter_alternatives(schema['oneOf'], allowed_values)
schema.delete('oneOf') if schema['oneOf'].empty?
end
def filter_any_of_alternatives(schema, allowed_values)
return unless schema['anyOf'].is_a?(Array)
schema['anyOf'] = filter_alternatives(schema['anyOf'], allowed_values)
schema.delete('anyOf') if schema['anyOf'].empty?
end
def filter_alternatives(alternatives, allowed_values)
alternatives.select do |alt|
# Check if alternative has an enum with any allowed values
if alt['enum'].is_a?(Array)
alt['enum'].map(&:to_s).intersect?(allowed_values)
# Check if alternative has a const matching allowed values
elsif alt['const']
allowed_values.include?(alt['const'].to_s)
else
# Keep alternatives without enum/const
true
end
end
end
def clean_description(desc)
return unless desc
desc.gsub('+optional', '').tr("\n", ' ').strip
end
def extract_enum_values(prop)
prop['enum']&.select { |v| v.is_a?(String) }
end
def render_description(description)
return '' unless description
description = description.to_s.force_encoding('UTF-8')
if description.length > DESCRIPTION_TRUNCATE_LENGTH
truncated = description[0...DESCRIPTION_TRUNCATE_LENGTH]
preview = CGI.escapeHTML(truncated)
<<~HTML.chomp
<div class="schema-viewer__description" data-full-text="#{description}">
<span class="schema-viewer__description-text">#{preview}...</span>
<button type="button" class="schema-viewer__show-more" aria-expanded="false">show more</button>
</div>
HTML
else
escaped = CGI.escapeHTML(description)
"<div class=\"schema-viewer__description\"><span class=\"schema-viewer__description-text\">#{escaped}</span></div>"
end
end
def render_enum_values(values)
return '' if values.empty?
"<div class=\"schema-viewer__enum\">Values: #{values.map { |v| "<code>#{CGI.escapeHTML(v)}</code>" }.join(' | ')}</div>"
end
def render_default_value(value)
return '' if value.nil?
formatted_value = value.is_a?(String) ? "\"#{value}\"" : JSON.generate(value)
"<div class=\"schema-viewer__default\">Default: <code>#{CGI.escapeHTML(formatted_value)}</code></div>"
end
end
end
end
end
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
require 'jekyll-generator-single-source'
require_relative 'support/golden_file_manager'
require_relative '../app/_plugins/tags/tabs/tabs'
require_relative '../jekyll-kuma-plugins/lib/jekyll_kuma_plugins'
# Register the tab and tabs tags from the Jekyll tabs plugin
Liquid::Template.register_tag('tab', Jekyll::Tabs::TabBlock)
Liquid::Template.register_tag('tabs', Jekyll::Tabs::TabsBlock)
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See https://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# If we ever upgrade jekyll-generator-single-source we will have to use below
# setting, where shared context can be found at:
# https://github.com/Kong/jekyll-generator-single-source/blob/51f1bac5603f3f0dad690bd1b9eced40565b389c/spec/support/shared_contexts/site.rb
# and example app fixture at:
# https://github.com/Kong/jekyll-generator-single-source/tree/51f1bac5603f3f0dad690bd1b9eced40565b389c/spec/fixtures/app2
# config.include SharedContexts::Site
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
# # This allows you to limit a spec run to individual examples or groups
# # you care about by tagging them with `:focus` metadata. When nothing
# # is tagged with `:focus`, all examples get run. RSpec also provides
# # aliases for `it`, `describe`, and `context` that include `:focus`
# # metadata: `fit`, `fdescribe` and `fcontext`, respectively.
# config.filter_run_when_matching :focus
#
# # Allows RSpec to persist some state between runs in order to support
# # the `--only-failures` and `--next-failure` CLI options. We recommend
# # you configure your source control system to ignore this file.
# config.example_status_persistence_file_path = "spec/examples.txt"
#
# # Limits the available syntax to the non-monkey patched syntax that is
# # recommended. For more details, see:
# # https://rspec.info/features/3-12/rspec-core/configuration/zero-monkey-patching-mode/
# config.disable_monkey_patching!
#
# # This setting enables warnings. It's recommended, but in some cases may
# # be too noisy due to issues in dependencies.
# config.warnings = true
#
# # Many RSpec users commonly either run the entire suite or an individual
# # file, and it's useful to allow more verbose output when running an
# # individual spec file.
# if config.files_to_run.one?
# # Use the documentation formatter for detailed output,
# # unless a formatter has already been configured
# # (e.g. via a command-line flag).
# config.default_formatter = "doc"
# end
#
# # Print the 10 slowest examples and example groups at the
# # end of the spec run, to help surface which specs are running
# # particularly slow.
# config.profile_examples = 10
#
# # Run specs in random order to surface order dependencies. If you find an
# # order dependency and want to debug it, you can fix the order by providing
# # the seed, which is printed after each run.
# # --seed 1234
# config.order = :random
#
# # Seed global randomization in this process using the `--seed` CLI option.
# # Setting this allows you to use `--seed` to deterministically reproduce
# # test failures related to randomization by passing the same `--seed` value
# # as the one that triggered the failure.
# Kernel.srand config.seed
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/spec/support/golden_file_manager.rb | spec/support/golden_file_manager.rb | # frozen_string_literal: true
require 'fileutils'
require 'diff/lcs'
module GoldenFileManager
ASSETS_DIR = 'dist/vite/assets/'
OUTPUT_CSS = File.join(ASSETS_DIR, 'application.css')
OUTPUT_JS = File.join(ASSETS_DIR, 'application.js')
def self.load_input(file_path)
File.read(file_path)
end
def self.load_golden(file_path)
File.read(file_path)
end
def self.update_golden(file_path, content)
File.write(file_path, content)
end
def self.remove_dynamic_attributes(html)
# Remove all occurrences of data-tab attributes
html.gsub(/ data-tab="[^"]*"/, '')
end
def self.find_latest_assets
latest_css = Dir.glob("#{ASSETS_DIR}*.css").max_by { |f| File.mtime(f) }
latest_js = Dir.glob("#{ASSETS_DIR}*.js").max_by { |f| File.mtime(f) }
[latest_css, latest_js]
end
def self.copy_file_if_different(src, dest)
return unless src && !File.identical?(src, dest)
FileUtils.cp(src, dest)
end
def self.copy_latest_assets
css_file, js_file = find_latest_assets
FileUtils.mkdir_p(ASSETS_DIR)
copy_file_if_different(css_file, OUTPUT_CSS) if css_file
copy_file_if_different(js_file, OUTPUT_JS) if js_file
end
def self.build_header
<<~HTML
<link rel="stylesheet" href="http://localhost:8000/#{OUTPUT_CSS}" />
<script src="http://localhost:8000/#{OUTPUT_JS}" crossorigin="anonymous" type="module"></script>
HTML
end
def self.assert_output(output, golden_path, include_header: false)
# Remove dynamic attributes from the actual output
cleaned_output = remove_dynamic_attributes(output)
# Add header if needed
if include_header
copy_latest_assets
header = build_header
cleaned_output = "#{header}\n\n#{cleaned_output}"
end
# Load the golden file content (original)
if File.exist?(golden_path)
golden_content = load_golden(golden_path)
else
# If the golden file does not exist, create it
update_golden(golden_path, cleaned_output.strip)
puts "Golden file created: #{golden_path}"
return
end
# Trim insignificant whitespace for comparison (removing indentation and trailing spaces)
trimmed_output = trim_insignificant_whitespace(cleaned_output)
trimmed_golden_content = trim_insignificant_whitespace(golden_content)
# Compare the trimmed versions
return unless trimmed_output != trimmed_golden_content
if ENV['UPDATE_GOLDEN_FILES'] == 'true'
# Update golden file if necessary
update_golden(golden_path, cleaned_output)
puts "Golden file updated: #{golden_path}"
else
# Print the diff of original (untrimmed) content for better visibility
puts "Output does not match golden file at #{golden_path}."
print_diff(golden_content, cleaned_output) # use original content for diff
raise "Output does not match golden file at #{golden_path}."
end
end
# Trim insignificant whitespace: leading/trailing spaces and indentation
def self.trim_insignificant_whitespace(content)
# Split content into lines, remove leading spaces and trailing whitespace
content.force_encoding('UTF-8').lines.map(&:rstrip).reject(&:empty?).join("\n")
end
def self.print_diff(expected, actual, context_lines: 5)
expected_lines = expected.split("\n")
actual_lines = actual.split("\n")
diffs = Diff::LCS.sdiff(expected_lines, actual_lines)
# Collect all the indexes of differences
diff_indexes = diffs.each_index.reject { |i| diffs[i].action == '=' }
# If there are no differences, return
return if diff_indexes.empty?
# Get the range of lines to display (5 lines before and after the first and last diffs)
first_diff = diff_indexes.first
last_diff = diff_indexes.last
start_line = [first_diff - context_lines, 0].max
end_line = [last_diff + context_lines, diffs.size - 1].min
puts "\nDiff (showing #{context_lines} lines before and after changes):\n\n"
(start_line..end_line).each do |i|
diff = diffs[i]
case diff.action
when '='
puts " #{i + 1}: #{diff.old_element}" # Unchanged line
when '-'
puts "-#{i + 1}: #{diff.old_element}" # Line in golden file but missing in actual output
when '+'
puts "+#{i + 1}: #{diff.new_element}" # Line in actual output but missing in golden file
when '!'
puts "-#{i + 1}: #{diff.old_element}" # Modified line in golden file
puts "+#{i + 1}: #{diff.new_element}" # Modified line in actual output
end
end
puts "\n"
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/spec/kuma_plugins/liquid/tags/inc_spec.rb | spec/kuma_plugins/liquid/tags/inc_spec.rb | # frozen_string_literal: true
ProcessedPage = Struct.new(:content)
RSpec.describe Jekyll::KumaPlugins::Liquid::Tags::Inc do
let(:version) { '2.9.1' }
let(:release) { Jekyll::GeneratorSingleSource::Product::Release.new({ 'release' => version }) }
let(:page) { { 'release' => release.to_liquid } }
let(:environment) { { 'page' => page } }
let(:registers) { { page: page } }
let(:liquid_context) { Liquid::Context.new(environment, {}, registers) }
shared_examples 'renders inc tag' do |if_version, params = [], golden_file|
tag_params = [%W[some_value if_version='#{if_version}'], *params.to_a].join(' ')
it "renders correctly for: {% inc #{tag_params} %} in context" do
template = <<~LIQUID
{% assign docs = "/docs/" | append: page.release %}
{% assign link = docs | append: "/networking/transparent-proxying/" %}
{% if_version #{if_version} %}
## Step {% inc #{tag_params} %}: Ensure the correct version of iptables.
{% endif_version %}
To prepare your service environment and start the data plane proxy,
follow the [Installing Transparent Proxy]({{ link }})
guide up to [Step {% inc #{tag_params} %}: Install the Transparent Proxy]({{ link }}).
LIQUID
processed = ProcessedPage.new(template)
Jekyll::Hooks.trigger(:pages, :pre_render, processed)
output = Liquid::Template.parse(processed.content).render(liquid_context)
GoldenFileManager.assert_output(output, golden_file, include_header: false)
end
end
describe 'inc tag rendering' do
[
{
if_version: 'gte:2.9.x',
golden_file: 'spec/fixtures/inc-if-version.golden.html'
},
{
if_version: 'lte:2.8.x',
golden_file: 'spec/fixtures/inc-if-version-not-met.golden.html'
},
{
if_version: 'gte:2.9.x',
params: ['init_value=5'],
golden_file: 'spec/fixtures/inc-if-version-init-value.golden.html'
},
{
if_version: 'lte:2.8.x',
params: ['init_value=5'],
golden_file: 'spec/fixtures/inc-if-version-not-met-init-value.golden.html'
},
{
if_version: 'gte:2.9.x',
params: ['get_current'],
golden_file: 'spec/fixtures/inc-if-version-get-current.golden.html'
},
{
if_version: 'lte:2.8.x',
params: ['get_current'],
golden_file: 'spec/fixtures/inc-if-version-not-met-get-current.golden.html'
},
{
if_version: 'gte:2.9.x',
params: %w[get_current init_value=5],
golden_file: 'spec/fixtures/inc-if-version-get-current-init-value.golden.html'
},
{
if_version: 'lte:2.8.x',
params: %w[get_current init_value=5],
golden_file: 'spec/fixtures/inc-if-version-not-met-get-current-init-value.golden.html'
}
].each do |test_case|
include_examples 'renders inc tag', test_case[:if_version],
test_case[:params],
test_case[:golden_file]
end
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/spec/kuma_plugins/liquid/tags/rbacresources_spec.rb | spec/kuma_plugins/liquid/tags/rbacresources_spec.rb | # frozen_string_literal: true
RSpec.describe Jekyll::KumaPlugins::Liquid::Tags::RbacResources do
shared_examples 'rbac resources rendering' do |input_file, golden_file|
it "renders correctly for #{input_file}" do
site = Jekyll::Site.new(Jekyll.configuration({}))
context = Liquid::Context.new({}, {}, {
page: {
'edition' => 'kuma',
'release' => Jekyll::GeneratorSingleSource::Product::Release.new({ 'release' => '2.11.x',
'edition' => 'kuma' })
},
site: site
})
tag = "{% rbacresources filename=#{input_file} %}"
template = Liquid::Template.parse(tag)
output = template.render(context)
GoldenFileManager.assert_output(output, golden_file, include_header: true)
end
end
describe 'rendering test' do
include_examples 'rbac resources rendering',
'spec/fixtures/rbac.yaml',
'spec/fixtures/rbac.golden.html'
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/spec/kuma_plugins/liquid/tags/policy_yaml_spec.rb | spec/kuma_plugins/liquid/tags/policy_yaml_spec.rb | # frozen_string_literal: true
RSpec.describe Jekyll::KumaPlugins::Liquid::Tags::PolicyYaml do
# Set up the Jekyll site and context for testing
shared_examples 'policy yaml rendering' do |input_file, golden_file, tag_options, release|
it "renders correctly for #{input_file}" do
site = Jekyll::Site.new(Jekyll.configuration({ mesh_namespace: 'kuma-demo' }))
release ||= { 'release' => '2.9.x', 'edition' => 'kuma' } # This sets the version key for testing
context = Liquid::Context.new({}, {},
{ page: { 'edition' => release['edition'], 'release' => Jekyll::GeneratorSingleSource::Product::Release.new(release) }, site: site })
content = GoldenFileManager.load_input(input_file)
tag_content = tag_options ? "{% policy_yaml #{tag_options} %}" : '{% policy_yaml %}'
template = Liquid::Template.parse("#{tag_content}#{content}{% endpolicy_yaml %}")
output = template.render(context)
GoldenFileManager.assert_output(output, golden_file, include_header: true)
end
end
describe 'rendering tests' do
test_cases = [
{
input_file: 'spec/fixtures/mt-with-from-and-meshservice-in-to.yaml',
golden_file: 'spec/fixtures/mt-with-from-and-meshservice-in-to.golden.html',
tag_options: 'use_meshservice=true'
},
{
input_file: 'spec/fixtures/mhr-and-mtr.yaml',
golden_file: 'spec/fixtures/mhr-and-mtr.golden.html',
tag_options: 'use_meshservice=true'
},
{
input_file: 'spec/fixtures/mt-with-from-and-to.yaml',
golden_file: 'spec/fixtures/mt-with-from-and-to.golden.html',
tag_options: nil
},
{
input_file: 'spec/fixtures/mtr.yaml',
golden_file: 'spec/fixtures/mtr.golden.html',
tag_options: 'use_meshservice=true'
},
{
input_file: 'spec/fixtures/mhr-port.yaml',
golden_file: 'spec/fixtures/mhr-port.golden.html',
tag_options: 'use_meshservice=true'
},
{
input_file: 'spec/fixtures/mhr-port.yaml',
golden_file: 'spec/fixtures/mhr-port_edition.golden.html',
tag_options: 'use_meshservice=true',
page: { 'release' => '2.10.x', 'edition' => 'mesh' }
},
{
input_file: 'spec/fixtures/mhr-port.yaml',
golden_file: 'spec/fixtures/mhr-port_dev.golden.html',
tag_options: 'use_meshservice=true',
page: { 'release' => '2.10.x', 'edition' => 'kuma', 'label' => 'dev' }
},
{
input_file: 'spec/fixtures/hostnamegenerator.yaml',
golden_file: 'spec/fixtures/hostnamegenerator.golden.html',
tag_options: nil
},
{
input_file: 'spec/fixtures/hostnamegenerator-labels.yaml',
golden_file: 'spec/fixtures/hostnamegenerator-labels.golden.html',
tag_options: nil
}
]
test_cases.each do |test_case|
include_examples 'policy yaml rendering',
test_case[:input_file],
test_case[:golden_file],
test_case[:tag_options],
test_case[:page]
end
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
kumahq/kuma-website | https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/spec/kuma_plugins/liquid/tags/schema_viewer_spec.rb | spec/kuma_plugins/liquid/tags/schema_viewer_spec.rb | # frozen_string_literal: true
RSpec.describe Jekyll::KumaPlugins::Liquid::Tags::SchemaViewer do
shared_examples 'schema viewer rendering' do |schema_name, schema_type, golden_file|
it "renders correctly for #{schema_name} type=#{schema_type}" do
site = Jekyll::Site.new(Jekyll.configuration({
mesh_raw_generated_paths: ['app/assets']
}))
context = Liquid::Context.new({}, {}, {
page: {
'edition' => 'kuma',
'release' => Jekyll::GeneratorSingleSource::Product::Release.new({
'release' => 'dev',
'edition' => 'kuma'
})
},
site: site
})
tag = "{% schema_viewer #{schema_name} type=#{schema_type} %}"
template = Liquid::Template.parse(tag)
output = template.render(context)
GoldenFileManager.assert_output(output, golden_file, include_header: true)
end
end
describe 'rendering tests' do
include_examples 'schema viewer rendering',
'Mesh',
'proto',
'spec/fixtures/schema-viewer-mesh.golden.html'
include_examples 'schema viewer rendering',
'MeshTimeouts',
'policy',
'spec/fixtures/schema-viewer-meshtimeouts.golden.html'
include_examples 'schema viewer rendering',
'MeshCircuitBreakers',
'policy',
'spec/fixtures/schema-viewer-meshcircuitbreakers.golden.html'
end
describe 'error handling' do
it 'returns error div for missing schema' do
site = Jekyll::Site.new(Jekyll.configuration({
mesh_raw_generated_paths: ['app/assets']
}))
context = Liquid::Context.new({}, {}, {
page: {
'edition' => 'kuma',
'release' => Jekyll::GeneratorSingleSource::Product::Release.new({
'release' => 'dev',
'edition' => 'kuma'
})
},
site: site
})
tag = '{% schema_viewer NonExistentSchema type=proto %}'
template = Liquid::Template.parse(tag)
output = template.render(context)
expect(output).to include('schema-viewer-error')
expect(output).to include('Error loading schema')
end
end
describe 'parameter filtering' do
it 'parses filter parameters with dot notation' do
tag = Liquid::Template.parse('{% schema_viewer TestSchema targetRef.kind=Mesh,MeshService %}').root.nodelist.first
filters = tag.instance_variable_get(:@filters)
expect(filters).to have_key('targetRef.kind')
expect(filters['targetRef.kind']).to eq(%w[Mesh MeshService])
end
it 'handles parameter values with multiple = signs' do
tag = Liquid::Template.parse('{% schema_viewer TestSchema key=value=with=equals %}').root.nodelist.first
filters = tag.instance_variable_get(:@filters)
expect(filters).to be_empty
end
it 'separates filter parameters from regular parameters' do
tag = Liquid::Template.parse('{% schema_viewer TestSchema type=policy targetRef.kind=Mesh %}').root.nodelist.first
filters = tag.instance_variable_get(:@filters)
expect(filters).to have_key('targetRef.kind')
expect(filters['targetRef.kind']).to eq(['Mesh'])
end
it 'handles comma-separated values without spaces' do
tag = Liquid::Template.parse('{% schema_viewer TestSchema path.field=Value1,Value2,Value3 %}').root.nodelist.first
filters = tag.instance_variable_get(:@filters)
expect(filters['path.field']).to eq(%w[Value1 Value2 Value3])
end
it 'strips whitespace from comma-separated values' do
tag = Liquid::Template.parse('{% schema_viewer TestSchema path.field=Value1,Value2,Value3 %}').root.nodelist.first
filters = tag.instance_variable_get(:@filters)
filters['path.field'].each do |value|
expect(value).not_to match(/^\s|\s$/)
end
end
it 'parses exclude parameter' do
tag = Liquid::Template.parse('{% schema_viewer TestSchema exclude=from %}').root.nodelist.first
excluded_fields = tag.instance_variable_get(:@excluded_fields)
expect(excluded_fields).to eq(['from'])
end
it 'parses exclude parameter with multiple fields' do
tag = Liquid::Template.parse('{% schema_viewer TestSchema exclude=from,rules %}').root.nodelist.first
excluded_fields = tag.instance_variable_get(:@excluded_fields)
expect(excluded_fields).to eq(%w[from rules])
end
it 'handles multiple excluded fields' do
tag = Liquid::Template.parse('{% schema_viewer TestSchema exclude=from,rules,to %}').root.nodelist.first
excluded_fields = tag.instance_variable_get(:@excluded_fields)
expect(excluded_fields).to eq(%w[from rules to])
end
it 'parses path-based exclusion parameters' do
tag = Liquid::Template.parse('{% schema_viewer TestSchema exclude.targetRef=tags,mesh %}').root.nodelist.first
path_exclusions = tag.instance_variable_get(:@path_exclusions)
expect(path_exclusions).to have_key('targetRef')
expect(path_exclusions['targetRef']).to eq(%w[tags mesh])
end
it 'handles multiple path-based exclusions' do
tag = Liquid::Template.parse('{% schema_viewer TestSchema exclude.targetRef=tags exclude.to.targetRef=mesh %}').root.nodelist.first
path_exclusions = tag.instance_variable_get(:@path_exclusions)
expect(path_exclusions).to have_key('targetRef')
expect(path_exclusions).to have_key('to.targetRef')
expect(path_exclusions['targetRef']).to eq(['tags'])
expect(path_exclusions['to.targetRef']).to eq(['mesh'])
end
end
describe Jekyll::KumaPlugins::Liquid::Tags::SchemaViewerComponents::Renderer do
describe '#apply_filters' do
let(:schema) do
{
'enum' => %w[Mesh MeshService MeshGateway],
'oneOf' => [
{ 'enum' => ['Mesh'] },
{ 'enum' => ['MeshService'] }
],
'anyOf' => [
{ 'const' => 'Value1' },
{ 'const' => 'Value2' }
]
}
end
it 'filters enum values to allowed list' do
filters = { 'targetRef.kind' => %w[Mesh MeshService] }
renderer = described_class.new({ 'properties' => {} }, filters)
filtered = renderer.send(:apply_filters, schema, %w[targetRef kind])
expect(filtered['enum']).to eq(%w[Mesh MeshService])
expect(filtered['enum']).not_to include('MeshGateway')
end
it 'filters oneOf alternatives based on enum values' do
filters = { 'targetRef.kind' => ['Mesh'] }
renderer = described_class.new({ 'properties' => {} }, filters)
filtered = renderer.send(:apply_filters, schema, %w[targetRef kind])
expect(filtered['oneOf'].length).to eq(1)
expect(filtered['oneOf'][0]['enum']).to eq(['Mesh'])
end
it 'filters anyOf alternatives based on const values' do
filters = { 'field.path' => ['Value1'] }
renderer = described_class.new({ 'properties' => {} }, filters)
filtered = renderer.send(:apply_filters, schema, %w[field path])
expect(filtered['anyOf'].length).to eq(1)
expect(filtered['anyOf'][0]['const']).to eq('Value1')
end
it 'deletes empty oneOf after filtering' do
filters = { 'targetRef.kind' => ['NonExistent'] }
renderer = described_class.new({ 'properties' => {} }, filters)
filtered = renderer.send(:apply_filters, schema, %w[targetRef kind])
expect(filtered).not_to have_key('oneOf')
end
it 'deletes empty anyOf after filtering' do
filters = { 'field.path' => ['NonExistent'] }
renderer = described_class.new({ 'properties' => {} }, filters)
filtered = renderer.send(:apply_filters, schema, %w[field path])
expect(filtered).not_to have_key('anyOf')
end
it 'returns unchanged schema when no filters match path' do
filters = { 'other.path' => ['Value'] }
renderer = described_class.new({ 'properties' => {} }, filters)
filtered = renderer.send(:apply_filters, schema, %w[targetRef kind])
expect(filtered['enum']).to eq(schema['enum'])
expect(filtered['oneOf']).to eq(schema['oneOf'])
end
it 'returns unchanged schema when filters are empty' do
renderer = described_class.new({ 'properties' => {} }, {})
filtered = renderer.send(:apply_filters, schema, %w[targetRef kind])
expect(filtered).to eq(schema)
end
it 'does not mutate original schema' do
original_enum = schema['enum'].dup
filters = { 'targetRef.kind' => ['Mesh'] }
renderer = described_class.new({ 'properties' => {} }, filters)
renderer.send(:apply_filters, schema, %w[targetRef kind])
expect(schema['enum']).to eq(original_enum)
end
end
describe '#filter_alternatives' do
let(:renderer) { described_class.new({ 'properties' => {} }, {}) }
it 'filters alternatives with matching enum values' do
alternatives = [
{ 'enum' => %w[Mesh MeshService] },
{ 'enum' => ['MeshGateway'] }
]
allowed = ['Mesh']
result = renderer.send(:filter_alternatives, alternatives, allowed)
expect(result.length).to eq(1)
expect(result[0]['enum']).to include('Mesh')
end
it 'filters alternatives with matching const values' do
alternatives = [
{ 'const' => 'Value1' },
{ 'const' => 'Value2' }
]
allowed = ['Value1']
result = renderer.send(:filter_alternatives, alternatives, allowed)
expect(result.length).to eq(1)
expect(result[0]['const']).to eq('Value1')
end
it 'keeps alternatives without enum or const' do
alternatives = [
{ 'type' => 'string' },
{ 'enum' => ['NotAllowed'] }
]
allowed = ['Allowed']
result = renderer.send(:filter_alternatives, alternatives, allowed)
expect(result.length).to eq(1)
expect(result[0]['type']).to eq('string')
end
it 'handles empty enum arrays' do
alternatives = [{ 'enum' => [] }]
allowed = ['Value']
result = renderer.send(:filter_alternatives, alternatives, allowed)
expect(result).to be_empty
end
it 'excludes alternatives with non-matching const when const is present' do
alternatives = [
{ 'const' => 'NotMatching' },
{ 'const' => 'Value1' }
]
allowed = ['Value1']
result = renderer.send(:filter_alternatives, alternatives, allowed)
expect(result.length).to eq(1)
expect(result[0]['const']).to eq('Value1')
end
end
end
end
| ruby | Apache-2.0 | 7b6c49c772192d2ecf31f70c006229013ad32a56 | 2026-01-04T17:42:48.724969Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/riddle_spec.rb | spec/riddle_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle do
describe '.version_warning' do
before :each do
@existing_version = Riddle.loaded_version
end
after :each do
Riddle.loaded_version = @existing_version
end
it "should do nothing if there is a Sphinx version loaded" do
STDERR.should_not_receive(:puts)
Riddle.loaded_version = '0.9.8'
Riddle.version_warning
end
it "should output a warning if no version is loaded" do
STDERR.should_receive(:puts)
Riddle.loaded_version = nil
Riddle.version_warning
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
require 'rubygems'
require 'bundler'
$:.unshift File.dirname(__FILE__) + '/../lib'
$:.unshift File.dirname(__FILE__) + '/..'
Dir['spec/support/**/*.rb'].each { |f| require f }
Bundler.require :default, :development
require 'riddle'
RSpec.configure do |config|
config.include BinaryFixtures
sphinx = Sphinx.new
sphinx.setup_mysql
sphinx.generate_configuration
sphinx.index
config.before :all do |group|
sphinx.start if group.class.metadata[:live]
end
config.after :all do |group|
sphinx.stop if group.class.metadata[:live]
end
# enable filtering for examples
config.filter_run :wip => true
config.run_all_when_everything_filtered = true
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/support/binary_fixtures.rb | spec/support/binary_fixtures.rb | # frozen_string_literal: true
module BinaryFixtures
def query_contents(key)
path = "spec/fixtures/data/#{Riddle.loaded_version}/#{key}.bin"
contents = open(path) { |f| f.read }
contents.respond_to?(:encoding) ?
contents.force_encoding('ASCII-8BIT') : contents
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/support/sphinx.rb | spec/support/sphinx.rb | # frozen_string_literal: true
require 'erb'
require 'yaml'
require 'tempfile'
if RUBY_PLATFORM == 'java'
require 'java'
require 'jdbc/mysql'
Jdbc::MySQL.load_driver
end
class Sphinx
attr_accessor :host, :username, :password, :port
def initialize
self.host = ENV['MYSQL_HOST'] || 'localhost'
self.username = ENV['MYSQL_USER'] || 'root'
self.password = ENV['MYSQL_PASSWORD'] || ''
self.port = ENV['MYSQL_PORT'] || nil
if File.exist?('spec/fixtures/sql/conf.yml')
config = YAML.load(File.open('spec/fixtures/sql/conf.yml'))
self.host = config['host']
self.username = config['username']
self.password = config['password']
self.port = config['port']
end
end
def bin_path
ENV.fetch 'SPHINX_BIN', ''
end
def setup_mysql
databases = mysql_client.query "SHOW DATABASES"
unless databases.include?("riddle")
mysql_client.execute "CREATE DATABASE riddle"
end
mysql_client.execute 'USE riddle'
structure = File.open('spec/fixtures/sql/structure.sql') { |f| f.read }
structure.split(/;/).each { |sql| mysql_client.execute sql }
mysql_client.execute <<-SQL
LOAD DATA LOCAL INFILE '#{fixtures_path}/sql/data.tsv' INTO TABLE
`riddle`.`people` FIELDS TERMINATED BY ',' ENCLOSED BY "'" (gender,
first_name, middle_initial, last_name, street_address, city, state,
postcode, email, birthday)
SQL
mysql_client.close
end
def mysql_client
@mysql_client ||= if RUBY_PLATFORM == 'java'
JRubyClient.new host, username, password, port
else
MRIClient.new host, username, password, port
end
end
def generate_configuration
template = File.open('spec/fixtures/sphinx/configuration.erb') { |f| f.read }
File.open('spec/fixtures/sphinx/spec.conf', 'w') { |f|
f.puts ERB.new(template).result(binding)
}
FileUtils.mkdir_p "spec/fixtures/sphinx/binlog"
end
def index
cmd = "#{bin_path}indexer --config #{fixtures_path}/sphinx/spec.conf --all"
cmd << ' --rotate' if running?
`#{cmd}`
end
def start
return if running?
`#{bin_path}searchd --config #{fixtures_path}/sphinx/spec.conf`
sleep(1)
unless running?
puts 'Failed to start searchd daemon. Check fixtures/sphinx/searchd.log.'
end
end
def stop
return unless running?
stop_flag = '--stopwait'
stop_flag = '--stop' if Riddle.loaded_version.to_i < 1
`#{bin_path}searchd --config #{fixtures_path}/sphinx/spec.conf #{stop_flag}`
end
private
def fixtures_path
File.expand_path File.join(File.dirname(__FILE__), '..', 'fixtures')
end
def pid
if File.exist?("#{fixtures_path}/sphinx/searchd.pid")
`cat #{fixtures_path}/sphinx/searchd.pid`[/\d+/]
else
nil
end
end
def running?
pid && `ps #{pid} | wc -l`.to_i > 1
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/support/jruby_client.rb | spec/support/jruby_client.rb | # frozen_string_literal: true
class JRubyClient
def initialize(host, username, password, port)
address = "jdbc:mysql://#{host}"
properties = Java::JavaUtil::Properties.new
properties.setProperty "user", username if username
properties.setProperty "password", password if password
properties.setProperty "port", port if port
properties.setProperty "useSSL", "false"
properties.setProperty "allowLoadLocalInfile", "true"
@client = Java::ComMysqlJdbc::Driver.new.connect address, properties
end
def query(statement)
set = client.createStatement.executeQuery(statement)
results = []
results << set.getString(1) while set.next
results
end
def execute(statement)
client.createStatement.execute statement
end
def close
@client.close
end
private
attr_reader :client
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/support/mri_client.rb | spec/support/mri_client.rb | # frozen_string_literal: true
class MRIClient
def initialize(host, username, password, port)
@client = Mysql2::Client.new(
:host => host,
:username => username,
:password => password,
:port => port,
:local_infile => true
)
end
def query(statement)
client.query(statement, :as => :array).to_a.flatten
end
def execute(statement)
client.query statement
end
def close
@client.close
end
private
attr_reader :client
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/unit/response_spec.rb | spec/unit/response_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Client::Response do
it "should interpret an integer correctly" do
Riddle::Client::Response.new([42].pack('N')).next_int.should == 42
end
it "should interpret a string correctly" do
str = "this is a string"
Riddle::Client::Response.new(
[str.length].pack('N') + str
).next.should == str
end
# Comparing floats with decimal places doesn't seem to be exact
it "should interpret a float correctly" do
Riddle::Client::Response.new([1.0].pack('f').unpack('L*').pack('N')).next_float.should == 1.0
end
it "should interpret an array of strings correctly" do
arr = ["a", "b", "c", "d"]
Riddle::Client::Response.new(
[arr.length].pack('N') + arr.collect { |str|
[str.length].pack('N') + str
}.join("")
).next_array.should == arr
end
it "should interpret an array of ints correctly" do
arr = [1, 2, 3, 4]
Riddle::Client::Response.new(
[arr.length].pack('N') + arr.collect { |int|
[int].pack('N')
}.join("")
).next_int_array.should == arr
end
it "should reflect the length of the incoming data correctly" do
data = [1, 2, 3, 4].pack('NNNN')
Riddle::Client::Response.new(data).length.should == data.length
end
it "should handle a combination of strings and ints correctly" do
data = [1, 3, 5, 1].pack('NNNN') + 'a' + [2, 4].pack('NN') + 'test'
response = Riddle::Client::Response.new(data)
response.next_int.should == 1
response.next_int.should == 3
response.next_int.should == 5
response.next.should == 'a'
response.next_int.should == 2
response.next.should == 'test'
end
it "should handle a combination of strings, ints, floats and string arrays correctly" do
data = [1, 2, 2].pack('NNN') + 'aa' + [2].pack('N') + 'bb' + [4].pack('N') +
"word" + [7].pack('f').unpack('L*').pack('N') + [3, 2, 2, 2].pack('NNNN')
response = Riddle::Client::Response.new(data)
response.next_int.should == 1
response.next_array.should == ['aa', 'bb']
response.next.should == "word"
response.next_float.should == 7
response.next_int_array.should == [2, 2, 2]
end
end | ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/unit/client_spec.rb | spec/unit/client_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Client do
it "should have the same keys for both commands and versions, except persist" do
(Riddle::Client::Commands.keys - [:persist]).should == Riddle::Client::Versions.keys
end
it "should default to localhost as the server" do
Riddle::Client.new.server.should == "localhost"
end
it "should default to port 9312" do
Riddle::Client.new.port.should == 9312
end
it "should accept an array of servers" do
servers = ["1.1.1.1", "2.2.2.2", "3.3.3.3"]
client = Riddle::Client.new(servers)
client.servers.should == servers
end
it "should translate anchor arguments correctly" do
client = Riddle::Client.new
client.set_anchor "latitude", 10.0, "longitude", 95.0
client.anchor.should == {
:latitude_attribute => "latitude",
:latitude => 10.0,
:longitude_attribute => "longitude",
:longitude => 95.0
}
end
it "should add queries to the queue" do
client = Riddle::Client.new
client.queue.should be_empty
client.append_query "spec"
client.queue.should_not be_empty
end
describe 'query contents' do
it "should build a basic search message correctly" do
client = Riddle::Client.new
client.append_query "test "
client.queue.first.should == query_contents(:simple)
end
it "should build a message with a specified index correctly" do
client = Riddle::Client.new
client.append_query "test ", "edition"
client.queue.first.should == query_contents(:index)
end
it "should build a message using match mode :any correctly" do
client = Riddle::Client.new
client.match_mode = :any
client.append_query "test this "
client.queue.first.should == query_contents(:any)
end
it "should build a message using sort by correctly" do
client = Riddle::Client.new
client.sort_by = 'id'
client.sort_mode = :extended
client.append_query "testing "
client.queue.first.should == query_contents(:sort)
end
it "should build a message using match mode :boolean correctly" do
client = Riddle::Client.new
client.match_mode = :boolean
client.append_query "test "
client.queue.first.should == query_contents(:boolean)
end
it "should build a message using match mode :phrase correctly" do
client = Riddle::Client.new
client.match_mode = :phrase
client.append_query "testing this "
client.queue.first.should == query_contents(:phrase)
end
it "should build a message with a filter correctly" do
client = Riddle::Client.new
client.filters << Riddle::Client::Filter.new("id", [10, 100, 1000])
client.append_query "test "
client.queue.first.should == query_contents(:filter)
end
it "should build a message with group values correctly" do
client = Riddle::Client.new
client.group_by = "id"
client.group_function = :attr
client.group_clause = "id"
client.append_query "test "
client.queue.first.should == query_contents(:group)
end
it "should build a message with group distinct value correctly" do
client = Riddle::Client.new
client.group_distinct = "id"
client.append_query "test "
client.queue.first.should == query_contents(:distinct)
end
it "should build a message with weights correctly" do
client = Riddle::Client.new
client.weights = [100, 1]
client.append_query "test "
client.queue.first.should == query_contents(:weights)
end
it "should build a message with an anchor correctly" do
client = Riddle::Client.new
client.set_anchor "latitude", 10.0, "longitude", 95.0
client.append_query "test "
client.queue.first.should == query_contents(:anchor)
end
it "should build a message with index weights correctly" do
client = Riddle::Client.new
client.index_weights = {"people" => 101}
client.append_query "test "
client.queue.first.should == query_contents(:index_weights)
end
it "should build a message with field weights correctly" do
client = Riddle::Client.new
client.field_weights = {"city" => 101}
client.append_query "test "
client.queue.first.should == query_contents(:field_weights)
end
it "should build a message with a comment correctly" do
client = Riddle::Client.new
client.append_query "test ", "*", "commenting"
client.queue.first.should == query_contents(:comment)
end
if Riddle.loaded_version == '0.9.9' || Riddle.loaded_version == '1.10'
it "should build a message with overrides correctly" do
client = Riddle::Client.new
client.add_override("rating", :float, {1 => 10.0})
client.append_query "test "
client.queue.first.should == query_contents(:overrides)
end
it "should build a message with selects correctly" do
client = Riddle::Client.new
client.select = "selecting"
client.append_query "test "
client.queue.first.should == query_contents(:select)
end
end
it "should keep multiple messages in the queue" do
client = Riddle::Client.new
client.weights = [100, 1]
client.append_query "test "
client.append_query "test "
client.queue.length.should == 2
client.queue.each { |item| item.should == query_contents(:weights) }
end
it "should keep multiple messages in the queue with different params" do
client = Riddle::Client.new
client.weights = [100, 1]
client.append_query "test "
client.weights = []
client.append_query "test ", "edition"
client.queue.first.should == query_contents(:weights)
client.queue.last.should == query_contents(:index)
end
it "should build a basic update message correctly" do
client = Riddle::Client.new
client.send(
:update_message,
"people",
["birthday"],
{1 => [191163600]}
).should == query_contents(:update_simple)
end
it "should build a keywords request without hits correctly" do
client = Riddle::Client.new
client.send(
:keywords_message,
"pat",
"people",
false
).should == query_contents(:keywords_without_hits)
end
it "should build a keywords request with hits correctly" do
client = Riddle::Client.new
client.send(
:keywords_message,
"pat",
"people",
true
).should == query_contents(:keywords_with_hits)
end
end
it "should timeout after a specified time" do
client = Riddle::Client.new
client.port = 9314
client.timeout = 1
server = TCPServer.new "localhost", 9314
lambda {
client.send(:connect) { |socket| }
}.should raise_error(Riddle::ConnectionError)
server.close
end unless RUBY_PLATFORM == 'java' # JRuby doesn't like Timeout
context "connection retrying" do
it "should try fives time when connection refused" do
client = Riddle::Client.new
client.port = 3314
TCPSocket.should_receive(:new).with('localhost', 3314).exactly(5).times.
and_raise(Errno::ECONNREFUSED)
lambda {
client.send(:connect) { |socket| }
}.should raise_error(Riddle::ConnectionError)
end
end
context "connection fail over" do
it "should try each of several server addresses after timeouts" do
client = Riddle::Client.new
client.port = 3314
client.servers = %w[localhost 127.0.0.1 0.0.0.0]
client.timeout = 1
TCPSocket.should_receive(:new).with(
an_instance_of(String), 3314
).exactly(3).and_raise Timeout::Error
lambda {
client.send(:connect) { |socket| }
}.should raise_error(Riddle::ConnectionError)
end unless RUBY_PLATFORM == 'java' # JRuby doesn't like Timeout
it "should try each of several server addresses after a connection refused" do
client = Riddle::Client.new
client.port = 3314
client.servers = %w[localhost 127.0.0.1 0.0.0.0]
client.timeout = 1
# initialise_socket will retry 5 times before failing,
# these combined with the multiple server failover should result in 15
# calls to TCPSocket.new
TCPSocket.should_receive(:new).with(
an_instance_of(String), 3314
).exactly(3 * 5).and_raise Errno::ECONNREFUSED
lambda {
client.send(:connect) { |socket| }
}.should raise_error(Riddle::ConnectionError)
end unless RUBY_PLATFORM == 'java' # JRuby doesn't like Timeout
end
it "should fail if the server has the wrong version" do
client = Riddle::Client.new
client.port = 9314
client.timeout = 1
server = TCPServer.new "localhost", 9314
thread = Thread.new do
client = server.accept
client.send [0].pack("N"), 0
client.close
end
lambda {
client.send(:connect) { |socket| }
}.should raise_error(Riddle::VersionError)
thread.exit
server.close
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/unit/message_spec.rb | spec/unit/message_spec.rb | # encoding: BINARY
# frozen_string_literal: true
require 'spec_helper'
describe Riddle::Client::Message do
it "should start with an empty string" do
Riddle::Client::Message.new.to_s.should == ""
end
it "should append raw data correctly" do
data = [1, 2, 3].pack('NNN')
message = Riddle::Client::Message.new
message.append data
message.to_s.should == data
end
it "should append strings correctly - with length first" do
str = "something to test with"
message = Riddle::Client::Message.new
message.append_string str
message.to_s.should == [str.length].pack('N') + str
end
it "should append integers correctly - packed with N" do
message = Riddle::Client::Message.new
message.append_int 234
message.to_s.should == "\x00\x00\x00\xEA"
end
it "should append integers as strings correctly - packed with N" do
message = Riddle::Client::Message.new
message.append_int "234"
message.to_s.should == "\x00\x00\x00\xEA"
end
it "should append 64bit integers correctly" do
message = Riddle::Client::Message.new
message.append_64bit_int 234
message.to_s.should == "\x00\x00\x00\x00\x00\x00\x00\xEA"
end
it "should append 64bit integers that use exactly 32bits correctly" do
message = Riddle::Client::Message.new
message.append_64bit_int 4294967295
message.to_s.should == "\x00\x00\x00\x00\xFF\xFF\xFF\xFF"
end
it "should append 64bit integers that use more than 32 bits correctly" do
message = Riddle::Client::Message.new
message.append_64bit_int 4294967296
message.to_s.should == "\x00\x00\x00\x01\x00\x00\x00\x00"
end
it "should append 64bit integers as strings correctly" do
message = Riddle::Client::Message.new
message.append_64bit_int "234"
message.to_s.should == "\x00\x00\x00\x00\x00\x00\x00\xEA"
end
it "should append floats correctly - packed with f" do
message = Riddle::Client::Message.new
message.append_float 1.4
message.to_s.should == [1.4].pack('f').unpack('L*').pack('N')
end
it "should append a collection of integers correctly" do
message = Riddle::Client::Message.new
message.append_ints 1, 2, 3, 4
message.to_s.should == [1, 2, 3, 4].pack('NNNN')
end
it "should append a collection of floats correctly" do
message = Riddle::Client::Message.new
message.append_floats 1.0, 1.1, 1.2, 1.3
message.to_s.should == [1.0, 1.1, 1.2, 1.3].pack('ffff').unpack('L*L*L*L*').pack('NNNN')
end
it "should append an array of strings correctly" do
arr = ["a", "bb", "ccc"]
message = Riddle::Client::Message.new
message.append_array arr
message.to_s.should == [3, 1].pack('NN') + "a" + [2].pack('N') + "bb" +
[3].pack('N') + "ccc"
end
it "should append a variety of objects correctly" do
message = Riddle::Client::Message.new
message.append_int 4
message.append_string "test"
message.append_array ["one", "two"]
message.append_floats 1.5, 1.7
message.to_s.should == [4, 4].pack('NN') + "test" + [2, 3].pack('NN') +
"one" + [3].pack('N') + "two" + [1.5, 1.7].pack('ff').unpack('L*L*').pack('NN')
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/unit/riddle_spec.rb | spec/unit/riddle_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe "Riddle" do
it "should escape characters correctly" do
invalid_chars = ['(', ')', '|', '-', '!', '@', '~', '"', '/']
invalid_chars.each do |char|
base = "string with '#{char}' character"
Riddle.escape(base).should == base.gsub(char, "\\#{char}")
end
# Not sure why this doesn't work within the loop...
Riddle.escape("string with & character").should == "string with \\& character"
all_chars = invalid_chars.join('') + '&'
Riddle.escape(all_chars).should == "\\(\\)\\|\\-\\!\\@\\~\\\"\\/\\&"
end
end | ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/unit/configuration_spec.rb | spec/unit/configuration_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Configuration do
it "should render all given indexes and sources, plus the indexer and search sections" do
config = Riddle::Configuration.new
config.searchd.port = 3312
config.searchd.pid_file = "file.pid"
source = Riddle::Configuration::XMLSource.new("src1", "xmlpipe")
source.xmlpipe_command = "ls /dev/null"
index = Riddle::Configuration::Index.new("index1")
index.path = "/path/to/index1"
index.sources << source
config.indices << index
generated_conf = config.render
generated_conf.should match(/index index1/)
generated_conf.should match(/source src1/)
generated_conf.should match(/indexer/)
generated_conf.should match(/searchd/)
end
end | ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/unit/filter_spec.rb | spec/unit/filter_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Client::Filter do
it "should render a filter that uses an array of ints correctly" do
filter = Riddle::Client::Filter.new("field", [1, 2, 3])
filter.query_message.should == query_contents(:filter_array)
end
it "should render a filter that has exclude set correctly" do
filter = Riddle::Client::Filter.new("field", [1, 2, 3], true)
filter.query_message.should == query_contents(:filter_array_exclude)
end
it "should render a filter that is a range of ints correctly" do
filter = Riddle::Client::Filter.new("field", 1..3)
filter.query_message.should == query_contents(:filter_range)
end
it "should render a filter that is a range of ints as exclude correctly" do
filter = Riddle::Client::Filter.new("field", 1..3, true)
filter.query_message.should == query_contents(:filter_range_exclude)
end
it "should render a filter that is a range of floats correctly" do
filter = Riddle::Client::Filter.new("field", 5.4..13.5)
filter.query_message.should == query_contents(:filter_floats)
end
it "should render a filter that is a range of floats as exclude correctly" do
filter = Riddle::Client::Filter.new("field", 5.4..13.5, true)
filter.query_message.should == query_contents(:filter_floats_exclude)
end
it "should render a filter that is an array of boolean values correctly" do
filter = Riddle::Client::Filter.new("field", [false, true])
filter.query_message.should == query_contents(:filter_boolean)
end
end | ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/unit/configuration/common_spec.rb | spec/unit/configuration/common_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Configuration::Common do
it "should always be valid" do
common = Riddle::Configuration::Common.new
common.should be_valid
end
it "should support Sphinx's common settings" do
settings = %w( lemmatizer_base on_json_attr_error json_autoconv_numbers
json_autoconv_keynames rlp_root rlp_environment rlp_max_batch_size
rlp_max_batch_docs )
common = Riddle::Configuration::Common.new
settings.each do |setting|
common.should respond_to(setting.to_sym)
common.should respond_to("#{setting}=".to_sym)
end
end
it "should render a correct configuration" do
common = Riddle::Configuration::Common.new
common.common_sphinx_configuration = true
common.render.should == <<-COMMON
common
{
}
COMMON
common.lemmatizer_base = "/tmp"
common.render.should == <<-COMMON
common
{
lemmatizer_base = /tmp
}
COMMON
end
it "should not be present when common_sphinx_configuration is not set" do
common = Riddle::Configuration::Common.new
common.render.should be_nil
end
it "should not be present when common_sphinx_configuration is false" do
common = Riddle::Configuration::Common.new
common.common_sphinx_configuration = false
common.render.should be_nil
end
it "should render when common_sphinx_configuration is true" do
common = Riddle::Configuration::Common.new
common.common_sphinx_configuration = true
common.render.should == <<-COMMON
common
{
}
COMMON
end
end | ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/unit/configuration/source_spec.rb | spec/unit/configuration/source_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Configuration::Source do
#
end | ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/unit/configuration/realtime_index_spec.rb | spec/unit/configuration/realtime_index_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Configuration::RealtimeIndex do
let(:index) { Riddle::Configuration::RealtimeIndex.new('rt1') }
describe '#valid?' do
it "should not be valid without a name" do
index.name = nil
index.path = 'foo'
index.should_not be_valid
end
it "should not be valid without a path" do
index.path = nil
index.should_not be_valid
end
it "should be valid with a name and path" do
index.path = 'foo'
index.should be_valid
end
end
describe '#type' do
it "should be 'rt'" do
index.type.should == 'rt'
end
end
describe '#render' do
it "should raise a ConfigurationError if rendering when not valid" do
lambda {
index.render
}.should raise_error(Riddle::Configuration::ConfigurationError)
end
it "should render correctly if supplied settings are valid" do
index.path = '/var/data/rt'
index.rt_mem_limit = '512M'
index.rt_field << 'title' << 'content'
index.rt_attr_uint << 'gid'
index.rt_attr_bigint << 'guid'
index.rt_attr_float << 'gpa'
index.rt_attr_timestamp << 'ts_added'
index.rt_attr_string << 'author'
index.render.should == <<-RTINDEX
index rt1
{
type = rt
path = /var/data/rt
rt_mem_limit = 512M
rt_field = title
rt_field = content
rt_attr_uint = gid
rt_attr_bigint = guid
rt_attr_float = gpa
rt_attr_timestamp = ts_added
rt_attr_string = author
}
RTINDEX
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/unit/configuration/distributed_index_spec.rb | spec/unit/configuration/distributed_index_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Configuration::DistributedIndex do
it "should not be valid without any indices" do
index = Riddle::Configuration::DistributedIndex.new("dist1")
index.should_not be_valid
end
it "should be valid with just local indices" do
index = Riddle::Configuration::DistributedIndex.new("dist1")
index.local_indices << "local_one"
index.should be_valid
end
it "should be valid with just remote indices" do
index = Riddle::Configuration::DistributedIndex.new("dist1")
index.remote_indices << Riddle::Configuration::RemoteIndex.new("local", 3312, "remote_one")
index.should be_valid
end
it "should be of type 'distributed'" do
index = Riddle::Configuration::DistributedIndex.new("dist1")
index.type.should == 'distributed'
end
it "should raise a ConfigurationError if rendering when not valid" do
index = Riddle::Configuration::DistributedIndex.new("dist1")
lambda { index.render }.should raise_error(Riddle::Configuration::ConfigurationError)
end
it "should render correctly if supplied settings are valid" do
index = Riddle::Configuration::DistributedIndex.new("dist1")
index.local_indices << "test1" << "test1stemmed"
index.remote_indices <<
Riddle::Configuration::RemoteIndex.new("localhost", 3313, "remote1") <<
Riddle::Configuration::RemoteIndex.new("localhost", 3314, "remote2") <<
Riddle::Configuration::RemoteIndex.new("localhost", 3314, "remote3")
index.agent_blackhole << "testbox:3312:testindex1,testindex2"
index.agent_connect_timeout = 1000
index.agent_query_timeout = 3000
index.render.should == <<-DISTINDEX
index dist1
{
type = distributed
local = test1
local = test1stemmed
agent = localhost:3313:remote1
agent = localhost:3314:remote2,remote3
agent_blackhole = testbox:3312:testindex1,testindex2
agent_connect_timeout = 1000
agent_query_timeout = 3000
}
DISTINDEX
end
end | ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/unit/configuration/tsv_source_spec.rb | spec/unit/configuration/tsv_source_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Configuration::TSVSource do
it "should be invalid without an tsvpipe command, name and type if there's no parent" do
source = Riddle::Configuration::TSVSource.new("tsv1")
source.should_not be_valid
source.tsvpipe_command = "ls /var/null"
source.should be_valid
source.name = nil
source.should_not be_valid
source.name = "tsv1"
source.type = nil
source.should_not be_valid
end
it "should be invalid without only a name and type if there is a parent" do
source = Riddle::Configuration::TSVSource.new("tsv1")
source.should_not be_valid
source.parent = "tsvparent"
source.should be_valid
source.name = nil
source.should_not be_valid
source.name = "tsv1"
source.type = nil
source.should_not be_valid
end
it "should raise a ConfigurationError if rendering when not valid" do
source = Riddle::Configuration::TSVSource.new("tsv1")
lambda {
source.render
}.should raise_error(Riddle::Configuration::ConfigurationError)
end
it "should render correctly when valid" do
source = Riddle::Configuration::TSVSource.new("tsv1")
source.tsvpipe_command = "ls /var/null"
source.render.should == <<-TSVSOURCE
source tsv1
{
type = tsvpipe
tsvpipe_command = ls /var/null
}
TSVSOURCE
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/unit/configuration/indexer_spec.rb | spec/unit/configuration/indexer_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Configuration::Indexer do
it "should always be valid" do
indexer = Riddle::Configuration::Indexer.new
indexer.should be_valid
end
it "should support Sphinx's indexer settings" do
settings = %w( mem_limit max_iops max_iosize )
indexer = Riddle::Configuration::Indexer.new
settings.each do |setting|
indexer.should respond_to(setting.to_sym)
indexer.should respond_to("#{setting}=".to_sym)
end
end
it "should render a correct configuration" do
indexer = Riddle::Configuration::Indexer.new
indexer.render.should == <<-INDEXER
indexer
{
}
INDEXER
indexer.mem_limit = "32M"
indexer.render.should == <<-INDEXER
indexer
{
mem_limit = 32M
}
INDEXER
end
it "should render shared settings when common_sphinx_configuration is not set" do
indexer = Riddle::Configuration::Indexer.new
indexer.rlp_root = '/tmp'
indexer.render.should == <<-INDEXER
indexer
{
rlp_root = /tmp
}
INDEXER
end
it "should render shared settings when common_sphinx_configuration is false" do
indexer = Riddle::Configuration::Indexer.new
indexer.common_sphinx_configuration = false
indexer.rlp_root = '/tmp'
indexer.render.should == <<-INDEXER
indexer
{
rlp_root = /tmp
}
INDEXER
end
it "should not render shared settings when common_sphinx_configuration is true" do
indexer = Riddle::Configuration::Indexer.new
indexer.common_sphinx_configuration = true
indexer.rlp_root = '/tmp'
indexer.render.should == <<-INDEXER
indexer
{
}
INDEXER
end
end | ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/unit/configuration/template_index_spec.rb | spec/unit/configuration/template_index_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Configuration::TemplateIndex do
it "should be invalid without a name" do
index = Riddle::Configuration::TemplateIndex.new(nil)
index.should_not be_valid
index.name = "test1"
index.should be_valid
end
it "should raise a ConfigurationError if rendering when not valid" do
index = Riddle::Configuration::TemplateIndex.new(nil)
lambda {
index.render
}.should raise_error(Riddle::Configuration::ConfigurationError)
end
it "should render correctly if supplied settings are valid" do
index = Riddle::Configuration::TemplateIndex.new("test1")
index.docinfo = "extern"
index.mlock = 0
index.morphologies << "stem_en" << "stem_ru" << "soundex"
index.min_stemming_len = 1
index.stopword_files << "/var/data/stopwords.txt" << "/var/data/stopwords2.txt"
index.wordform_files << "/var/data/wordforms.txt"
index.exception_files << "/var/data/exceptions.txt"
index.min_word_len = 1
index.charset_type = "utf-8"
index.charset_table = "0..9, A..Z->a..z, _, a..z, U+410..U+42F->U+430..U+44F, U+430..U+44F"
index.ignore_characters << "U+00AD"
index.min_prefix_len = 0
index.min_infix_len = 0
index.prefix_field_names << "filename"
index.infix_field_names << "url" << "domain"
index.enable_star = true
index.ngram_len = 1
index.ngram_characters << "U+3000..U+2FA1F"
index.phrase_boundaries << "." << "?" << "!" << "U+2026"
index.phrase_boundary_step = 100
index.html_strip = 0
index.html_index_attrs = "img=alt,title; a=title"
index.html_remove_element_tags << "style" << "script"
index.preopen = 1
index.ondisk_dict = 1
index.inplace_enable = 1
index.inplace_hit_gap = 0
index.inplace_docinfo_gap = 0
index.inplace_reloc_factor = 0.1
index.inplace_write_factor = 0.1
index.index_exact_words = 1
index.render.should == <<-INDEX
index test1
{
type = template
docinfo = extern
mlock = 0
morphology = stem_en, stem_ru, soundex
min_stemming_len = 1
stopwords = /var/data/stopwords.txt /var/data/stopwords2.txt
wordforms = /var/data/wordforms.txt
exceptions = /var/data/exceptions.txt
min_word_len = 1
charset_type = utf-8
charset_table = 0..9, A..Z->a..z, _, a..z, U+410..U+42F->U+430..U+44F, U+430..U+44F
ignore_chars = U+00AD
min_prefix_len = 0
min_infix_len = 0
prefix_fields = filename
infix_fields = url, domain
enable_star = 1
ngram_len = 1
ngram_chars = U+3000..U+2FA1F
phrase_boundary = ., ?, !, U+2026
phrase_boundary_step = 100
html_strip = 0
html_index_attrs = img=alt,title; a=title
html_remove_elements = style, script
preopen = 1
ondisk_dict = 1
inplace_enable = 1
inplace_hit_gap = 0
inplace_docinfo_gap = 0
inplace_reloc_factor = 0.1
inplace_write_factor = 0.1
index_exact_words = 1
}
INDEX
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/unit/configuration/searchd_spec.rb | spec/unit/configuration/searchd_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Configuration::Searchd do
if Riddle.loaded_version.to_f >= 0.9
it "should be invalid without a listen or pid_file" do
searchd = Riddle::Configuration::Searchd.new
searchd.should_not be_valid
searchd.port = 3312
searchd.should_not be_valid
searchd.pid_file = "file.pid"
searchd.should be_valid
searchd.port = nil
searchd.listen = nil
searchd.should_not be_valid
searchd.listen = "localhost:3312"
searchd.should be_valid
end
else
it "should be invalid without a port or pid_file" do
searchd = Riddle::Configuration::Searchd.new
searchd.should_not be_valid
searchd.port = 3312
searchd.should_not be_valid
searchd.pid_file = "file.pid"
searchd.should be_valid
searchd.port = nil
searchd.should_not be_valid
end
end
it "should raise a ConfigurationError if rendering but not valid" do
searchd = Riddle::Configuration::Searchd.new
searchd.should_not be_valid
lambda { searchd.render }.should raise_error(Riddle::Configuration::ConfigurationError)
end
it "should support Sphinx's searchd settings" do
settings = %w( listen address port log query_log read_timeout
client_timeout max_children pid_file max_matches seamless_rotate
preopen_indexes unlink_old attr_flush_period ondisk_dict_default
max_packet_size mva_updates_pool crash_log_path max_filters
max_filter_values )
searchd = Riddle::Configuration::Searchd.new
settings.each do |setting|
searchd.should respond_to(setting.to_sym)
searchd.should respond_to("#{setting}=".to_sym)
end
end
it "should support setting listen to a port number" do
searchd = Riddle::Configuration::Searchd.new
searchd.port = 3312
searchd.pid_file = "file.pid"
searchd.listen = 3312
if Riddle.loaded_version.to_f >= 0.9
searchd.render.should == <<-SEARCHD
searchd
{
listen = 3312
pid_file = file.pid
}
SEARCHD
else
searchd.render.should == <<-SEARCHD
searchd
{
port = 3312
pid_file = file.pid
}
SEARCHD
end
end
it "should render a correct configuration with valid settings" do
searchd = Riddle::Configuration::Searchd.new
searchd.port = 3312
searchd.pid_file = "file.pid"
if Riddle.loaded_version.to_f >= 0.9
searchd.render.should == <<-SEARCHD
searchd
{
listen = 3312
pid_file = file.pid
}
SEARCHD
else
searchd.render.should == <<-SEARCHD
searchd
{
port = 3312
pid_file = file.pid
}
SEARCHD
end
end
it "should render with a client key if one is provided" do
searchd = Riddle::Configuration::Searchd.new
searchd.port = 3312
searchd.pid_file = 'file.pid'
searchd.client_key = 'secret'
if Riddle.loaded_version.to_f >= 0.9
searchd.render.should == <<-SEARCHD
searchd
{
listen = 3312
pid_file = file.pid
client_key = secret
}
SEARCHD
else
searchd.render.should == <<-SEARCHD
searchd
{
port = 3312
pid_file = file.pid
client_key = secret
}
SEARCHD
end
end
if Riddle.loaded_version.to_f >= 0.9
it "should render with mysql41 on the default port if true" do
searchd = Riddle::Configuration::Searchd.new
searchd.mysql41 = true
searchd.pid_file = 'file.pid'
searchd.render.should == <<-SEARCHD
searchd
{
listen = 9306:mysql41
pid_file = file.pid
}
SEARCHD
end
it "should render with mysql41 on a given port" do
searchd = Riddle::Configuration::Searchd.new
searchd.mysql41 = 9307
searchd.pid_file = 'file.pid'
searchd.render.should == <<-SEARCHD
searchd
{
listen = 9307:mysql41
pid_file = file.pid
}
SEARCHD
end
it "allows for both normal and mysql41 connections" do
searchd = Riddle::Configuration::Searchd.new
searchd.mysql41 = true
searchd.port = 9312
searchd.pid_file = 'file.pid'
searchd.render.should == <<-SEARCHD
searchd
{
listen = 9312
listen = 9306:mysql41
pid_file = file.pid
}
SEARCHD
end
it "uses given address for mysql41 connections" do
searchd = Riddle::Configuration::Searchd.new
searchd.mysql41 = true
searchd.address = '127.0.0.1'
searchd.pid_file = 'file.pid'
searchd.render.should == <<-SEARCHD
searchd
{
listen = 127.0.0.1:9306:mysql41
pid_file = file.pid
}
SEARCHD
end
it "applies the given address to both normal and mysql41 connections" do
searchd = Riddle::Configuration::Searchd.new
searchd.mysql41 = true
searchd.port = 9312
searchd.address = 'sphinx.server.local'
searchd.pid_file = 'file.pid'
searchd.render.should == <<-SEARCHD
searchd
{
listen = sphinx.server.local:9312
listen = sphinx.server.local:9306:mysql41
pid_file = file.pid
}
SEARCHD
end
it 'maintains the address and port settings without rendering them' do
searchd = Riddle::Configuration::Searchd.new
searchd.port = 9312
searchd.address = 'sphinx.server.local'
searchd.pid_file = 'file.pid'
searchd.render.should == <<-SEARCHD
searchd
{
listen = sphinx.server.local:9312
pid_file = file.pid
}
SEARCHD
searchd.address.should == 'sphinx.server.local'
searchd.port.should == 9312
end
it "respects the socket setting" do
searchd = Riddle::Configuration::Searchd.new
searchd.socket = "/my/socket"
searchd.pid_file = "file.pid"
searchd.render.should == <<-SEARCHD
searchd
{
listen = /my/socket
pid_file = file.pid
}
SEARCHD
end
it "respects multiple socket values" do
searchd = Riddle::Configuration::Searchd.new
searchd.socket = ["/my/socket.binary", "/my/socket.sphinxql:mysql41"]
searchd.pid_file = "file.pid"
searchd.render.should == <<-SEARCHD
searchd
{
listen = /my/socket.binary
listen = /my/socket.sphinxql:mysql41
pid_file = file.pid
}
SEARCHD
end
it "does not prefix addresses to sockets" do
searchd = Riddle::Configuration::Searchd.new
searchd.socket = "/my/socket"
searchd.address = "1.1.1.1"
searchd.pid_file = "file.pid"
searchd.render.should == <<-SEARCHD
searchd
{
listen = 1.1.1.1
listen = /my/socket
pid_file = file.pid
}
SEARCHD
end
it "handles socket and port settings" do
searchd = Riddle::Configuration::Searchd.new
searchd.socket = "/my/socket"
searchd.port = 9312
searchd.pid_file = "file.pid"
searchd.render.should == <<-SEARCHD
searchd
{
listen = 9312
listen = /my/socket
pid_file = file.pid
}
SEARCHD
end
it "handles socket and mysql41 settings" do
searchd = Riddle::Configuration::Searchd.new
searchd.socket = "/my/socket"
searchd.mysql41 = 9307
searchd.pid_file = "file.pid"
searchd.render.should == <<-SEARCHD
searchd
{
listen = 9307:mysql41
listen = /my/socket
pid_file = file.pid
}
SEARCHD
searchd = Riddle::Configuration::Searchd.new
searchd.socket = "/my/socket"
searchd.mysql41 = true
searchd.pid_file = "file.pid"
searchd.render.should == <<-SEARCHD
searchd
{
listen = 9306:mysql41
listen = /my/socket
pid_file = file.pid
}
SEARCHD
end
it "handles socket, address and port settings" do
searchd = Riddle::Configuration::Searchd.new
searchd.socket = "/my/socket"
searchd.address = "1.1.1.1"
searchd.port = 9312
searchd.pid_file = "file.pid"
searchd.render.should == <<-SEARCHD
searchd
{
listen = 1.1.1.1:9312
listen = /my/socket
pid_file = file.pid
}
SEARCHD
end
it "handles socket, address and mysql41 settings" do
searchd = Riddle::Configuration::Searchd.new
searchd.socket = "/my/socket"
searchd.address = "1.1.1.1"
searchd.mysql41 = 9312
searchd.pid_file = "file.pid"
searchd.render.should == <<-SEARCHD
searchd
{
listen = 1.1.1.1:9312:mysql41
listen = /my/socket
pid_file = file.pid
}
SEARCHD
searchd = Riddle::Configuration::Searchd.new
searchd.socket = "/my/socket"
searchd.address = "1.1.1.1"
searchd.mysql41 = true
searchd.pid_file = "file.pid"
searchd.render.should == <<-SEARCHD
searchd
{
listen = 1.1.1.1:9306:mysql41
listen = /my/socket
pid_file = file.pid
}
SEARCHD
end
it "handles socket, address, port and mysql41 settings" do
searchd = Riddle::Configuration::Searchd.new
searchd.socket = "/my/socket"
searchd.address = "1.1.1.1"
searchd.port = 9312
searchd.mysql41 = true
searchd.pid_file = "file.pid"
searchd.render.should == <<-SEARCHD
searchd
{
listen = 1.1.1.1:9312
listen = 1.1.1.1:9306:mysql41
listen = /my/socket
pid_file = file.pid
}
SEARCHD
searchd = Riddle::Configuration::Searchd.new
searchd.socket = "/my/socket"
searchd.address = "1.1.1.1"
searchd.port = 9312
searchd.mysql41 = 9307
searchd.pid_file = "file.pid"
searchd.render.should == <<-SEARCHD
searchd
{
listen = 1.1.1.1:9312
listen = 1.1.1.1:9307:mysql41
listen = /my/socket
pid_file = file.pid
}
SEARCHD
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/unit/configuration/index_spec.rb | spec/unit/configuration/index_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Configuration::DistributedIndex do
it "should be invalid without a name, sources or path if there's no parent" do
index = Riddle::Configuration::Index.new(nil)
index.should_not be_valid
index.name = "test1"
index.should_not be_valid
index.sources << Riddle::Configuration::SQLSource.new("source", "mysql")
index.should_not be_valid
index.path = "a/path"
index.should be_valid
index.name = nil
index.should_not be_valid
index.name = "test1"
index.sources.clear
index.should_not be_valid
end
it "should be invalid without a name but not sources or path if it has a parent" do
index = Riddle::Configuration::Index.new(nil)
index.should_not be_valid
index.name = "test1stemmed"
index.should_not be_valid
index.parent = "test1"
index.should be_valid
end
it "should raise a ConfigurationError if rendering when not valid" do
index = Riddle::Configuration::Index.new("test1")
lambda { index.render }.should raise_error(Riddle::Configuration::ConfigurationError)
end
it "should render correctly if supplied settings are valid" do
source = Riddle::Configuration::XMLSource.new("src1", "xmlpipe")
source.xmlpipe_command = "ls /dev/null"
index = Riddle::Configuration::Index.new("test1", source)
index.path = "/var/data/test1"
index.docinfo = "extern"
index.mlock = 0
index.morphologies << "stem_en" << "stem_ru" << "soundex"
index.min_stemming_len = 1
index.stopword_files << "/var/data/stopwords.txt" << "/var/data/stopwords2.txt"
index.wordform_files << "/var/data/wordforms.txt"
index.exception_files << "/var/data/exceptions.txt"
index.min_word_len = 1
index.charset_type = "utf-8"
index.charset_table = "0..9, A..Z->a..z, _, a..z, U+410..U+42F->U+430..U+44F, U+430..U+44F"
index.ignore_characters << "U+00AD"
index.min_prefix_len = 0
index.min_infix_len = 0
index.prefix_field_names << "filename"
index.infix_field_names << "url" << "domain"
index.enable_star = true
index.ngram_len = 1
index.ngram_characters << "U+3000..U+2FA1F"
index.phrase_boundaries << "." << "?" << "!" << "U+2026"
index.phrase_boundary_step = 100
index.html_strip = 0
index.html_index_attrs = "img=alt,title; a=title"
index.html_remove_element_tags << "style" << "script"
index.preopen = 1
index.ondisk_dict = 1
index.inplace_enable = 1
index.inplace_hit_gap = 0
index.inplace_docinfo_gap = 0
index.inplace_reloc_factor = 0.1
index.inplace_write_factor = 0.1
index.index_exact_words = 1
index.render.should == <<-INDEX
source src1
{
type = xmlpipe
xmlpipe_command = ls /dev/null
}
index test1
{
path = /var/data/test1
docinfo = extern
mlock = 0
morphology = stem_en, stem_ru, soundex
min_stemming_len = 1
stopwords = /var/data/stopwords.txt /var/data/stopwords2.txt
wordforms = /var/data/wordforms.txt
exceptions = /var/data/exceptions.txt
min_word_len = 1
charset_type = utf-8
charset_table = 0..9, A..Z->a..z, _, a..z, U+410..U+42F->U+430..U+44F, U+430..U+44F
ignore_chars = U+00AD
min_prefix_len = 0
min_infix_len = 0
prefix_fields = filename
infix_fields = url, domain
enable_star = 1
ngram_len = 1
ngram_chars = U+3000..U+2FA1F
phrase_boundary = ., ?, !, U+2026
phrase_boundary_step = 100
html_strip = 0
html_index_attrs = img=alt,title; a=title
html_remove_elements = style, script
preopen = 1
ondisk_dict = 1
inplace_enable = 1
inplace_hit_gap = 0
inplace_docinfo_gap = 0
inplace_reloc_factor = 0.1
inplace_write_factor = 0.1
index_exact_words = 1
source = src1
}
INDEX
end
end | ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/unit/configuration/sql_source_spec.rb | spec/unit/configuration/sql_source_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Configuration::SQLSource do
it "should be invalid without a host, user, database, and query if there's no parent" do
source = Riddle::Configuration::SQLSource.new("src1", "mysql")
source.should_not be_valid
source.sql_host = "localhost"
source.sql_user = "test"
source.sql_db = "test"
source.sql_query = "SELECT * FROM tables"
source.should be_valid
[:name, :type, :sql_host, :sql_user, :sql_db, :sql_query].each do |setting|
value = source.send(setting)
source.send("#{setting}=".to_sym, nil)
source.should_not be_nil
source.send("#{setting}=".to_sym, value)
end
end
it "should be invalid without only a name and type if there is a parent" do
source = Riddle::Configuration::SQLSource.new("src1", "mysql")
source.should_not be_valid
source.parent = "sqlparent"
source.should be_valid
source.name = nil
source.should_not be_valid
source.name = "src1"
source.type = nil
source.should_not be_valid
end
it "should raise a ConfigurationError if rendering when not valid" do
source = Riddle::Configuration::SQLSource.new("src1", "mysql")
lambda { source.render }.should raise_error(Riddle::Configuration::ConfigurationError)
end
it "should render correctly when valid" do
source = Riddle::Configuration::SQLSource.new("src1", "mysql")
source.sql_host = "localhost"
source.sql_user = "test"
source.sql_pass = ""
source.sql_db = "test"
source.sql_port = 3306
source.sql_sock = "/tmp/mysql.sock"
source.mysql_connect_flags = 32
source.sql_query_pre << "SET NAMES utf8" << "SET SESSION query_cache_type=OFF"
source.sql_query = "SELECT id, group_id, UNIX_TIMESTAMP(date_added) AS date_added, title, content FROM documents WHERE id >= $start AND id <= $end"
source.sql_query_range = "SELECT MIN(id), MAX(id) FROM documents"
source.sql_range_step = 1000
source.sql_query_killlist = "SELECT id FROM documents WHERE edited>=@last_reindex"
source.sql_attr_uint << "author_id" << "forum_id:9" << "group_id"
source.sql_attr_bool << "is_deleted"
source.sql_attr_bigint << "my_bigint_id"
source.sql_attr_timestamp << "posted_ts" << "last_edited_ts" << "date_added"
source.sql_attr_str2ordinal << "author_name"
source.sql_attr_float << "lat_radians" << "long_radians"
source.sql_attr_multi << "uint tag from query; select id, tag FROM tags"
source.sql_query_post = ""
source.sql_query_post_index = "REPLACE INTO counters (id, val) VALUES ('max_indexed_id', $maxid)"
source.sql_ranged_throttle = 0
source.sql_query_info = "SELECT * FROM documents WHERE id = $id"
source.mssql_winauth = 1
source.mssql_unicode = 1
source.unpack_zlib << "zlib_column"
source.unpack_mysqlcompress << "compressed_column" << "compressed_column_2"
source.unpack_mysqlcompress_maxsize = "16M"
source.render.should == <<-SQLSOURCE
source src1
{
type = mysql
sql_host = localhost
sql_user = test
sql_pass =
sql_db = test
sql_port = 3306
sql_sock = /tmp/mysql.sock
mysql_connect_flags = 32
sql_query_pre = SET NAMES utf8
sql_query_pre = SET SESSION query_cache_type=OFF
sql_query = SELECT id, group_id, UNIX_TIMESTAMP(date_added) AS date_added, title, content FROM documents WHERE id >= $start AND id <= $end
sql_query_range = SELECT MIN(id), MAX(id) FROM documents
sql_range_step = 1000
sql_query_killlist = SELECT id FROM documents WHERE edited>=@last_reindex
sql_attr_uint = author_id
sql_attr_uint = forum_id:9
sql_attr_uint = group_id
sql_attr_bool = is_deleted
sql_attr_bigint = my_bigint_id
sql_attr_timestamp = posted_ts
sql_attr_timestamp = last_edited_ts
sql_attr_timestamp = date_added
sql_attr_str2ordinal = author_name
sql_attr_float = lat_radians
sql_attr_float = long_radians
sql_attr_multi = uint tag from query; select id, tag FROM tags
sql_query_post =
sql_query_post_index = REPLACE INTO counters (id, val) VALUES ('max_indexed_id', $maxid)
sql_ranged_throttle = 0
sql_query_info = SELECT * FROM documents WHERE id = $id
mssql_winauth = 1
mssql_unicode = 1
unpack_zlib = zlib_column
unpack_mysqlcompress = compressed_column
unpack_mysqlcompress = compressed_column_2
unpack_mysqlcompress_maxsize = 16M
}
SQLSOURCE
end
it "should insert a backslash-newline into an sql_query when greater than 8178 characters" do
source = Riddle::Configuration::SQLSource.new("src1", "mysql")
source.sql_query = big_query_string[0, 8200]
source.parent = 'src0'
source.render.should match(/sql_query\s=\s[^\n]+\\\n/)
end
it "should insert two backslash-newlines into an sql_query when greater than 16,356 characters" do
source = Riddle::Configuration::SQLSource.new("src1", "mysql")
source.sql_query = big_query_string
source.parent = 'src0'
source.render.should match(/sql_query\s=\s[^\n]+\\\n[^\n]+\\\n/)
end
def big_query_string
return <<-SQL
SELECT MARLEY was dead to begin with There is no doubtwhatever about that The register of his burial wassigned by the clergyman the clerk the undertakerand the chief mourner Scrooge signed it andScrooges name was good upon Change for anything hechose to put his hand to Old Marley was as dead as adoornailMind I dont mean to say that I know of myown knowledge what there is particularly dead abouta doornail I might have been inclined myself toregard a coffinnail as the deadest piece of ironmongeryin the trade But the wisdom of our ancestorsis in the simile and my unhallowed handsshall not disturb it or the Countrys done for Youwill therefore permit me to repeat emphatically thatMarley was as dead as a doornailScrooge knew he was dead Of course he didHow could it be otherwise Scrooge and he werepartners for I dont know how many years Scroogewas his sole executor his sole administrator his soleassign his sole residuary legatee his sole friend andsole mourner And even Scrooge was not so dreadfullycut up by the sad event but that he was an excellentman of business on the very day of the funeraland solemnised it with an undoubted bargainThe mention of Marleys funeral brings me back tothe point I started from There is no doubt that Marleywas dead This must be distinctly understood ornothing wonderful can come of the story I am goingto relate If we were not perfectly convinced thatHamlets Father died before the play began therewould be nothing more remarkable in his taking astroll at night in an easterly wind upon his own rampartsthan there would be in any other middleagedgentleman rashly turning out after dark in a breezyspotsay Saint Pauls Churchyard for instanceliterally to astonish his sons weak mindScrooge never painted out Old Marleys nameThere it stood years afterwards above the warehousedoor Scrooge and Marley The firm was known asScrooge and Marley Sometimes people new to thebusiness called Scrooge Scrooge and sometimes Marleybut he answered to both names It was all thesame to himOh But he was a tightfisted hand at the grindstoneScrooge a squeezing wrenching grasping scrapingclutching covetous old sinner Hard and sharp as flintfrom which no steel had ever struck out generous firesecret and selfcontained and solitary as an oyster Thecold within him froze his old features nipped his pointednose shrivelled his cheek stiffened his gait made hiseyes red his thin lips blue and spoke out shrewdly in hisgrating voice A frosty rime was on his head and on hiseyebrows and his wiry chin He carried his own lowtemperature always about with him he iced his office inthe dogdays and didnt thaw it one degree at ChristmasExternal heat and cold had little influence onScrooge No warmth could warm no wintry weatherchill him No wind that blew was bitterer than heno falling snow was more intent upon its purpose nopelting rain less open to entreaty Foul weather didntknow where to have him The heaviest rain andsnow and hail and sleet could boast of the advantageover him in only one respect They often came downhandsomely and Scrooge never didNobody ever stopped him in the street to say withgladsome looks My dear Scrooge how are youWhen will you come to see me No beggars imploredhim to bestow a trifle no children asked himwhat it was oclock no man or woman ever once in allhis life inquired the way to such and such a place ofScrooge Even the blind mens dogs appeared toknow him and when they saw him coming on wouldtug their owners into doorways and up courts andthen would wag their tails as though they said Noeye at all is better than an evil eye dark masterBut what did Scrooge care It was the very thinghe liked To edge his way along the crowded pathsof life warning all human sympathy to keep its distancewas what the knowing ones call nuts to ScroogeOnce upon a timeof all the good days in the yearon Christmas Eveold Scrooge sat busy in hiscountinghouse It was cold bleak biting weather foggywithal and he could hear the people in the court outsidego wheezing up and down beating their handsupon their breasts and stamping their feet upon thepavement stones to warm them The city clocks hadonly just gone three but it was quite dark alreadyit had not been light all dayand candles were flaringin the windows of the neighbouring offices likeruddy smears upon the palpable brown air The fogcame pouring in at every chink and keyhole and wasso dense without that although the court was of thenarrowest the houses opposite were mere phantomsTo see the dingy cloud come drooping down obscuringeverything one might have thought that Naturelived hard by and was brewing on a large scaleThe door of Scrooges countinghouse was openthat he might keep his eye upon his clerk who in adismal little cell beyond a sort of tank was copyingletters Scrooge had a very small fire but the clerksfire was so very much smaller that it looked like onecoal But he couldnt replenish it for Scrooge keptthe coalbox in his own room and so surely as theclerk came in with the shovel the master predictedthat it would be necessary for them to part Whereforethe clerk put on his white comforter and tried towarm himself at the candle in which effort not beinga man of a strong imagination he failedA merry Christmas uncle God save you crieda cheerful voice It was the voice of Scroogesnephew who came upon him so quickly that this wasthe first intimation he had of his approachBah said Scrooge HumbugHe had so heated himself with rapid walking in thefog and frost this nephew of Scrooges that he wasall in a glow his face was ruddy and handsome hiseyes sparkled and his breath smoked againChristmas a humbug uncle said Scroogesnephew You dont mean that I am sureI do said Scrooge Merry Christmas Whatright have you to be merry What reason have youto be merry Youre poor enoughCome then returned the nephew gaily Whatright have you to be dismal What reason have youto be morose Youre rich enoughScrooge having no better answer ready on the spurof the moment said Bah again and followed it upwith HumbugDont be cross uncle said the nephewWhat else can I be returned the uncle when Ilive in such a world of fools as this Merry ChristmasOut upon merry Christmas Whats Christmastime to you but a time for paying bills withoutmoney a time for finding yourself a year older butnot an hour richer a time for balancing your booksand having every item in em through a round dozenof months presented dead against you If I couldwork my will said Scrooge indignantly every idiotwho goes about with Merry Christmas on his lipsshould be boiled with his own pudding and buriedwith a stake of holly through his heart He shouldUncle pleaded the nephewNephew returned the uncle sternly keep Christmasin your own way and let me keep it in mineKeep it repeated Scrooges nephew But youdont keep itLet me leave it alone then said Scrooge Muchgood may it do you Much good it has ever doneyouThere are many things from which I might havederived good by which I have not profited I daresay returned the nephew Christmas among therest But I am sure I have always thought of Christmastime when it has come roundapart from theveneration due to its sacred name and origin if anythingbelonging to it can be apart from thatas agood time a kind forgiving charitable pleasanttime the only time I know of in the long calendarof the year when men and women seem by one consentto open their shutup hearts freely and to thinkof people below them as if they really werefellowpassengers to the grave and not another raceof creatures bound on other journeys And thereforeuncle though it has never put a scrap of gold orsilver in my pocket I believe that it has done megood and will do me good and I say God bless itThe clerk in the Tank involuntarily applaudedBecoming immediately sensible of the improprietyhe poked the fire and extinguished the last frail sparkfor everLet me hear another sound from you saidScrooge and youll keep your Christmas by losingyour situation Youre quite a powerful speakersir he added turning to his nephew I wonder youdont go into ParliamentDont be angry uncle Come Dine with us tomorrowScrooge said that he would see himyes indeed hedid He went the whole length of the expressionand said that he would see him in that extremity firstBut why cried Scrooges nephew WhyWhy did you get married said ScroogeBecause I fell in loveBecause you fell in love growled Scrooge as ifthat were the only one thing in the world more ridiculousthan a merry Christmas Good afternoonNay uncle but you never came to see me beforethat happened Why give it as a reason for notcoming nowGood afternoon said ScroogeI want nothing from you I ask nothing of youwhy cannot we be friendsGood afternoon said ScroogeI am sorry with all my heart to find you soresolute We have never had any quarrel to which Ihave been a party But I have made the trial inhomage to Christmas and Ill keep my Christmashumour to the last So A Merry Christmas uncleGood afternoon said ScroogeAnd A Happy New YearGood afternoon said ScroogeHis nephew left the room without an angry wordnotwithstanding He stopped at the outer door tobestow the greetings of the season on the clerk whocold as he was was warmer than Scrooge for he returnedthem cordiallyTheres another fellow muttered Scrooge whooverheard him my clerk with fifteen shillings aweek and a wife and family talking about a merryChristmas Ill retire to BedlamThis lunatic in letting Scrooges nephew out hadlet two other people in They were portly gentlemenpleasant to behold and now stood with their hats offin Scrooges office They had books and papers intheir hands and bowed to himScrooge and Marleys I believe said one of thegentlemen referring to his list Have I the pleasureof addressing Mr Scrooge or Mr MarleyMr Marley has been dead these seven yearsScrooge replied He died seven years ago this verynightWe have no doubt his liberality is well representedby his surviving partner said the gentleman presentinghis credentialsIt certainly was for they had been two kindredspirits At the ominous word liberality Scroogefrowned and shook his head and handed the credentialsbackAt this festive season of the year Mr Scroogesaid the gentleman taking up a pen it is more thanusually desirable that we should make some slightprovision for the Poor and destitute who suffergreatly at the present time Many thousands are inwant of common necessaries hundreds of thousandsare in want of common comforts sirAre there no prisons asked ScroogePlenty of prisons said the gentleman laying downthe pen againAnd the Union workhouses demanded ScroogeAre they still in operationThey are Still returned the gentleman I wishI could say they were notThe Treadmill and the Poor Law are in full vigourthen said ScroogeBoth very busy sirOh I was afraid from what you said at firstthat something had occurred to stop them in theiruseful course said Scrooge Im very glad tohear itUnder the impression that they scarcely furnishChristian cheer of mind or body to the multitudereturned the gentleman a few of us are endeavouringto raise a fund to buy the Poor some meat and drinkand means of warmth We choose this time becauseit is a time of all others when Want is keenly feltand Abundance rejoices What shall I put you downforNothing Scrooge repliedYou wish to be anonymousI wish to be left alone said Scrooge Since youask me what I wish gentlemen that is my answerI dont make merry myself at Christmas and I cantafford to make idle people merry I help to supportthe establishments I have mentionedthey costenough and those who are badly off must go thereMany cant go there and many would rather dieIf they would rather die said Scrooge they hadbetter do it and decrease the surplus populationBesidesexcuse meI dont know thatBut you might know it observed the gentlemanIts not my business Scrooge returned Itsenough for a man to understand his own business andnot to interfere with other peoples Mine occupiesme constantly Good afternoon gentlemenSeeing clearly that it would be useless to pursuetheir point the gentlemen withdrew Scrooge resumedhis labours with an improved opinion of himselfand in a more facetious temper than was usualwith himMeanwhile the fog and darkness thickened so thatpeople ran about with flaring links proffering theirservices to go before horses in carriages and conductthem on their way The ancient tower of a churchwhose gruff old bell was always peeping slily downat Scrooge out of a Gothic window in the wall becameinvisible and struck the hours and quarters in theclouds with tremulous vibrations afterwards as ifits teeth were chattering in its frozen head up thereThe cold became intense In the main street at thecorner of the court some labourers were repairingthe gaspipes and had lighted a great fire in a brazierround which a party of ragged men and boys weregathered warming their hands and winking theireyes before the blaze in rapture The waterplugbeing left in solitude its overflowings sullenly congealedand turned to misanthropic ice The brightnessof the shops where holly sprigs and berriescrackled in the lamp heat of the windows made palefaces ruddy as they passed Poulterers and grocerstrades became a splendid joke a glorious pageantwith which it was next to impossible to believe thatsuch dull principles as bargain and sale had anythingto do The Lord Mayor in the stronghold of themighty Mansion House gave orders to his fifty cooksand butlers to keep Christmas as a Lord Mayorshousehold should and even the little tailor whom hehad fined five shillings on the previous Monday forbeing drunk and bloodthirsty in the streets stirred uptomorrows pudding in his garret while his leanwife and the baby sallied out to buy the beefFoggier yet and colder Piercing searching bitingcold If the good Saint Dunstan had but nippedthe Evil Spirits nose with a touch of such weatheras that instead of using his familiar weapons thenindeed he would have roared to lusty purpose Theowner of one scant young nose gnawed and mumbledby the hungry cold as bones are gnawed by dogsstooped down at Scrooges keyhole to regale him witha Christmas carol but at the first sound of God bless you merry gentleman May nothing you dismayScrooge seized the ruler with such energy of actionthat the singer fled in terror leaving the keyhole tothe fog and even more congenial frostAt length the hour of shutting up the countinghousearrived With an illwill Scrooge dismounted from hisstool and tacitly admitted the fact to the expectantclerk in the Tank who instantly snuffed his candle outand put on his hatYoull want all day tomorrow I suppose saidScroogeIf quite convenient sirIts not convenient said Scrooge and its notfair If I was to stop halfacrown for it youdthink yourself illused Ill be boundThe clerk smiled faintlyAnd yet said Scrooge you dont think me illusedwhen I pay a days wages for no workThe clerk observed that it was only once a yearA poor excuse for picking a mans pocket everytwentyfifth of December said Scrooge buttoninghis greatcoat to the chin But I suppose you musthave the whole day Be here all the earlier nextmorningThe clerk promised that he would and Scroogewalked out with a growl The office was closed in atwinkling and the clerk with the long ends of hiswhite comforter dangling below his waist for heboasted no greatcoat went down a slide on Cornhillat the end of a lane of boys twenty times inhonour of its being Christmas Eve and then ran hometo Camden Town as hard as he could pelt to playat blindmansbuffScrooge took his melancholy dinner in his usualmelancholy tavern and having read all the newspapers andbeguiled the rest of the evening with hisbankersbook went home to bed He lived inchambers which had once belonged to his deceasedpartner They were a gloomy suite of rooms in alowering pile of building up a yard where it had solittle business to be that one could scarcely helpfancying it must have run there when it was a younghouse playing at hideandseek with other housesand forgotten the way out again It was old enoughnow and dreary enough for nobody lived in it butScrooge the other rooms being all let out as officesThe yard was so dark that even Scrooge who knewits every stone was fain to grope with his handsThe fog and frost so hung about the black old gatewayof the house that it seemed as if the Genius ofthe Weather sat in mournful meditation on thethresholdNow it is a fact that there was nothing at allparticular about the knocker on the door except that itwas very large It is also a fact that Scrooge hadseen it night and morning during his whole residencein that place also that Scrooge had as little of whatis called fancy about him as any man in the city ofLondon even includingwhich is a bold wordthecorporation aldermen and livery Let it also beborne in mind that Scrooge had not bestowed onethought on Marley since his last mention of hisseven years dead partner that afternoon And thenlet any man explain to me if he can how it happenedthat Scrooge having his key in the lock of the doorsaw in the knocker without its undergoing any intermediateprocess of changenot a knocker but Marleys faceMarleys face It was not in impenetrable shadowas the other objects in the yard were but had adismal light about it like a bad lobster in a darkcellar It was not angry or ferocious but lookedat Scrooge as Marley used to look with ghostlyspectacles turned up on its ghostly forehead Thehair was curiously stirred as if by breath or hot airand though the eyes were wide open they were perfectlymotionless FROM documents
SQL
end
end | ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/unit/configuration/xml_source_spec.rb | spec/unit/configuration/xml_source_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Configuration::XMLSource do
it "should be invalid without an xmlpipe command, name and type if there's no parent" do
source = Riddle::Configuration::XMLSource.new("xml1", "xmlpipe")
source.should_not be_valid
source.xmlpipe_command = "ls /var/null"
source.should be_valid
source.name = nil
source.should_not be_valid
source.name = "xml1"
source.type = nil
source.should_not be_valid
end
it "should be invalid without only a name and type if there is a parent" do
source = Riddle::Configuration::XMLSource.new("xml1", "xmlpipe")
source.should_not be_valid
source.parent = "xmlparent"
source.should be_valid
source.name = nil
source.should_not be_valid
source.name = "xml1"
source.type = nil
source.should_not be_valid
end
it "should raise a ConfigurationError if rendering when not valid" do
source = Riddle::Configuration::XMLSource.new("xml1", "xmlpipe")
lambda { source.render }.should raise_error(Riddle::Configuration::ConfigurationError)
end
it "should render correctly when valid" do
source = Riddle::Configuration::XMLSource.new("xml1", "xmlpipe")
source.xmlpipe_command = "ls /var/null"
source.render.should == <<-XMLSOURCE
source xml1
{
type = xmlpipe
xmlpipe_command = ls /var/null
}
XMLSOURCE
end
end | ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/riddle/auto_version_spec.rb | spec/riddle/auto_version_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::AutoVersion do
describe '.configure' do
before :each do
@controller = Riddle::Controller.new stub('configuration'), 'sphinx.conf'
Riddle::Controller.stub(:new => @controller)
unless ENV['SPHINX_VERSION'].nil?
@env_version, ENV['SPHINX_VERSION'] = ENV['SPHINX_VERSION'].dup, nil
end
end
after :each do
ENV['SPHINX_VERSION'] = @env_version unless @env_version.nil?
end
it "should require 0.9.8 if that is the known version" do
Riddle::AutoVersion.should_receive(:require).with('riddle/0.9.8')
@controller.stub(:sphinx_version => '0.9.8')
Riddle::AutoVersion.configure
end
it "should require 0.9.9 if that is the known version" do
Riddle::AutoVersion.should_receive(:require).with('riddle/0.9.9')
@controller.stub(:sphinx_version => '0.9.9')
Riddle::AutoVersion.configure
end
it "should require 1.10 if that is the known version" do
Riddle::AutoVersion.should_receive(:require).with('riddle/1.10')
@controller.stub(:sphinx_version => '1.10-beta')
Riddle::AutoVersion.configure
end
it "should require 1.10 if using 1.10 with 64 bit IDs" do
Riddle::AutoVersion.should_receive(:require).with('riddle/1.10')
@controller.stub(:sphinx_version => '1.10-id64-beta')
Riddle::AutoVersion.configure
end
it "should require 2.0.1 if that is the known version" do
Riddle::AutoVersion.should_receive(:require).with('riddle/2.0.1')
@controller.stub(:sphinx_version => '2.0.1-beta')
Riddle::AutoVersion.configure
end
it "should require 2.0.1 if 2.0.2-dev is being used" do
Riddle::AutoVersion.should_receive(:require).with('riddle/2.0.1')
@controller.stub(:sphinx_version => '2.0.2-dev')
Riddle::AutoVersion.configure
end
it "should require 2.1.0 if 2.0.3 is being used" do
Riddle::AutoVersion.should_receive(:require).with('riddle/2.1.0')
@controller.stub(:sphinx_version => '2.0.3-release')
Riddle::AutoVersion.configure
end
it "should require 2.1.0 if 2.0.4 is being used" do
Riddle::AutoVersion.should_receive(:require).with('riddle/2.1.0')
@controller.stub(:sphinx_version => '2.0.4-release')
Riddle::AutoVersion.configure
end
it "should require 2.1.0 if 2.0.5 is being used" do
Riddle::AutoVersion.should_receive(:require).with('riddle/2.1.0')
@controller.stub(:sphinx_version => '2.0.5-release')
Riddle::AutoVersion.configure
end
it "should require 2.1.0 if 2.2.1 is being used" do
Riddle::AutoVersion.should_receive(:require).with('riddle/2.1.0')
@controller.stub(:sphinx_version => '2.2.1-beta')
Riddle::AutoVersion.configure
end
it "should require 2.1.0 if that is the known version" do
Riddle::AutoVersion.should_receive(:require).with('riddle/2.1.0')
@controller.stub(:sphinx_version => '2.1.0-dev')
Riddle::AutoVersion.configure
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/riddle/client_spec.rb | spec/riddle/client_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Client do
describe '#initialize' do
it "should check the loaded Sphinx version" do
Riddle.should_receive(:version_warning)
Riddle::Client.new
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/riddle/query_spec.rb | spec/riddle/query_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Query, :live => true do
describe '.connection' do
let(:connection) { Riddle::Query.connection 'localhost', 9306 }
it "returns a MySQL Client" do
connection.should be_a(Mysql2::Client)
end
it "should handle search requests" do
connection.query(Riddle::Query.tables).to_a.should match_array([
{'Index' => 'people', 'Type' => 'local'},
{'Index' => 'article_core', 'Type' => 'local'},
{'Index' => 'article_delta', 'Type' => 'local'}
])
end
end
end unless RUBY_PLATFORM == 'java' || Riddle.loaded_version.to_i < 2
describe Riddle::Query do
describe '.set' do
it 'handles a single value' do
Riddle::Query.set('foo', 'bar').should == 'SET GLOBAL foo = bar'
end
it 'handles multiple values' do
Riddle::Query.set('foo', [1, 2, 3]).should == 'SET GLOBAL foo = (1, 2, 3)'
end
it 'handles non-global settings' do
Riddle::Query.set('foo', 'bar', false).should == 'SET foo = bar'
end
end
describe '.snippets' do
it 'handles a basic request' do
Riddle::Query.snippets('foo bar baz', 'foo_core', 'foo').
should == "CALL SNIPPETS('foo bar baz', 'foo_core', 'foo')"
end
it 'handles a request with options' do
Riddle::Query.snippets('foo bar baz', 'foo_core', 'foo', :around => 5).
should == "CALL SNIPPETS('foo bar baz', 'foo_core', 'foo', 5 AS around)"
end
it 'handles string options' do
Riddle::Query.snippets('foo bar baz', 'foo_core', 'foo',
:before_match => '<strong>').should == "CALL SNIPPETS('foo bar baz', 'foo_core', 'foo', '<strong>' AS before_match)"
end
it "handles boolean options" do
Riddle::Query.snippets('foo bar baz', 'foo_core', 'foo',
:exact_phrase => true).should == "CALL SNIPPETS('foo bar baz', 'foo_core', 'foo', 1 AS exact_phrase)"
end
it "escapes quotes in the text data" do
Riddle::Query.snippets("foo bar 'baz", 'foo_core', 'foo').
should == "CALL SNIPPETS('foo bar \\'baz', 'foo_core', 'foo')"
end
it "escapes quotes in the query data" do
Riddle::Query.snippets("foo bar baz", 'foo_core', "foo'").
should == "CALL SNIPPETS('foo bar baz', 'foo_core', 'foo\\'')"
end
end
describe '.create_function' do
it 'handles a basic create request' do
Riddle::Query.create_function('foo', :bigint, 'foo.sh').
should == "CREATE FUNCTION foo RETURNS BIGINT SONAME 'foo.sh'"
end
end
describe '.update' do
it 'handles a basic update request' do
Riddle::Query.update('foo_core', 5, :deleted => 1).
should == 'UPDATE foo_core SET deleted = 1 WHERE id = 5'
end
end
describe '.escape' do
%w(( ) | - ! @ ~ / ^ $ " > < ?).each do |reserved|
it "escapes #{reserved}" do
Riddle::Query.escape(reserved).should == "\\#{reserved}"
end
end
it "escapes word-operators correctly" do
operators = ['MAYBE', 'NEAR', 'PARAGRAPH', 'SENTENCE', 'ZONE', 'ZONESPAN']
operators.each do |operator|
base = "string with #{operator} operator"
Riddle::Query.escape(base).should == base.gsub(operator, "\\#{operator}")
end
Riddle::Query.escape("FIND THE ZONES").should == "FIND THE ZONES"
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/riddle/configuration_spec.rb | spec/riddle/configuration_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Configuration do
describe Riddle::Configuration::Index do
describe '#settings' do
it 'should return array with all settings of index' do
Riddle::Configuration::Index.settings.should_not be_empty
end
it 'should return array which contains a docinfo' do
Riddle::Configuration::Index.settings.should be_include :docinfo
end
end
end
describe 'class inherited from Riddle::Configuration::Index' do
before :all do
class TestIndex < Riddle::Configuration::Index; end
end
describe '#settings' do
it 'should has same settings as Riddle::Configuration::Index' do
TestIndex.settings.should == Riddle::Configuration::Index.settings
end
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/riddle/controller_spec.rb | spec/riddle/controller_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Controller do
let(:controller) do
Riddle::Controller.new double('configuration'), 'sphinx.conf'
end
describe '#sphinx_version' do
it "should return 1.10 if using 1.10-beta" do
controller.stub(:` => 'Sphinx 1.10-beta (r2420)')
controller.sphinx_version.should == '1.10-beta'
end
it "should return 0.9.9 if using 0.9.9" do
controller.stub(:` => 'Sphinx 0.9.9-release (r2117)')
controller.sphinx_version.should == '0.9.9'
end
it "should return 0.9.9 if using 0.9.9 rc2" do
controller.stub(:` => 'Sphinx 0.9.9-rc2 (r1785)')
controller.sphinx_version.should == '0.9.9'
end
it "should return 0.9.9 if using 0.9.9 rc1" do
controller.stub(:` => 'Sphinx 0.9.9-rc1 (r1566)')
controller.sphinx_version.should == '0.9.9'
end
it "should return 0.9.8 if using 0.9.8.1" do
controller.stub(:` => 'Sphinx 0.9.8.1-release (r1533)')
controller.sphinx_version.should == '0.9.8'
end
it "should return 0.9.8 if using 0.9.8" do
controller.stub(:` => 'Sphinx 0.9.8-release (r1371)')
controller.sphinx_version.should == '0.9.8'
end
end
describe "#merge" do
before :each do
allow(Riddle::ExecuteCommand).to receive(:call)
allow(controller).to receive(:running?).and_return(false)
end
it "generates the command" do
expect(Riddle::ExecuteCommand).to receive(:call).with(
"indexer --config \"sphinx.conf\" --merge foo bar", nil
)
controller.merge "foo", "bar"
end
it "passes through the verbose option" do
expect(Riddle::ExecuteCommand).to receive(:call).with(
"indexer --config \"sphinx.conf\" --merge foo bar", true
)
controller.merge "foo", "bar", :verbose => true
end
it "adds filters with range values" do
expect(Riddle::ExecuteCommand).to receive(:call).with(
"indexer --config \"sphinx.conf\" --merge foo bar --merge-dst-range flagged 0 1", nil
)
controller.merge "foo", "bar", :filters => {:flagged => 0..1}
end
it "adds filters with single values" do
expect(Riddle::ExecuteCommand).to receive(:call).with(
"indexer --config \"sphinx.conf\" --merge foo bar --merge-dst-range flagged 0 0", nil
)
controller.merge "foo", "bar", :filters => {:flagged => 0}
end
it "rotates if Sphinx is running" do
allow(controller).to receive(:running?).and_return(true)
expect(Riddle::ExecuteCommand).to receive(:call).with(
"indexer --config \"sphinx.conf\" --merge foo bar --rotate", nil
)
controller.merge "foo", "bar"
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/riddle/query/select_spec.rb | spec/riddle/query/select_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'date'
require 'time'
describe Riddle::Query::Select do
let(:query) { Riddle::Query::Select.new }
it 'handles basic queries on a specific index' do
query.from('foo_core').to_sql.should == 'SELECT * FROM foo_core'
end
it 'handles queries on multiple indices' do
query.from('foo_core').from('foo_delta').to_sql.
should == 'SELECT * FROM foo_core, foo_delta'
end
it 'accepts multiple arguments for indices' do
query.from('foo_core', 'foo_delta').to_sql.
should == 'SELECT * FROM foo_core, foo_delta'
end
it "handles custom select values" do
query.values('@weight').from('foo_core').to_sql.
should == 'SELECT @weight FROM foo_core'
end
it 'handles JSON as a select value using dot notation' do
query.values('key1.key2.key3').from('foo_core').to_sql.
should == 'SELECT key1.key2.key3 FROM foo_core'
end
it 'handles JSON as a select value using bracket notation 2' do
query.values("key1['key2']['key3']").from('foo_core').to_sql.
should == "SELECT key1['key2']['key3'] FROM foo_core"
end
it "can prepend select values" do
query.values('@weight').prepend_values('foo').from('foo_core').to_sql.
should == 'SELECT foo, @weight FROM foo_core'
end
it 'handles basic queries with a search term' do
query.from('foo_core').matching('foo').to_sql.
should == "SELECT * FROM foo_core WHERE MATCH('foo')"
end
it "escapes single quotes in the search terms" do
query.from('foo_core').matching("fo'o").to_sql.
should == "SELECT * FROM foo_core WHERE MATCH('fo\\'o')"
end
it 'handles filters with integers' do
query.from('foo_core').matching('foo').where(:bar_id => 10).to_sql.
should == "SELECT * FROM foo_core WHERE MATCH('foo') AND `bar_id` = 10"
end
it "handles exclusive filters with integers" do
query.from('foo_core').matching('foo').where_not(:bar_id => 10).to_sql.
should == "SELECT * FROM foo_core WHERE MATCH('foo') AND `bar_id` <> 10"
end
it "handles filters with true" do
query.from('foo_core').matching('foo').where(:bar => true).to_sql.
should == "SELECT * FROM foo_core WHERE MATCH('foo') AND `bar` = 1"
end
it "handles exclusive filters with true" do
query.from('foo_core').matching('foo').where_not(:bar => true).to_sql.
should == "SELECT * FROM foo_core WHERE MATCH('foo') AND `bar` <> 1"
end
it "handles filters with false" do
query.from('foo_core').matching('foo').where(:bar => false).to_sql.
should == "SELECT * FROM foo_core WHERE MATCH('foo') AND `bar` = 0"
end
it "handles exclusive filters with false" do
query.from('foo_core').matching('foo').where_not(:bar => false).to_sql.
should == "SELECT * FROM foo_core WHERE MATCH('foo') AND `bar` <> 0"
end
it "handles filters with arrays" do
query.from('foo_core').matching('foo').where(:bars => [1, 2]).to_sql.
should == "SELECT * FROM foo_core WHERE MATCH('foo') AND `bars` IN (1, 2)"
end
it "ignores filters with empty arrays" do
query.from('foo_core').matching('foo').where(:bars => []).to_sql.
should == "SELECT * FROM foo_core WHERE MATCH('foo')"
end
it "handles exclusive filters with arrays" do
query.from('foo_core').matching('foo').where_not(:bars => [1, 2]).to_sql.
should == "SELECT * FROM foo_core WHERE MATCH('foo') AND `bars` NOT IN (1, 2)"
end
it "ignores exclusive filters with empty arrays" do
query.from('foo_core').matching('foo').where_not(:bars => []).to_sql.
should == "SELECT * FROM foo_core WHERE MATCH('foo')"
end
it "handles filters with timestamps" do
time = Time.now
query.from('foo_core').matching('foo').where(:created_at => time).to_sql.
should == "SELECT * FROM foo_core WHERE MATCH('foo') AND `created_at` = #{time.to_i}"
end
it "handles filters with dates" do
date = Date.new 2014, 1, 1
query.from('foo_core').matching('foo').where(:created_at => date).to_sql.
should == "SELECT * FROM foo_core WHERE MATCH('foo') AND `created_at` = #{Time.utc(2014, 1, 1).to_i}"
end
it "handles exclusive filters with timestamps" do
time = Time.now
query.from('foo_core').matching('foo').where_not(:created_at => time).
to_sql.should == "SELECT * FROM foo_core WHERE MATCH('foo') AND `created_at` <> #{time.to_i}"
end
it "handles filters with ranges" do
query.from('foo_core').matching('foo').where(:bar => 1..5).to_sql.
should == "SELECT * FROM foo_core WHERE MATCH('foo') AND `bar` BETWEEN 1 AND 5"
end
it "handles filters with strings" do
query.from('foo_core').where(:bar => 'baz').to_sql.
should == "SELECT * FROM foo_core WHERE `bar` = 'baz'"
end
it "handles filters expecting matches on all values" do
query.from('foo_core').where_all(:bars => [1, 2]).to_sql.
should == "SELECT * FROM foo_core WHERE `bars` = 1 AND `bars` = 2"
end
it "handles filters expecting matches on all combinations of values" do
query.from('foo_core').where_all(:bars => [[1,2], 3]).to_sql.
should == "SELECT * FROM foo_core WHERE `bars` IN (1, 2) AND `bars` = 3"
end
it "handles exclusive filters expecting matches on none of the values" do
query.from('foo_core').where_not_all(:bars => [1, 2]).to_sql.
should == "SELECT * FROM foo_core WHERE (`bars` <> 1 OR `bars` <> 2)"
end
it 'handles filters on JSON with dot syntax' do
query.from('foo_core').where('key1.key2.key3' => 10).to_sql.
should == "SELECT * FROM foo_core WHERE key1.key2.key3 = 10"
end
it 'handles filters on JSON with bracket syntax' do
query.from('foo_core').where("key1['key2']['key3']" => 10).to_sql.
should == "SELECT * FROM foo_core WHERE key1['key2']['key3'] = 10"
end
it 'handles grouping' do
query.from('foo_core').group_by('bar_id').to_sql.
should == "SELECT * FROM foo_core GROUP BY `bar_id`"
end
it "handles grouping n-best results" do
query.from('foo_core').group_by('bar_id').group_best(3).to_sql.
should == "SELECT * FROM foo_core GROUP 3 BY `bar_id`"
end
it 'handles having conditions' do
query.from('foo_core').group_by('bar_id').having('bar_id > 10').to_sql.
should == "SELECT * FROM foo_core GROUP BY `bar_id` HAVING bar_id > 10"
end
it 'handles ordering' do
query.from('foo_core').order_by('bar_id ASC').to_sql.
should == 'SELECT * FROM foo_core ORDER BY `bar_id` ASC'
end
it 'handles ordering when an already escaped column is passed in' do
query.from('foo_core').order_by('`bar_id` ASC').to_sql.
should == 'SELECT * FROM foo_core ORDER BY `bar_id` ASC'
end
it 'handles ordering when just a symbol is passed in' do
query.from('foo_core').order_by(:bar_id).to_sql.
should == 'SELECT * FROM foo_core ORDER BY `bar_id`'
end
it 'handles ordering when a computed sphinx variable is passed in' do
query.from('foo_core').order_by('@weight DESC').to_sql.
should == 'SELECT * FROM foo_core ORDER BY @weight DESC'
end
it "handles ordering when a sphinx function is passed in" do
query.from('foo_core').order_by('weight() DESC').to_sql.
should == 'SELECT * FROM foo_core ORDER BY weight() DESC'
end
it 'handles group ordering' do
query.from('foo_core').order_within_group_by('bar_id ASC').to_sql.
should == 'SELECT * FROM foo_core WITHIN GROUP ORDER BY `bar_id` ASC'
end
it 'handles a limit' do
query.from('foo_core').limit(10).to_sql.
should == 'SELECT * FROM foo_core LIMIT 10'
end
it 'handles an offset' do
query.from('foo_core').offset(20).to_sql.
should == 'SELECT * FROM foo_core LIMIT 20, 20'
end
it 'handles an option' do
query.from('foo_core').with_options(:bar => :baz).to_sql.
should == 'SELECT * FROM foo_core OPTION bar=baz'
end
it 'handles multiple options' do
sql = query.from('foo_core').with_options(:bar => :baz, :qux => :quux).
to_sql
sql.should match(/OPTION .*bar=baz/)
sql.should match(/OPTION .*qux=quux/)
end
it "handles options of hashes" do
query.from('foo_core').with_options(:weights => {:foo => 5}).to_sql.
should == 'SELECT * FROM foo_core OPTION weights=(foo=5)'
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/riddle/query/delete_spec.rb | spec/riddle/query/delete_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Query::Delete do
it 'handles a single id' do
query = Riddle::Query::Delete.new 'foo_core', 5
query.to_sql.should == 'DELETE FROM foo_core WHERE id = 5'
end
it 'handles multiple ids' do
query = Riddle::Query::Delete.new 'foo_core', 5, 6, 7
query.to_sql.should == 'DELETE FROM foo_core WHERE id IN (5, 6, 7)'
end
it 'handles multiple ids in an explicit array' do
query = Riddle::Query::Delete.new 'foo_core', [5, 6, 7]
query.to_sql.should == 'DELETE FROM foo_core WHERE id IN (5, 6, 7)'
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/riddle/query/insert_spec.rb | spec/riddle/query/insert_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Riddle::Query::Insert do
it 'handles inserts' do
query = Riddle::Query::Insert.new('foo_core', [:id, :deleted], [4, false])
query.to_sql.should == 'INSERT INTO foo_core (id, `deleted`) VALUES (4, 0)'
end
it 'handles replaces' do
query = Riddle::Query::Insert.new('foo_core', [:id, :deleted], [4, false])
query.replace!
query.to_sql.should == 'REPLACE INTO foo_core (id, `deleted`) VALUES (4, 0)'
end
it 'encloses strings in single quotes' do
query = Riddle::Query::Insert.new('foo_core', [:id, :name], [4, 'bar'])
query.to_sql.should == "INSERT INTO foo_core (id, `name`) VALUES (4, 'bar')"
end
it 'handles inserts with more than one set of values' do
query = Riddle::Query::Insert.new 'foo_core', [:id, :name], [[4, 'bar'], [5, 'baz']]
query.to_sql.
should == "INSERT INTO foo_core (id, `name`) VALUES (4, 'bar'), (5, 'baz')"
end
it 'handles values with single quotes' do
query = Riddle::Query::Insert.new('foo_core', [:id, :name], [4, "bar's"])
query.to_sql.
should == "INSERT INTO foo_core (id, `name`) VALUES (4, 'bar\\'s')"
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/functional/status_spec.rb | spec/functional/status_spec.rb | # frozen_string_literal: true
require 'spec_helper'
if Riddle.loaded_version == '0.9.9' || Riddle.loaded_version == '1.10'
describe "Sphinx Status", :live => true do
before :each do
@client = Riddle::Client.new("localhost", 9313)
@status = @client.status
end
it "should return a hash" do
@status.should be_a(Hash)
end
it "should include the uptime, connections, and command_search keys" do
# Not checking all values, but ensuring keys are being set correctly
@status[:uptime].should_not be_nil
@status[:connections].should_not be_nil
@status[:command_search].should_not be_nil
end
end
end | ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/functional/parsing_spec.rb | spec/functional/parsing_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe "Parsing" do
it "handles invalid configuration files" do
Riddle::Configuration.parse!(<<-DOC)
latex_documents = [
#
]
DOC
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/functional/search_spec.rb | spec/functional/search_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe "Sphinx Searches", :live => true do
let(:client) { Riddle::Client.new 'localhost', 9313 }
it "should return a single hash if a single query" do
client.query("smith", "people").should be_kind_of(Hash)
end
it "should return an array of hashs if multiple queries are run" do
client.append_query "smith", "people"
client.append_query "jones", "people"
results = client.run
results.should be_kind_of(Array)
results.each { |result| result.should be_kind_of(Hash) }
end
it "should return an array of matches" do
matches = client.query("smith", "people")[:matches]
matches.should be_kind_of(Array)
matches.each { |match| match.should be_kind_of(Hash) }
end
it "should return an array of string fields" do
fields = client.query("smith", "people")[:fields]
fields.should be_kind_of(Array)
fields.each { |field| field.should be_kind_of(String) }
end
it "should return an array of attribute names" do
attributes = client.query("smith", "people")[:attribute_names]
attributes.should be_kind_of(Array)
attributes.each { |a| a.should be_kind_of(String) }
end
it "should return a hash of attributes" do
attributes = client.query("smith", "people")[:attributes]
attributes.should be_kind_of(Hash)
attributes.each do |key,value|
key.should be_kind_of(String)
value.should be_kind_of(Integer)
end
end
it "should return the total number of results returned" do
client.query("smith", "people")[:total].should be_kind_of(Integer)
end
it "should return the total number of results available" do
client.query("smith", "people")[:total_found].should be_kind_of(Integer)
end
it "should return the time taken for the query as a float" do
client.query("smith", "people")[:time].should be_kind_of(Float)
end
it "should return a hash of the words from the query, with the number of documents and the number of hits" do
words = client.query("smith victoria", "people")[:words]
words.should be_kind_of(Hash)
words.each do |word,hash|
word.should be_kind_of(String)
hash.should be_kind_of(Hash)
hash[:docs].should be_kind_of(Integer)
hash[:hits].should be_kind_of(Integer)
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/functional/update_spec.rb | spec/functional/update_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe "Sphinx Updates", :live => true do
before :each do
@client = Riddle::Client.new("localhost", 9313)
end
it "should update a single record appropriately" do
# check existing birthday
result = @client.query("Ellie K Ford", "people")
result[:matches].should_not be_empty
result[:matches].length.should == 1
ellie = result[:matches].first
ellie[:attributes]["birthday"].should == Time.local(1970, 1, 23).to_i
# make Ellie younger by 6 years
@client.update("people", ["birthday"], {ellie[:doc] => [Time.local(1976, 1, 23).to_i]})
# check attribute's value
result = @client.query("Ellie K Ford", "people")
result[:matches].should_not be_empty
result[:matches].length.should == 1
ellie = result[:matches].first
ellie[:attributes]["birthday"].should == Time.local(1976, 1, 23).to_i
end
it "should update multiple records appropriately" do
result = @client.query("Steele", "people")
pairs = {}
result[:matches].each do |match|
pairs[match[:doc]] = [match[:attributes]["birthday"] + (365*24*60*60)]
end
@client.update "people", ["birthday"], pairs
result = @client.query("Steele", "people")
result[:matches].each do |match|
match[:attributes]["birthday"].should == pairs[match[:doc]].first
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/functional/persistance_spec.rb | spec/functional/persistance_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe "Sphinx Persistance Connection", :live => true do
before :each do
@client = Riddle::Client.new("localhost", 9313)
end
it "should raise errors once already opened" do
@client.open
lambda { @client.open }.should raise_error
@client.close
end
it "should raise errors if closing when already closed" do
lambda { @client.close }.should raise_error
end
end | ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/functional/merging_spec.rb | spec/functional/merging_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe "Merging indices", :live => true do
let(:connection) { Mysql2::Client.new :host => '127.0.0.1', :port => 9306 }
let(:path) { "spec/fixtures/sphinx/spec.conf" }
let(:configuration) do
Riddle::Configuration::Parser.new(File.read(path)).parse!
end
let(:controller) { Riddle::Controller.new configuration, path }
let(:sphinx) { Sphinx.new }
def record_matches?(index, string)
select = Riddle::Query::Select.new
select.from index
select.matching string
select.to_sql
!!connection.query(select.to_sql).first
end
before :each do
controller.bin_path = sphinx.bin_path
sphinx.mysql_client.execute "USE riddle"
sphinx.mysql_client.execute "DELETE FROM articles"
end
it "merges in new records" do
controller.index
sphinx.mysql_client.execute <<-SQL
INSERT INTO articles (title, delta) VALUES ('pancakes', 1)
SQL
controller.index "article_delta"
sleep 1.5
expect(record_matches?("article_delta", "pancakes")).to eq(true)
expect(record_matches?("article_core", "pancakes")).to eq(false)
controller.merge "article_core", "article_delta"
sleep 1.5
expect(record_matches?("article_core", "pancakes")).to eq(true)
end
it "merges in existing records" do
sphinx.mysql_client.execute <<-SQL
INSERT INTO articles (title, delta) VALUES ('pancakes', 0)
SQL
controller.index
sleep 1.5
expect(record_matches?("article_core", "pancakes")).to eq(true)
expect(record_matches?("article_delta", "pancakes")).to eq(false)
sphinx.mysql_client.execute <<-SQL
UPDATE articles SET title = 'waffles', delta = 1 WHERE title = 'pancakes'
SQL
controller.index "article_delta"
sleep 1.5
expect(record_matches?("article_delta", "waffles")).to eq(true)
expect(record_matches?("article_core", "waffles")).to eq(false)
expect(record_matches?("article_core", "pancakes")).to eq(true)
id = connection.query("SELECT id FROM article_core").first["id"]
connection.query "UPDATE article_core SET deleted = 1 WHERE id = #{id}"
expect(
connection.query("SELECT id FROM article_core WHERE deleted = 1").to_a
).to_not be_empty
controller.merge "article_core", "article_delta",
:filters => {:deleted => 0}
sleep 1.5
expect(record_matches?("article_core", "pancakes")).to eq(false)
expect(record_matches?("article_core", "waffles")).to eq(true)
expect(
connection.query("SELECT id FROM article_core WHERE deleted = 1").to_a
).to be_empty
end
end unless RUBY_PLATFORM == 'java'
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/functional/connection_spec.rb | spec/functional/connection_spec.rb | # frozen_string_literal: true
require 'spec_helper'
class RiddleSpecConnectionProcError < StandardError; end
describe 'Sphinx Client', :live => true do
let(:client) { Riddle::Client.new 'localhost', 9313 }
after :each do
Riddle::Client.connection = nil
end
describe '.connection' do
it "should use the given block" do
Riddle::Client.connection = lambda { |client|
TCPSocket.new(client.server, client.port)
}
client.query('smith').should be_kind_of(Hash)
end
it "should fail with errors from the given block" do
Riddle::Client.connection = lambda { |client|
raise RiddleSpecConnectionProcError
}
lambda { client.query('smith') }.
should raise_error(Riddle::ResponseError)
end
end
describe '#connection' do
it "use the given block" do
client.connection = lambda { |client|
TCPSocket.new(client.server, client.port)
}
client.query('smith').should be_kind_of(Hash)
end
it "should fail with errors from the given block" do
client.connection = lambda { |client|
raise RiddleSpecConnectionProcError
}
lambda { client.query('smith') }.
should raise_error(Riddle::ResponseError)
end
it "should not override OutOfBoundsError instances" do
client.connection = lambda { |client|
raise Riddle::OutOfBoundsError
}
lambda { client.query('smith') }.
should raise_error(Riddle::OutOfBoundsError)
end
it "should prioritise instance over class connection" do
Riddle::Client.connection = lambda { |client|
raise RiddleSpecConnectionProcError
}
client.connection = lambda { |client|
TCPSocket.new(client.server, client.port)
}
lambda { client.query('smith') }.should_not raise_error
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/functional/excerpt_spec.rb | spec/functional/excerpt_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe "Sphinx Excepts", :live => true do
let(:client) { Riddle::Client.new "localhost", 9313 }
let(:controller) do
controller = Riddle::Controller.new nil, ''
controller.bin_path = Sphinx.new.bin_path
controller
end
it "should highlight a single word multiple times in a document" do
excerpts = client.excerpts(
:index => "people",
:words => "Mary",
:docs => ["Mary, Mary, quite contrary."]
)
if controller.sphinx_version.to_i >= 3
excerpts.should == [
'<span class="match">Mary, Mary</span>, quite contrary.'
]
else
excerpts.should == [
'<span class="match">Mary</span>, <span class="match">Mary</span>, quite contrary.'
]
end
end
it "should use specified word markers" do
excerpts = client.excerpts(
:index => "people",
:words => "Mary",
:docs => ["Mary, Mary, quite contrary."],
:before_match => "<em>",
:after_match => "</em>"
)
if controller.sphinx_version.to_i >= 3
excerpts.should == [
"<em>Mary, Mary</em>, quite contrary."
]
else
excerpts.should == [
"<em>Mary</em>, <em>Mary</em>, quite contrary."
]
end
end
it "should separate matches that are far apart by an ellipsis by default" do
excerpts = client.excerpts(
:index => "people",
:words => "Pat",
:docs => [
<<-SENTENCE
This is a really long sentence written by Pat. It has to be over 256
characters long, between keywords. But what is the keyword? Well, I
can't tell you just yet... wait patiently until we've hit the 256 mark.
It'll take a bit longer than you think. We're probably just hitting the
200 mark at this point. But I think we've now arrived - so I can tell
you what the keyword is. I bet you're really interested in finding out,
yeah? Excerpts are particularly riveting. This keyword, however, is
not. It's just my name: Pat.
SENTENCE
],
:before_match => "<em>",
:after_match => "</em>"
)
case Riddle.loaded_version
when '0.9.9'
excerpts.should == [
<<-SENTENCE
This is a really long sentence written by <em>Pat</em>. It has to be over 256
characters long, between keywords. But what is the … 're really interested in finding out,
yeah? Excerpts are particularly riveting. This keyword, however, is
not. It's just my name: <em>Pat</em>.
SENTENCE
]
when '1.10'
excerpts.should == [" … really long sentence written by <em>Pat</em>. It has to be over … . This keyword, however, is\nnot. It's just my name: <em>Pat</em> … "]
when '2.0.1', '2.1.0'
excerpts.should == [" … really long sentence written by <em>Pat</em>. It has to be over … . It's just my name: <em>Pat</em>.\n"]
else
excerpts.should == [
<<-SENTENCE
This is a really long sentence written by <em>Pat</em>. It has to be over 256
characters long, between keywords. But what is the keyword? … interested in finding out,
yeah? Excerpts are particularly riveting. This keyword, however, is
not. It's just my name: <em>Pat</em>.
SENTENCE
]
end
end
it "should use the provided separator" do
excerpts = client.excerpts(
:index => "people",
:words => "Pat",
:docs => [
<<-SENTENCE
This is a really long sentence written by Pat. It has to be over 256
characters long, between keywords. But what is the keyword? Well, I
can't tell you just yet... wait patiently until we've hit the 256 mark.
It'll take a bit longer than you think. We're probably just hitting the
200 mark at this point. But I think we've now arrived - so I can tell
you what the keyword is. I bet you're really interested in finding out,
yeah? Excerpts are particularly riveting. This keyword, however, is
not. It's just my name: Pat.
SENTENCE
],
:before_match => "<em>",
:after_match => "</em>",
:chunk_separator => " --- "
)
case Riddle.loaded_version
when '0.9.9'
excerpts.should == [
<<-SENTENCE
This is a really long sentence written by <em>Pat</em>. It has to be over 256
characters long, between keywords. But what is the --- 're really interested in finding out,
yeah? Excerpts are particularly riveting. This keyword, however, is
not. It's just my name: <em>Pat</em>.
SENTENCE
]
when '1.10'
excerpts.should == [" --- really long sentence written by <em>Pat</em>. It has to be over --- . This keyword, however, is\nnot. It's just my name: <em>Pat</em> --- "]
when '2.0.1', '2.1.0'
excerpts.should == [" --- really long sentence written by <em>Pat</em>. It has to be over --- . It's just my name: <em>Pat</em>.\n"]
else
excerpts.should == [
<<-SENTENCE
This is a really long sentence written by <em>Pat</em>. It has to be over 256
characters long, between keywords. But what is the keyword? --- interested in finding out,
yeah? Excerpts are particularly riveting. This keyword, however, is
not. It's just my name: <em>Pat</em>.
SENTENCE
]
end
end
it "should return multiple results for multiple documents" do
excerpts = client.excerpts(
:index => "people",
:words => "Mary",
:docs => [
"Mary, Mary, quite contrary.",
"The epithet \"Bloody Mary\" is associated with a number of historical and fictional women, most notably Queen Mary I of England"
],
:before_match => "<em>",
:after_match => "</em>"
)
if controller.sphinx_version.to_f >= 3
excerpts.should == [
"<em>Mary, Mary</em>, quite contrary.",
"The epithet \"Bloody <em>Mary</em>\" is associated with a number of historical and fictional women, most notably Queen <em>Mary</em> I of England"
]
else
excerpts.should == [
"<em>Mary</em>, <em>Mary</em>, quite contrary.",
"The epithet \"Bloody <em>Mary</em>\" is associated with a number of historical and fictional women, most notably Queen <em>Mary</em> I of England"
]
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/functional/escaping_spec.rb | spec/functional/escaping_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe 'SphinxQL escaping', :live => true do
let(:connection) { Mysql2::Client.new :host => '127.0.0.1', :port => 9306 }
def sphinxql_matching(string)
select = Riddle::Query::Select.new
select.from 'people'
select.matching string
select.to_sql
end
['@', "'", '"', '\\"', "\\'", "?"].each do |string|
it "escapes #{string}" do
lambda {
connection.query sphinxql_matching(Riddle::Query.escape(string))
}.should_not raise_error
end
end
context 'on snippets' do
def snippets_for(text, words = '', options = nil)
snippets_query = Riddle::Query.snippets(text, 'people', words, options)
connection.query(snippets_query).first['snippet']
end
it 'preserves original text with special SphinxQL escape characters' do
text = 'email: john@example.com (yay!)'
snippets_for(text).should == text
end
it 'preserves original text with special MySQL escape characters' do
text = "'Dear' Susie\nAlways use {\\LaTeX}"
snippets_for(text).should == text
end
it 'escapes match delimiters with special SphinxQL escape characters' do
snippets = snippets_for('hello world', 'world',
:before_match => '()|-!', :after_match => '@~"/^$')
snippets.should == 'hello ()|-!world@~"/^$'
end
it 'escapes match delimiters with special MySQL escape characters' do
snippets = snippets_for('hello world', 'world',
:before_match => "'\"", :after_match => "\n\t\\")
snippets.should == "hello '\"world\n\t\\"
end
end
end unless RUBY_PLATFORM == 'java' || Riddle.loaded_version.to_i < 2
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/spec/functional/keywords_spec.rb | spec/functional/keywords_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe "Sphinx Keywords", :live => true do
before :each do
@client = Riddle::Client.new("localhost", 9313)
end
it "should return an array of hashes" do
results = @client.keywords("pat", "people")
results.should be_kind_of(Array)
results.each do |result|
result.should be_kind_of(Hash)
end
end
it "should have keys for normalised and tokenised versions of the keywords" do
results = @client.keywords("pat", "people")
results.each do |result|
result.keys.should include(:normalised)
result.keys.should include(:tokenised)
end
end
it "shouldn't have docs or hits keys if not requested" do
results = @client.keywords("pat", "people")
results.each do |result|
result.keys.should_not include(:docs)
result.keys.should_not include(:hits)
end
end
it "should have docs and hits keys if requested" do
results = @client.keywords("pat", "people", true)
results.each do |result|
result.keys.should include(:docs)
result.keys.should include(:hits)
end
end
end | ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle.rb | lib/riddle.rb | # frozen_string_literal: true
require 'date'
require 'thread'
require 'socket'
require 'stringio'
require 'timeout'
module Riddle #:nodoc:
@@mutex = Mutex.new
@@escape_pattern = /[\(\)\|\-!@~"&\/\?]/
@@use_encoding = defined?(::Encoding) &&
::Encoding.respond_to?(:default_external)
class ConnectionError < StandardError #:nodoc:
#
end
def self.encode(data, encoding = @@use_encoding && ::Encoding.default_external)
if @@use_encoding
data.force_encoding(encoding)
else
data
end
end
def self.mutex
@@mutex
end
def self.escape_pattern
@@escape_pattern
end
def self.escape_pattern=(pattern)
mutex.synchronize do
@@escape_pattern = pattern
end
end
def self.escape(string)
string.gsub(escape_pattern) { |char| "\\#{char}" }
end
def self.loaded_version
@@sphinx_version
end
def self.loaded_version=(version)
@@sphinx_version = version
end
def self.version_warning
return if loaded_version
STDERR.puts %Q{
Riddle cannot detect Sphinx on your machine, and so can't determine which
version of Sphinx you are planning on using. Please use one of the following
lines after "require 'riddle'" to avoid this warning.
require 'riddle/0.9.8'
# or
require 'riddle/0.9.9'
# or
require 'riddle/1.10'
}
end
end
require 'riddle/auto_version'
require 'riddle/client'
require 'riddle/command_failed_error'
require 'riddle/command_result'
require 'riddle/configuration'
require 'riddle/controller'
require 'riddle/execute_command'
require 'riddle/query'
Riddle.loaded_version = nil
Riddle::AutoVersion.configure
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/1.10.rb | lib/riddle/1.10.rb | # frozen_string_literal: true
require 'riddle/0.9.9'
Riddle.loaded_version = '1.10'
require 'riddle/1.10/client' | ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/0.9.9.rb | lib/riddle/0.9.9.rb | # frozen_string_literal: true
Riddle.loaded_version = '0.9.9'
require 'riddle/0.9.9/client'
require 'riddle/0.9.9/client/filter'
require 'riddle/0.9.9/configuration/searchd'
Riddle.escape_pattern = /[\(\)\|\-!@~"&\/\\\^\$=]/
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/auto_version.rb | lib/riddle/auto_version.rb | # frozen_string_literal: true
class Riddle::AutoVersion
def self.configure
controller = Riddle::Controller.new nil, ''
version = ENV['SPHINX_VERSION'] || controller.sphinx_version
case version
when '0.9.8', '0.9.9'
require "riddle/#{version}"
when /1.10/
require 'riddle/1.10'
when /2.0.[12]/
require 'riddle/2.0.1'
else
require 'riddle/2.1.0'
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/2.1.0.rb | lib/riddle/2.1.0.rb | # frozen_string_literal: true
require 'riddle/0.9.9'
require 'riddle/1.10'
require 'riddle/2.0.1'
Riddle.loaded_version = '2.1.0'
Riddle::Client::Versions[:search] = 0x119
Riddle::Client::Versions[:excerpt] = 0x104
Riddle::Client::RankModes[:expr] = 8
Riddle::Client::RankModes[:total] = 9
Riddle::Client::AttributeTypes[:multi] = 0x40000001
Riddle::Client::AttributeTypes[:multi_64] = 0x40000002
Riddle::Client::AttributeHandlers[Riddle::Client::AttributeTypes[:multi_64]] = :next_64bit_int_array
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/2.0.1.rb | lib/riddle/2.0.1.rb | # frozen_string_literal: true
require 'riddle/0.9.9'
require 'riddle/1.10'
Riddle.loaded_version = '2.0.1'
require 'riddle/2.0.1/client'
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/query.rb | lib/riddle/query.rb | # frozen_string_literal: true
module Riddle::Query
ESCAPE_CHARACTERS = /[\(\)\|\-!@~\/"\/\^\$\\><&=\?]/
# http://sphinxsearch.com/docs/current/extended-syntax.html
ESCAPE_WORDS = /\b(?:MAYBE|NEAR|PARAGRAPH|SENTENCE|ZONE|ZONESPAN)\b/
MYSQL2_ESCAPE = defined?(Mysql2) && defined?(Mysql::Client)
def self.connection(address = '127.0.0.1', port = 9312)
require 'mysql2'
# If you use localhost, MySQL insists on a socket connection, but Sphinx
# requires a TCP connection. Using 127.0.0.1 fixes that.
address = '127.0.0.1' if address == 'localhost'
Mysql2::Client.new(
:host => address,
:port => port
)
end
def self.meta
'SHOW META'
end
def self.warnings
'SHOW WARNINGS'
end
def self.status
'SHOW STATUS'
end
def self.tables
'SHOW TABLES'
end
def self.variables
'SHOW VARIABLES'
end
def self.collation
'SHOW COLLATION'
end
def self.describe(index)
"DESCRIBE #{index}"
end
def self.begin
'BEGIN'
end
def self.commit
'COMMIT'
end
def self.rollback
'ROLLBACK'
end
def self.set(variable, values, global = true)
values = "(#{values.join(', ')})" if values.is_a?(Array)
"SET#{ ' GLOBAL' if global } #{variable} = #{values}"
end
def self.snippets(data, index, query, options = nil)
data, index, query = quote(data), quote(index), quote(query)
options = ', ' + options.keys.collect { |key|
value = translate_value options[key]
value = quote value if value.is_a?(String)
"#{value} AS #{key}"
}.join(', ') unless options.nil?
"CALL SNIPPETS(#{data}, #{index}, #{query}#{options})"
end
def self.create_function(name, type, file)
type = type.to_s.upcase
"CREATE FUNCTION #{name} RETURNS #{type} SONAME #{quote file}"
end
def self.drop_function(name)
"DROP FUNCTION #{name}"
end
def self.update(index, id, values = {})
values = values.keys.collect { |key|
"#{key} = #{translate_value values[key]}"
}.join(', ')
"UPDATE #{index} SET #{values} WHERE id = #{id}"
end
def self.translate_value(value)
case value
when TrueClass
1
when FalseClass
0
else
value
end
end
def self.escape(string)
string.gsub(ESCAPE_CHARACTERS) { |match| "\\#{match}" }
.gsub(ESCAPE_WORDS) { |word| "\\#{word}" }
end
def self.quote(string)
"'#{sql_escape string}'"
end
def self.sql_escape(string)
return Mysql2::Client.escape(string) if MYSQL2_ESCAPE
string.gsub(/['"\\]/) { |character| "\\#{character}" }
end
end
require 'riddle/query/delete'
require 'riddle/query/insert'
require 'riddle/query/select'
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/command_failed_error.rb | lib/riddle/command_failed_error.rb | # frozen_string_literal: true
class Riddle::CommandFailedError < StandardError
attr_accessor :command_result
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/execute_command.rb | lib/riddle/execute_command.rb | # frozen_string_literal: true
class Riddle::ExecuteCommand
WINDOWS = (RUBY_PLATFORM =~ /mswin|mingw/)
def self.call(command, verbose = true)
new(command, verbose).call
end
def initialize(command, verbose)
@command, @verbose = command, verbose
return unless WINDOWS
@command = "start /B #{@command} 1> NUL 2>&1"
@verbose = true
end
def call
result = verbose? ? result_from_system : result_from_backticks
return result if result.status == 0
error = Riddle::CommandFailedError.new "Sphinx command failed to execute"
error.command_result = result
raise error
end
private
attr_reader :command, :verbose
def result_from_backticks
begin
output = `#{command}`
rescue SystemCallError => error
output = error.message
end
Riddle::CommandResult.new command, $?.exitstatus, output
end
def result_from_system
system command
Riddle::CommandResult.new command, $?.exitstatus
end
def verbose?
verbose
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/configuration.rb | lib/riddle/configuration.rb | # frozen_string_literal: true
require 'riddle/configuration/section'
require 'riddle/configuration/index_settings'
require 'riddle/configuration/common'
require 'riddle/configuration/distributed_index'
require 'riddle/configuration/index'
require 'riddle/configuration/indexer'
require 'riddle/configuration/realtime_index'
require 'riddle/configuration/remote_index'
require 'riddle/configuration/searchd'
require 'riddle/configuration/source'
require 'riddle/configuration/sql_source'
require 'riddle/configuration/template_index'
require 'riddle/configuration/tsv_source'
require 'riddle/configuration/xml_source'
require 'riddle/configuration/parser'
module Riddle
class Configuration
class ConfigurationError < StandardError #:nodoc:
end
attr_reader :common, :indices, :searchd, :sources
attr_accessor :indexer
def self.parse!(input)
Riddle::Configuration::Parser.new(input).parse!
end
def initialize
@common = Riddle::Configuration::Common.new
@indexer = Riddle::Configuration::Indexer.new
@searchd = Riddle::Configuration::Searchd.new
@indices = []
@sources = []
end
def render
(
[@common.render, @indexer.render, @searchd.render] +
@sources.collect { |source| source.render } +
@indices.collect { |index| index.render }
).join("\n")
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/controller.rb | lib/riddle/controller.rb | # frozen_string_literal: true
module Riddle
NoConfigurationFileError = Class.new StandardError
class Controller
DEFAULT_MERGE_OPTIONS = {:filters => {}}.freeze
attr_accessor :path, :bin_path, :searchd_binary_name, :indexer_binary_name
def initialize(configuration, path)
@configuration = configuration
@path = path
@bin_path = ''
@searchd_binary_name = 'searchd'
@indexer_binary_name = 'indexer'
end
def sphinx_version
`#{indexer} 2>&1`[/(Sphinx|Manticore) (\d+\.\d+(\.\d+|(?:-dev|(\-id64)?\-beta)))/, 2]
rescue
nil
end
def index(*indices)
options = indices.last.is_a?(Hash) ? indices.pop : {}
indices << '--all' if indices.empty?
command = "#{indexer} --config \"#{@path}\" #{indices.join(' ')}"
command = "#{command} --rotate" if running?
Riddle::ExecuteCommand.call command, options[:verbose]
end
def merge(destination, source, options = {})
options = DEFAULT_MERGE_OPTIONS.merge options
command = "#{indexer} --config \"#{@path}\"".dup
command << " --merge #{destination} #{source}"
options[:filters].each do |attribute, value|
value = value..value unless value.is_a?(Range)
command << " --merge-dst-range #{attribute} #{value.min} #{value.max}"
end
command << " --rotate" if running?
Riddle::ExecuteCommand.call command, options[:verbose]
end
def start(options = {})
return if running?
check_for_configuration_file
command = "#{searchd} --pidfile --config \"#{@path}\""
command = "#{command} --nodetach" if options[:nodetach]
exec(command) if options[:nodetach]
# Code does not get here if nodetach is true.
Riddle::ExecuteCommand.call command, options[:verbose]
end
def stop(options = {})
return true unless running?
check_for_configuration_file
stop_flag = 'stopwait'
stop_flag = 'stop' if Riddle.loaded_version.split('.').first == '0'
command = %(#{searchd} --pidfile --config "#{@path}" --#{stop_flag})
result = Riddle::ExecuteCommand.call command, options[:verbose]
result.successful = !running?
result
end
def pid
if File.exist?(configuration.searchd.pid_file)
File.read(configuration.searchd.pid_file)[/\d+/]
else
nil
end
end
def rotate
pid && Process.kill(:HUP, pid.to_i)
end
def running?
!!pid && !!Process.kill(0, pid.to_i)
rescue
false
end
private
attr_reader :configuration
def indexer
"#{bin_path}#{indexer_binary_name}"
end
def searchd
"#{bin_path}#{searchd_binary_name}"
end
def check_for_configuration_file
return if File.exist?(@path)
raise Riddle::NoConfigurationFileError, "'#{@path}' does not exist"
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/client.rb | lib/riddle/client.rb | # frozen_string_literal: true
require 'riddle/client/filter'
require 'riddle/client/message'
require 'riddle/client/response'
module Riddle
class VersionError < StandardError; end
class ResponseError < StandardError
attr_accessor :original
end
class OutOfBoundsError < StandardError; end
# This class was heavily based on the existing Client API by Dmytro Shteflyuk
# and Alexy Kovyrin. Their code worked fine, I just wanted something a bit
# more Ruby-ish (ie. lowercase and underscored method names). I also have
# used a few helper classes, just to neaten things up.
#
# Feel free to use it wherever. Send bug reports, patches, comments and
# suggestions to pat at freelancing-gods dot com.
#
# Most properties of the client are accessible through attribute accessors,
# and where relevant use symboles instead of the long constants common in
# other clients.
# Some examples:
#
# client.sort_mode = :extended
# client.sort_by = "birthday DESC"
# client.match_mode = :extended
#
# To add a filter, you will need to create a Filter object:
#
# client.filters << Riddle::Client::Filter.new("birthday",
# Time.at(1975, 1, 1).to_i..Time.at(1985, 1, 1).to_i, false)
#
class Client
Commands = {
:search => 0, # SEARCHD_COMMAND_SEARCH
:excerpt => 1, # SEARCHD_COMMAND_EXCERPT
:update => 2, # SEARCHD_COMMAND_UPDATE
:keywords => 3, # SEARCHD_COMMAND_KEYWORDS
:persist => 4, # SEARCHD_COMMAND_PERSIST
:status => 5, # SEARCHD_COMMAND_STATUS
:query => 6, # SEARCHD_COMMAND_QUERY
:flushattrs => 7 # SEARCHD_COMMAND_FLUSHATTRS
}
Versions = {
:search => 0x113, # VER_COMMAND_SEARCH
:excerpt => 0x100, # VER_COMMAND_EXCERPT
:update => 0x101, # VER_COMMAND_UPDATE
:keywords => 0x100, # VER_COMMAND_KEYWORDS
:status => 0x100, # VER_COMMAND_STATUS
:query => 0x100, # VER_COMMAND_QUERY
:flushattrs => 0x100 # VER_COMMAND_FLUSHATTRS
}
Statuses = {
:ok => 0, # SEARCHD_OK
:error => 1, # SEARCHD_ERROR
:retry => 2, # SEARCHD_RETRY
:warning => 3 # SEARCHD_WARNING
}
MatchModes = {
:all => 0, # SPH_MATCH_ALL
:any => 1, # SPH_MATCH_ANY
:phrase => 2, # SPH_MATCH_PHRASE
:boolean => 3, # SPH_MATCH_BOOLEAN
:extended => 4, # SPH_MATCH_EXTENDED
:fullscan => 5, # SPH_MATCH_FULLSCAN
:extended2 => 6 # SPH_MATCH_EXTENDED2
}
RankModes = {
:proximity_bm25 => 0, # SPH_RANK_PROXIMITY_BM25
:bm25 => 1, # SPH_RANK_BM25
:none => 2, # SPH_RANK_NONE
:wordcount => 3, # SPH_RANK_WORDCOUNT
:proximity => 4, # SPH_RANK_PROXIMITY
:match_any => 5, # SPH_RANK_MATCHANY
:fieldmask => 6, # SPH_RANK_FIELDMASK
:sph04 => 7, # SPH_RANK_SPH04
:total => 8 # SPH_RANK_TOTAL
}
SortModes = {
:relevance => 0, # SPH_SORT_RELEVANCE
:attr_desc => 1, # SPH_SORT_ATTR_DESC
:attr_asc => 2, # SPH_SORT_ATTR_ASC
:time_segments => 3, # SPH_SORT_TIME_SEGMENTS
:extended => 4, # SPH_SORT_EXTENDED
:expr => 5 # SPH_SORT_EXPR
}
AttributeTypes = {
:integer => 1, # SPH_ATTR_INTEGER
:timestamp => 2, # SPH_ATTR_TIMESTAMP
:ordinal => 3, # SPH_ATTR_ORDINAL
:bool => 4, # SPH_ATTR_BOOL
:float => 5, # SPH_ATTR_FLOAT
:bigint => 6, # SPH_ATTR_BIGINT
:string => 7, # SPH_ATTR_STRING
:group_concat => 10,
:multi => 0x40000000 # SPH_ATTR_MULTI
}
GroupFunctions = {
:day => 0, # SPH_GROUPBY_DAY
:week => 1, # SPH_GROUPBY_WEEK
:month => 2, # SPH_GROUPBY_MONTH
:year => 3, # SPH_GROUPBY_YEAR
:attr => 4, # SPH_GROUPBY_ATTR
:attrpair => 5 # SPH_GROUPBY_ATTRPAIR
}
FilterTypes = {
:values => 0, # SPH_FILTER_VALUES
:range => 1, # SPH_FILTER_RANGE
:float_range => 2 # SPH_FILTER_FLOATRANGE
}
attr_accessor :servers, :port, :offset, :limit, :max_matches,
:match_mode, :sort_mode, :sort_by, :weights, :id_range, :filters,
:group_by, :group_function, :group_clause, :group_distinct, :cut_off,
:retry_count, :retry_delay, :anchor, :index_weights, :rank_mode,
:rank_expr, :max_query_time, :field_weights, :timeout, :overrides,
:select, :connection, :key
attr_reader :queue
@@connection = nil
def self.connection=(value)
Riddle.mutex.synchronize do
@@connection = value
end
end
def self.connection
@@connection
end
# Can instantiate with a specific server and port - otherwise it assumes
# defaults of localhost and 9312 respectively. All other settings can be
# accessed and changed via the attribute accessors.
def initialize(servers = nil, port = nil, key = nil)
Riddle.version_warning
@servers = Array(servers || "localhost")
@port = port || 9312
@socket = nil
@key = key
reset
@queue = []
end
# Reset attributes and settings to defaults.
def reset
# defaults
@offset = 0
@limit = 20
@max_matches = 1000
@match_mode = :all
@sort_mode = :relevance
@sort_by = ''
@weights = []
@id_range = 0..0
@filters = []
@group_by = ''
@group_function = :day
@group_clause = '@weight DESC'
@group_distinct = ''
@cut_off = 0
@retry_count = 0
@retry_delay = 0
@anchor = {}
# string keys are index names, integer values are weightings
@index_weights = {}
@rank_mode = :proximity_bm25
@rank_expr = ''
@max_query_time = 0
# string keys are field names, integer values are weightings
@field_weights = {}
@timeout = 0
@overrides = {}
@select = "*"
end
# The searchd server to query. Servers are removed from @server after a
# Timeout::Error is hit to allow for fail-over.
def server
@servers.first
end
# Backwards compatible writer to the @servers array.
def server=(server)
@servers = server.to_a
end
# Set the geo-anchor point - with the names of the attributes that contain
# the latitude and longitude (in radians), and the reference position.
# Note that for geocoding to work properly, you must also set
# match_mode to :extended. To sort results by distance, you will
# need to set sort_by to '@geodist asc', and sort_mode to extended (as an
# example). Sphinx expects latitude and longitude to be returned from you
# SQL source in radians.
#
# Example:
# client.set_anchor('lat', -0.6591741, 'long', 2.530770)
#
def set_anchor(lat_attr, lat, long_attr, long)
@anchor = {
:latitude_attribute => lat_attr,
:latitude => lat,
:longitude_attribute => long_attr,
:longitude => long
}
end
# Append a query to the queue. This uses the same parameters as the query
# method.
def append_query(search, index = '*', comments = '')
@queue << query_message(search, index, comments)
end
# Run all the queries currently in the queue. This will return an array of
# results hashes.
def run
response = Response.new request(:search, @queue)
results = @queue.collect do
result = {
:matches => [],
:fields => [],
:attributes => {},
:attribute_names => [],
:words => {}
}
result[:status] = response.next_int
case result[:status]
when Statuses[:warning]
result[:warning] = response.next
when Statuses[:error]
result[:error] = response.next
next result
end
result[:fields] = response.next_array
attributes = response.next_int
attributes.times do
attribute_name = response.next
type = response.next_int
result[:attributes][attribute_name] = type
result[:attribute_names] << attribute_name
end
result_attribute_names_and_types = result[:attribute_names].
inject([]) { |array, attr| array.push([ attr, result[:attributes][attr] ]) }
matches = response.next_int
is_64_bit = response.next_int
result[:matches] = (0...matches).map do |i|
doc = is_64_bit > 0 ? response.next_64bit_int : response.next_int
weight = response.next_int
current_match_attributes = {}
result_attribute_names_and_types.each do |attr, type|
current_match_attributes[attr] = attribute_from_type(type, response)
end
{:doc => doc, :weight => weight, :index => i, :attributes => current_match_attributes}
end
result[:total] = response.next_int.to_i || 0
result[:total_found] = response.next_int.to_i || 0
result[:time] = ('%.3f' % (response.next_int / 1000.0)).to_f || 0.0
words = response.next_int
words.times do
word = response.next
docs = response.next_int
hits = response.next_int
result[:words][word] = {:docs => docs, :hits => hits}
end
result
end
@queue.clear
results
rescue Riddle::OutOfBoundsError => error
raise error
rescue => original
error = ResponseError.new original.message
error.original = original
raise error
end
# Query the Sphinx daemon - defaulting to all indices, but you can specify
# a specific one if you wish. The search parameter should be a string
# following Sphinx's expectations.
#
# The object returned from this method is a hash with the following keys:
#
# * :matches
# * :fields
# * :attributes
# * :attribute_names
# * :words
# * :total
# * :total_found
# * :time
# * :status
# * :warning (if appropriate)
# * :error (if appropriate)
#
# The key <tt>:matches</tt> returns an array of hashes - the actual search
# results. Each hash has the document id (<tt>:doc</tt>), the result
# weighting (<tt>:weight</tt>), and a hash of the attributes for the
# document (<tt>:attributes</tt>).
#
# The <tt>:fields</tt> and <tt>:attribute_names</tt> keys return list of
# fields and attributes for the documents. The key <tt>:attributes</tt>
# will return a hash of attribute name and type pairs, and <tt>:words</tt>
# returns a hash of hashes representing the words from the search, with the
# number of documents and hits for each, along the lines of:
#
# results[:words]["Pat"] #=> {:docs => 12, :hits => 15}
#
# <tt>:total</tt>, <tt>:total_found</tt> and <tt>:time</tt> return the
# number of matches available, the total number of matches (which may be
# greater than the maximum available, depending on the number of matches
# and your sphinx configuration), and the time in milliseconds that the
# query took to run.
#
# <tt>:status</tt> is the error code for the query - and if there was a
# related warning, it will be under the <tt>:warning</tt> key. Fatal errors
# will be described under <tt>:error</tt>.
#
def query(search, index = '*', comments = '')
@queue.clear
@queue << query_message(search, index, comments)
self.run.first
end
# Build excerpts from search terms (the +words+) and the text of documents. Excerpts are bodies of text that have the +words+ highlighted.
# They may also be abbreviated to fit within a word limit.
#
# As part of the options hash, you will need to
# define:
# * :docs
# * :words
# * :index
#
# Optional settings include:
# * :before_match (defaults to <span class="match">)
# * :after_match (defaults to </span>)
# * :chunk_separator (defaults to ' … ' - which is an HTML ellipsis)
# * :limit (defaults to 256)
# * :around (defaults to 5)
# * :exact_phrase (defaults to false)
# * :single_passage (defaults to false)
#
# The defaults differ from the official PHP client, as I've opted for
# semantic HTML markup.
#
# Example:
#
# client.excerpts(:docs => ["Pat Allan, Pat Cash"], :words => 'Pat', :index => 'pats')
# #=> ["<span class=\"match\">Pat</span> Allan, <span class=\"match\">Pat</span> Cash"]
#
# lorem_lipsum = "Lorem ipsum dolor..."
#
# client.excerpts(:docs => ["Pat Allan, #{lorem_lipsum} Pat Cash"], :words => 'Pat', :index => 'pats')
# #=> ["<span class=\"match\">Pat</span> Allan, Lorem ipsum dolor sit amet, consectetur adipisicing
# elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua … . Excepteur
# sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est
# laborum. <span class=\"match\">Pat</span> Cash"]
#
# Workflow:
#
# Excerpt creation is completely isolated from searching the index. The nominated index is only used to
# discover encoding and charset information.
#
# Therefore, the workflow goes:
#
# 1. Do the sphinx query.
# 2. Fetch the documents found by sphinx from their repositories.
# 3. Pass the documents' text to +excerpts+ for marking up of matched terms.
#
def excerpts(options = {})
options[:index] ||= '*'
options[:before_match] ||= '<span class="match">'
options[:after_match] ||= '</span>'
options[:chunk_separator] ||= ' … ' # ellipsis
options[:limit] ||= 256
options[:limit_passages] ||= 0
options[:limit_words] ||= 0
options[:around] ||= 5
options[:exact_phrase] ||= false
options[:single_passage] ||= false
options[:query_mode] ||= false
options[:force_all_words] ||= false
options[:start_passage_id] ||= 1
options[:load_files] ||= false
options[:html_strip_mode] ||= 'index'
options[:allow_empty] ||= false
options[:passage_boundary] ||= 'none'
options[:emit_zones] ||= false
options[:load_files_scattered] ||= false
response = Response.new request(:excerpt, excerpts_message(options))
options[:docs].collect { response.next }
end
# Update attributes - first parameter is the relevant index, second is an
# array of attributes to be updated, and the third is a hash, where the
# keys are the document ids, and the values are arrays with the attribute
# values - in the same order as the second parameter.
#
# Example:
#
# client.update('people', ['birthday'], {1 => [Time.at(1982, 20, 8).to_i]})
#
def update(index, attributes, values_by_doc)
response = Response.new request(
:update,
update_message(index, attributes, values_by_doc)
)
response.next_int
end
# Generates a keyword list for a given query. Each keyword is represented
# by a hash, with keys :tokenised and :normalised. If return_hits is set to
# true it will also report on the number of hits and documents for each
# keyword (see :hits and :docs keys respectively).
def keywords(query, index, return_hits = false)
response = Response.new request(
:keywords,
keywords_message(query, index, return_hits)
)
(0...response.next_int).collect do
hash = {}
hash[:tokenised] = response.next
hash[:normalised] = response.next
if return_hits
hash[:docs] = response.next_int
hash[:hits] = response.next_int
end
hash
end
end
def status
response = Response.new request(
:status, Message.new
)
rows, cols = response.next_int, response.next_int
(0...rows).inject({}) do |hash, row|
hash[response.next.to_sym] = response.next
hash
end
end
def flush_attributes
response = Response.new request(
:flushattrs, Message.new
)
response.next_int
end
def add_override(attribute, type, values)
@overrides[attribute] = {:type => type, :values => values}
end
def open
open_socket
return if Versions[:search] < 0x116
@socket.send request_header(:persist) + [1].pack('N'), 0
end
def close
close_socket
end
private
def open_socket
raise "Already Connected" unless @socket.nil?
available_servers = servers.dup
if @timeout == 0
@socket = initialise_connection(available_servers.first)
else
begin
Timeout.timeout(@timeout) { @socket = initialise_connection(available_servers.first) }
rescue Timeout::Error, Riddle::ConnectionError => e
failed_servers ||= []
failed_servers << available_servers.shift
retry if !available_servers.empty?
case e
when Timeout::Error
raise Riddle::ConnectionError,
"Connection to #{failed_servers.inspect} on #{@port} timed out after #{@timeout} seconds"
else
raise e
end
end
end
true
end
def close_socket
raise "Not Connected" if @socket.nil?
@socket.close
@socket = nil
true
end
# If there's an active connection to the Sphinx daemon, this will yield the
# socket. If there's no active connection, then it will connect, yield the
# new socket, then close it.
def connect(&block)
if @socket.nil? || @socket.closed?
@socket = nil
open_socket
begin
yield @socket
ensure
close_socket
end
else
yield @socket
end
end
def initialise_connection(available_server)
socket = initialise_socket(available_server)
# Checking version
version = socket.recv(4).unpack('N*').first
if version < 1
socket.close
raise VersionError, "Can only connect to searchd version 1.0 or better, not version #{version}"
end
# Send version
socket.send [1].pack('N'), 0
socket
end
def initialise_socket(available_server)
tries = 0
begin
socket = if self.connection
self.connection.call(self)
elsif self.class.connection
self.class.connection.call(self)
elsif available_server && available_server.index('/') == 0
UNIXSocket.new available_server
elsif available_server
TCPSocket.new available_server, @port
else
raise "Server not set."
end
rescue Errno::ETIMEDOUT, Errno::ECONNRESET, Errno::ECONNREFUSED => e
retry if (tries += 1) < 5
raise Riddle::ConnectionError,
"Connection to #{available_server} on #{@port} failed. #{e.message}"
end
socket
end
def request_header(command, length = 0)
length += key_message.length if key
core_header = case command
when :search
# Message length is +4/+8 to account for the following count value for
# the number of messages.
if Versions[command] >= 0x118
[Commands[command], Versions[command], 8 + length].pack("nnN")
else
[Commands[command], Versions[command], 4 + length].pack("nnN")
end
when :status
[Commands[command], Versions[command], 4, 1].pack("nnNN")
when :persist
[Commands[command], 0, 4 + length].pack("nnN")
else
[Commands[command], Versions[command], length].pack("nnN")
end
key ? core_header + key_message : core_header
end
def key_message
@key_message ||= begin
message = Message.new
message.append_string key
message.to_s
end
end
# Send a collection of messages, for a command type (eg, search, excerpts,
# update), to the Sphinx daemon.
def request(command, messages)
response = StringIO.new String.new(""), "w"
response.set_encoding "ASCII-8BIT"
status = -1
version = 0
length = 0
message = Riddle.encode(Array(messages).join(""), 'ASCII-8BIT')
connect do |socket|
case command
when :search
if Versions[command] >= 0x118
socket.send request_header(command, message.length) +
[0, messages.length].pack('NN') + message, 0
else
socket.send request_header(command, message.length) +
[messages.length].pack('N') + message, 0
end
when :status
socket.send request_header(command, message.length), 0
else
socket.send request_header(command, message.length) + message, 0
end
header = socket.recv(8)
status, version, length = header.unpack('n2N')
while response.length < (length || 0)
part = socket.recv(length - response.length)
# will return 0 bytes if remote side closed TCP connection, e.g, searchd segfaulted.
break if part.length == 0 && socket.is_a?(TCPSocket)
response << part if part
end
end
response = response.string
if response.empty? || response.length != length
raise ResponseError, "No response from searchd (status: #{status}, version: #{version})"
end
case status
when Statuses[:ok]
if version < Versions[command]
puts format("searchd command v.%d.%d older than client (v.%d.%d)",
version >> 8, version & 0xff,
Versions[command] >> 8, Versions[command] & 0xff)
end
response
when Statuses[:warning]
length = response[0, 4].unpack('N*').first
puts response[4, length]
response[4 + length, response.length - 4 - length]
when Statuses[:error], Statuses[:retry]
message = response[4, response.length - 4]
klass = message[/out of bounds/] ? OutOfBoundsError : ResponseError
raise klass, "searchd error (status: #{status}): #{message}"
else
raise ResponseError, "Unknown searchd error (status: #{status})"
end
end
# Generation of the message to send to Sphinx for a search.
def query_message(search, index, comments = '')
message = Message.new
# Mode, Limits
message.append_ints @offset, @limit, MatchModes[@match_mode]
# Ranking
message.append_int RankModes[@rank_mode]
message.append_string @rank_expr if @rank_mode == :expr
# Sort Mode
message.append_int SortModes[@sort_mode]
message.append_string @sort_by
# Query
message.append_string search
# Weights
message.append_int @weights.length
message.append_ints *@weights
# Index
message.append_string index
# ID Range
message.append_int 1
message.append_64bit_ints @id_range.first, @id_range.last
# Filters
message.append_int @filters.length
@filters.each { |filter| message.append filter.query_message }
# Grouping
message.append_int GroupFunctions[@group_function]
message.append_string @group_by
message.append_int @max_matches
message.append_string @group_clause
message.append_ints @cut_off, @retry_count, @retry_delay
message.append_string @group_distinct
# Anchor Point
if @anchor.empty?
message.append_int 0
else
message.append_int 1
message.append_string @anchor[:latitude_attribute]
message.append_string @anchor[:longitude_attribute]
message.append_floats @anchor[:latitude], @anchor[:longitude]
end
# Per Index Weights
message.append_int @index_weights.length
@index_weights.each do |key,val|
message.append_string key.to_s
message.append_int val
end
# Max Query Time
message.append_int @max_query_time
# Per Field Weights
message.append_int @field_weights.length
@field_weights.each do |key,val|
message.append_string key.to_s
message.append_int val
end
message.append_string comments
return message.to_s if Versions[:search] < 0x116
# Overrides
message.append_int @overrides.length
@overrides.each do |key,val|
message.append_string key.to_s
message.append_int AttributeTypes[val[:type]]
message.append_int val[:values].length
val[:values].each do |id,map|
message.append_64bit_int id
method = case val[:type]
when :float
:append_float
when :bigint
:append_64bit_int
else
:append_int
end
message.send method, map
end
end
message.append_string @select
message.to_s
end
# Generation of the message to send to Sphinx for an excerpts request.
def excerpts_message(options)
message = Message.new
message.append [0, excerpt_flags(options)].pack('N2') # 0 = mode
message.append_string options[:index]
message.append_string options[:words]
# options
message.append_string options[:before_match]
message.append_string options[:after_match]
message.append_string options[:chunk_separator]
message.append_ints options[:limit], options[:around]
message.append_array options[:docs]
message.to_s
end
# Generation of the message to send to Sphinx to update attributes of a
# document.
def update_message(index, attributes, values_by_doc)
message = Message.new
message.append_string index
message.append_array attributes
message.append_int values_by_doc.length
values_by_doc.each do |key,values|
message.append_64bit_int key # document ID
message.append_ints *values # array of new values (integers)
end
message.to_s
end
# Generates the simple message to send to the daemon for a keywords request.
def keywords_message(query, index, return_hits)
message = Message.new
message.append_string query
message.append_string index
message.append_int return_hits ? 1 : 0
message.to_s
end
AttributeHandlers = {
AttributeTypes[:integer] => :next_int,
AttributeTypes[:timestamp] => :next_int,
AttributeTypes[:ordinal] => :next_int,
AttributeTypes[:bool] => :next_int,
AttributeTypes[:float] => :next_float,
AttributeTypes[:bigint] => :next_64bit_int,
AttributeTypes[:string] => :next,
AttributeTypes[:group_concat] => :next,
AttributeTypes[:multi] + AttributeTypes[:integer] => :next_int_array
}
def attribute_from_type(type, response)
handler = AttributeHandlers[type]
response.send handler
end
def excerpt_flags(options)
flags = 1
flags |= 2 if options[:exact_phrase]
flags |= 4 if options[:single_passage]
flags |= 8 if options[:use_boundaries]
flags |= 16 if options[:weight_order]
flags |= 32 if options[:query_mode]
flags |= 64 if options[:force_all_words]
flags |= 128 if options[:load_files]
flags |= 256 if options[:allow_empty]
flags |= 512 if options[:emit_zones]
flags |= 1024 if options[:load_files_scattered]
flags
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/0.9.8.rb | lib/riddle/0.9.8.rb | # frozen_string_literal: true
Riddle.loaded_version = '0.9.8'
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/command_result.rb | lib/riddle/command_result.rb | # frozen_string_literal: true
class Riddle::CommandResult
attr_reader :command, :status, :output
attr_accessor :successful
def initialize(command, status, output = nil, successful = nil)
@command, @status, @output = command, status, output
if successful.nil?
@successful = (@status == 0)
else
@successful = successful
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/query/insert.rb | lib/riddle/query/insert.rb | # frozen_string_literal: true
class Riddle::Query::Insert
attr_reader :columns, :values
def initialize(index, columns = [], values = [])
@index = index
@columns = columns
@values = values.first.is_a?(Array) ? values : [values]
@replace = false
end
def replace!
@replace = true
self
end
def to_sql
"#{command} INTO #{@index} (#{columns_to_s}) VALUES (#{values_to_s})"
end
private
def command
@replace ? 'REPLACE' : 'INSERT'
end
def columns_to_s
columns.collect { |column|
column.to_s == 'id' ? 'id' : "`#{column}`"
}.join(', ')
end
def values_to_s
values.collect { |value_set|
value_set.collect { |value|
translated_value(value)
}.join(', ')
}.join('), (')
end
def translated_value(value)
case value
when String
"'#{Riddle::Query.sql_escape(value).gsub(/\s+/, ' ')}'"
when TrueClass, FalseClass
value ? 1 : 0
when Time
value.to_i
when Date
value.to_time.to_i
when Array
"(#{value.join(',')})"
else
value
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/query/delete.rb | lib/riddle/query/delete.rb | # frozen_string_literal: true
class Riddle::Query::Delete
def initialize(index, *ids)
@index = index
@ids = ids.flatten
end
def to_sql
if @ids.length > 1
"DELETE FROM #{@index} WHERE id IN (#{@ids.join(', ')})"
else
"DELETE FROM #{@index} WHERE id = #{@ids.first}"
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/query/select.rb | lib/riddle/query/select.rb | # frozen_string_literal: true
class Riddle::Query::Select
def initialize
@values = []
@indices = []
@matching = nil
@wheres = {}
@where_alls = {}
@where_nots = {}
@where_not_alls = {}
@group_by = nil
@group_best = nil
@having = []
@order_by = nil
@order_within_group_by = nil
@offset = nil
@limit = nil
@options = {}
end
def values(*values)
@values += values
self
end
def prepend_values(*values)
@values.insert 0, *values
self
end
def from(*indices)
@indices += indices
self
end
def matching(match)
@matching = match
self
end
def where(filters = {})
@wheres.merge!(filters)
self
end
def where_all(filters = {})
@where_alls.merge!(filters)
self
end
def where_not(filters = {})
@where_nots.merge!(filters)
self
end
def where_not_all(filters = {})
@where_not_alls.merge!(filters)
self
end
def group_by(attribute)
@group_by = attribute
self
end
def group_best(count)
@group_best = count
self
end
def having(*conditions)
@having += conditions
self
end
def order_by(order)
@order_by = order
self
end
def order_within_group_by(order)
@order_within_group_by = order
self
end
def limit(limit)
@limit = limit
self
end
def offset(offset)
@offset = offset
self
end
def with_options(options = {})
@options.merge! options
self
end
def to_sql
sql = StringIO.new String.new(""), "w"
sql << "SELECT #{ extended_values } FROM #{ @indices.join(', ') }"
sql << " WHERE #{ combined_wheres }" if wheres?
sql << " #{group_prefix} #{escape_columns(@group_by)}" if !@group_by.nil?
unless @order_within_group_by.nil?
sql << " WITHIN GROUP ORDER BY #{escape_columns(@order_within_group_by)}"
end
sql << " HAVING #{@having.join(' AND ')}" unless @having.empty?
sql << " ORDER BY #{escape_columns(@order_by)}" if !@order_by.nil?
sql << " #{limit_clause}" unless @limit.nil? && @offset.nil?
sql << " #{options_clause}" unless @options.empty?
sql.string
end
private
def extended_values
@values.empty? ? '*' : @values.join(', ')
end
def group_prefix
['GROUP', @group_best, 'BY'].compact.join(' ')
end
def wheres?
!(@wheres.empty? && @where_alls.empty? && @where_nots.empty? && @where_not_alls.empty? && @matching.nil?)
end
def combined_wheres
wheres = wheres_to_s
if @matching.nil?
wheres
elsif wheres.empty?
"MATCH(#{Riddle::Query.quote @matching})"
else
"MATCH(#{Riddle::Query.quote @matching}) AND #{wheres}"
end
end
def wheres_to_s
(
@wheres.keys.collect { |key|
filter_comparison_and_value key, @wheres[key]
} +
@where_alls.collect { |key, values|
values.collect { |value|
filter_comparison_and_value key, value
}
} +
@where_nots.keys.collect { |key|
exclusive_filter_comparison_and_value key, @where_nots[key]
} +
@where_not_alls.collect { |key, values|
'(' + values.collect { |value|
exclusive_filter_comparison_and_value key, value
}.join(' OR ') + ')'
}
).flatten.compact.join(' AND ')
end
def filter_comparison_and_value(attribute, value)
case value
when Array
if !value.flatten.empty?
"#{escape_column(attribute)} IN (#{value.collect { |val| filter_value(val) }.join(', ')})"
end
when Range
"#{escape_column(attribute)} BETWEEN #{filter_value(value.first)} AND #{filter_value(value.last)}"
else
"#{escape_column(attribute)} = #{filter_value(value)}"
end
end
def exclusive_filter_comparison_and_value(attribute, value)
case value
when Array
if !value.flatten.empty?
"#{escape_column(attribute)} NOT IN (#{value.collect { |val| filter_value(val) }.join(', ')})"
end
when Range
"#{escape_column(attribute)} < #{filter_value(value.first)} OR #{attribute} > #{filter_value(value.last)}"
else
"#{escape_column(attribute)} <> #{filter_value(value)}"
end
end
def filter_value(value)
case value
when TrueClass
1
when FalseClass
0
when Time
value.to_i
when Date
Time.utc(value.year, value.month, value.day).to_i
when String
"'#{value.gsub("'", "\\'")}'"
else
value
end
end
def limit_clause
if @offset.nil?
"LIMIT #{@limit}"
else
"LIMIT #{@offset}, #{@limit || 20}"
end
end
def options_clause
'OPTION ' + @options.keys.collect { |key|
"#{key}=#{option_value @options[key]}"
}.join(', ')
end
def option_value(value)
case value
when Hash
'(' + value.collect { |key, value| "#{key}=#{value}" }.join(', ') + ')'
else
value
end
end
def escape_column(column)
if column.to_s[/\A[`@]/] || column.to_s[/\A\w+\(/] || column.to_s[/\A\w+[.\[]/]
column
else
column_name, *extra = column.to_s.split(' ')
extra.unshift("`#{column_name}`").compact.join(' ')
end
end
def escape_columns(columns)
columns.to_s.split(/,\s*/).collect { |column|
escape_column(column)
}.join(', ')
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/1.10/client.rb | lib/riddle/1.10/client.rb | # frozen_string_literal: true
Riddle::Client::Versions[:search] = 0x117
Riddle::Client::Versions[:excerpt] = 0x102
class Riddle::Client
private
# Generation of the message to send to Sphinx for an excerpts request.
def excerpts_message(options)
message = Message.new
message.append [0, excerpt_flags(options)].pack('N2') # 0 = mode
message.append_string options[:index]
message.append_string options[:words]
# options
message.append_string options[:before_match]
message.append_string options[:after_match]
message.append_string options[:chunk_separator]
message.append_ints options[:limit], options[:around]
message.append_ints options[:limit_passages], options[:limit_words]
message.append_ints options[:start_passage_id]
message.append_string options[:html_strip_mode]
if Versions[:excerpt] >= 0x103
message.append_string options[:passage_boundary]
end
message.append_array options[:docs]
message.to_s
end
end | ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/0.9.9/client.rb | lib/riddle/0.9.9/client.rb | # frozen_string_literal: true
Riddle::Client::Versions[:search] = 0x116
Riddle::Client::Versions[:update] = 0x102
class Riddle::Client
private
def initialise_connection(available_server)
socket = initialise_socket(available_server)
# Send version
socket.send [1].pack('N'), 0
# Checking version
version = socket.recv(4).unpack('N*').first
if version < 1
socket.close
raise Riddle::VersionError, "Can only connect to searchd version 1.0 or better, not version #{version}"
end
socket
end
def update_message(index, attributes, values_by_doc)
message = Message.new
message.append_string index
message.append_int attributes.length
attributes.each_with_index do |attribute, index|
message.append_string attribute
message.append_boolean values_by_doc.values.first[index].is_a?(Array)
end
message.append_int values_by_doc.length
values_by_doc.each do |key,values|
message.append_64bit_int key # document ID
values.each do |value|
case value
when Array
message.append_int value.length
message.append_ints *value
else
message.append_int value
end
end
end
message.to_s
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/0.9.9/configuration/searchd.rb | lib/riddle/0.9.9/configuration/searchd.rb | # frozen_string_literal: true
module Riddle
class Configuration
class Searchd
NUMBER = 1.class
def valid?
set_listen
!( @listen.nil? || @listen.empty? || @pid_file.nil? )
end
private
def set_listen
@listen = @listen.to_s if @listen.is_a?(NUMBER)
return unless @listen.nil? || @listen.empty?
@listen = []
@listen << @port.to_s if @port
@listen << "9306:mysql41" if @mysql41.is_a?(TrueClass)
@listen << "#{@mysql41}:mysql41" if @mysql41.is_a?(NUMBER)
if @listen.empty? && @address
@listen << @address
else
@listen = @listen.collect { |line| "#{@address}:#{line}" } if @address
end
@listen += Array(@socket) if @socket
end
def settings
@listen.nil? ? super : super - [:address, :port]
end
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/0.9.9/client/filter.rb | lib/riddle/0.9.9/client/filter.rb | # frozen_string_literal: true
class Riddle::Client::Filter
#
private
def append_integer_range(message, range)
message.append_64bit_ints self.values.first, self.values.last
end
def append_array(message, array)
message.append_64bit_ints *array.collect { |val|
case val
when TrueClass
1
when FalseClass
0
else
val
end
}
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/configuration/source.rb | lib/riddle/configuration/source.rb | # frozen_string_literal: true
module Riddle
class Configuration
class Source < Riddle::Configuration::Section
attr_accessor :name, :parent, :type
def render
raise ConfigurationError unless valid?
inherited_name = "#{name}"
inherited_name += " : #{parent}" if parent
(
["source #{inherited_name}", "{"] +
settings_body +
["}", ""]
).join("\n")
end
def valid?
!( @name.nil? || @type.nil? )
end
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/configuration/common.rb | lib/riddle/configuration/common.rb | # frozen_string_literal: true
module Riddle
class Configuration
class Common < Riddle::Configuration::Section
def self.settings
[
:lemmatizer_base, :json_autoconv_numbers, :json_autoconv_keynames,
:on_json_attr_error, :rlp_root, :rlp_environment, :rlp_max_batch_size,
:rlp_max_batch_docs, :plugin_dir
]
end
attr_accessor :common_sphinx_configuration, *settings
def render
return unless common_sphinx_configuration
raise ConfigurationError unless valid?
(
["common", "{"] +
settings_body +
["}", ""]
).join("\n")
end
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/configuration/index.rb | lib/riddle/configuration/index.rb | # frozen_string_literal: true
module Riddle
class Configuration
class Index < Riddle::Configuration::Section
include Riddle::Configuration::IndexSettings
def self.settings
Riddle::Configuration::IndexSettings.settings + [:source]
end
attr_accessor :parent, :sources
def initialize(name, *sources)
@name = name
@sources = sources
initialize_settings
end
def source
@sources.collect { |s| s.name }
end
def render
raise ConfigurationError, "#{@name} #{@sources.inspect} #{@path} #{@parent}" unless valid?
inherited_name = parent ? "#{name} : #{parent}" : "#{name}"
(
@sources.collect { |s| s.render } +
["index #{inherited_name}", "{"] +
settings_body +
["}", ""]
).join("\n")
end
def valid?
(!@name.nil?) && (!( @sources.length == 0 || @path.nil? ) || !@parent.nil?)
end
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.