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
sous-chefs/git
https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/test/integration/resources/git_installed_spec.rb
test/integration/resources/git_installed_spec.rb
# rubocop:disable Chef/Deprecations/ResourceWithoutUnifiedTrue home_dir = if os.family == 'windows' if user('vagrant') 'C:/Users/vagrant' else 'C:/Users/RUNNER~1' end elsif os.family == 'darwin' '/Users/random' else '/home/random' end repo_dir = if os.family == 'windows' 'C:/temp' else home_dir end etc_dir = if os.family == 'windows' 'C:/Program Files/Git/etc' elsif os.family == 'darwin' '/usr/local/etc' else '/etc' end describe command('git --version') do its('exit_status') { should eq 0 } its('stdout') { should match /git version/ } end describe ini("#{home_dir}/.gitconfig") do its(%w(user name)) { should eq 'John Doe global' } end describe ini("#{repo_dir}/git_repo/.git/config") do its(%w(user name)) { should eq 'John Doe local' } end describe ini("#{etc_dir}/gitconfig") do its(%w(user name)) { should eq 'John Doe system' } its(['url "https://github.com/"', 'insteadOf']) { should eq 'git://github.com/' } end describe ini('/root/.gitconfig.key') do its(%w(user signingkey)) { should eq 'FA2D8E280A6DD5' } end
ruby
Apache-2.0
83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43
2026-01-04T17:56:43.177115Z
false
sous-chefs/git
https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/test/fixtures/cookbooks/test/metadata.rb
test/fixtures/cookbooks/test/metadata.rb
name 'test' version '0.1.0' depends 'git'
ruby
Apache-2.0
83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43
2026-01-04T17:56:43.177115Z
false
sous-chefs/git
https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/test/fixtures/cookbooks/test/recipes/source.rb
test/fixtures/cookbooks/test/recipes/source.rb
apt_update include_recipe 'git::source'
ruby
Apache-2.0
83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43
2026-01-04T17:56:43.177115Z
false
sous-chefs/git
https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/test/fixtures/cookbooks/test/recipes/default.rb
test/fixtures/cookbooks/test/recipes/default.rb
apt_update git_client 'install it' home_dir = if windows? 'C:\temp' elsif macos? '/Users/random' else '/home/random' end user 'random' do manage_home true home home_dir end unless windows? directory 'C:\temp' if windows? git_config 'add name to random' do user 'random' unless windows? scope 'global' key 'user.name' value 'John Doe global' end git "#{home_dir}/git_repo" do repository 'https://github.com/chef/chef-repo.git' user 'random' unless windows? end git_config 'change local path' do user 'random' unless windows? scope 'local' key 'user.name' value 'John Doe local' path "#{home_dir}/git_repo" end git_config 'change system config' do scope 'system' key 'user.name' value 'John Doe system' end git_config 'url.https://github.com/.insteadOf' do value 'git://github.com/' scope 'system' options '--add' end git_config 'user.signingkey' do value 'FA2D8E280A6DD5' scope 'file' config_file '~/.gitconfig.key' end
ruby
Apache-2.0
83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43
2026-01-04T17:56:43.177115Z
false
sous-chefs/git
https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/test/fixtures/cookbooks/test/recipes/server.rb
test/fixtures/cookbooks/test/recipes/server.rb
apt_update include_recipe 'git::server'
ruby
Apache-2.0
83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43
2026-01-04T17:56:43.177115Z
false
sous-chefs/git
https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/recipes/source.rb
recipes/source.rb
# # Cookbook:: git # Recipe:: source # # Copyright:: 2012-2016, Brian Flad, Fletcher Nichol # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # drive version from node attributes git_client 'default' do source_checksum node['git']['checksum'] source_prefix node['git']['prefix'] source_url format(node['git']['url'], version: node['git']['version']) source_use_pcre node['git']['use_pcre'] source_version node['git']['version'] action :install_from_source end
ruby
Apache-2.0
83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43
2026-01-04T17:56:43.177115Z
false
sous-chefs/git
https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/recipes/default.rb
recipes/default.rb
# # Cookbook:: git # Recipe:: default # # Copyright:: 2008-2019, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. include_recipe 'git::package'
ruby
Apache-2.0
83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43
2026-01-04T17:56:43.177115Z
false
sous-chefs/git
https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/recipes/package.rb
recipes/package.rb
# # Cookbook:: git # Recipe:: package # # Copyright:: 2008-2019, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. git_client 'default'
ruby
Apache-2.0
83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43
2026-01-04T17:56:43.177115Z
false
sous-chefs/git
https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/recipes/windows.rb
recipes/windows.rb
# # Cookbook:: git # Recipe:: windows # # Copyright:: 2008-2019, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. git_client 'default' do windows_display_name node['git']['display_name'] windows_package_url format(node['git']['url'], version: node['git']['version'], architecture: node['git']['architecture']) windows_package_checksum node['git']['checksum'] end
ruby
Apache-2.0
83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43
2026-01-04T17:56:43.177115Z
false
sous-chefs/git
https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/attributes/default.rb
attributes/default.rb
# # Author:: Jamie Winsor (<jamie@vialstudios.com>) # Cookbook:: git # Attributes:: default # # Copyright:: 2008-2019, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. if platform_family?('windows') default['git']['version'] = '2.35.1' if node['kernel']['machine'] == 'x86_64' default['git']['architecture'] = '64' default['git']['checksum'] = '5d66948e7ada0ab184b2745fdf6e11843443a97655891c3c6268b5985b88bf4f' else default['git']['architecture'] = '32' default['git']['checksum'] = '5e45b1226b106dd241de0be0b350052afe53bd61dce80ac6044600dc85fbfa0b' end default['git']['url'] = 'https://github.com/git-for-windows/git/releases/download/v%{version}.windows.1/Git-%{version}-%{architecture}-bit.exe' default['git']['display_name'] = "Git version #{node['git']['version']}" else default['git']['prefix'] = '/usr/local' default['git']['version'] = '2.17.1' default['git']['url'] = 'https://nodeload.github.com/git/git/tar.gz/v%{version}' default['git']['checksum'] = '690f12cc5691e5adaf2dd390eae6f5acce68ae0d9bd9403814f8a1433833f02a' default['git']['use_pcre'] = false end default['git']['server']['base_path'] = '/srv/git' default['git']['server']['export_all'] = true
ruby
Apache-2.0
83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43
2026-01-04T17:56:43.177115Z
false
sous-chefs/git
https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/spec/spec_helper.rb
spec/spec_helper.rb
require 'chefspec' require 'chefspec/berkshelf' RSpec.configure do |config| config.formatter = :documentation # Use the specified formatter config.color = true config.log_level = :fatal # ignore warnings config.alias_example_group_to :describe_recipe, type: :recipe config.alias_example_group_to :describe_resource, type: :resource config.alias_example_group_to :describe_attribute, type: :attribute config.filter_run :focus config.run_all_when_everything_filtered = true Kernel.srand config.seed config.order = :random config.default_formatter = 'doc' if config.files_to_run.one? config.expect_with :rspec do |expectations| expectations.syntax = :expect end config.mock_with :rspec do |mocks| mocks.syntax = :expect mocks.verify_partial_doubles = true end end RSpec.shared_context 'recipe tests', type: :recipe do let(:chef_run) { ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '16.04').converge(described_recipe) } end
ruby
Apache-2.0
83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43
2026-01-04T17:56:43.177115Z
false
sous-chefs/git
https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/spec/unit/recipes/source_spec.rb
spec/unit/recipes/source_spec.rb
require_relative '../../spec_helper' describe 'git::source' do platform 'ubuntu' step_into :git_client before do stub_command(%r{test -f /tmp/.+/git-2.17.1.tar.gz}) stub_command('git --version | grep 2.17.1') stub_command('/usr/local/bin/git --version | grep 2.17.1') end it do is_expected.to install_from_source_git_client('default').with( source_checksum: '690f12cc5691e5adaf2dd390eae6f5acce68ae0d9bd9403814f8a1433833f02a', source_prefix: '/usr/local', source_url: 'https://nodeload.github.com/git/git/tar.gz/v2.17.1', source_use_pcre: false, source_version: '2.17.1' ) end end
ruby
Apache-2.0
83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43
2026-01-04T17:56:43.177115Z
false
sous-chefs/git
https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/spec/unit/recipes/default_spec.rb
spec/unit/recipes/default_spec.rb
require_relative '../../spec_helper' describe 'git::default' do context 'on windows' do let(:chef_run) do ChefSpec::ServerRunner.new( platform: 'windows', version: '10' ).converge(described_recipe) end it { is_expected.to install_git_client('default') } end context 'on linux' do platform 'ubuntu' it { is_expected.to install_git_client('default') } end end
ruby
Apache-2.0
83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43
2026-01-04T17:56:43.177115Z
false
sous-chefs/git
https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/spec/unit/recipes/windows_spec.rb
spec/unit/recipes/windows_spec.rb
require_relative '../../spec_helper' describe_recipe 'git::windows' do let(:chef_run) do ChefSpec::ServerRunner.new( platform: 'windows', version: '10' ).converge(described_recipe) end it do expect(chef_run).to install_git_client('default').with( windows_display_name: 'Git version 2.35.1', windows_package_url: 'https://github.com/git-for-windows/git/releases/download/v2.35.1.windows.1/Git-2.35.1-64-bit.exe', windows_package_checksum: '5d66948e7ada0ab184b2745fdf6e11843443a97655891c3c6268b5985b88bf4f' ) end end
ruby
Apache-2.0
83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43
2026-01-04T17:56:43.177115Z
false
sous-chefs/git
https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/libraries/helpers.rb
libraries/helpers.rb
module GitCookbook module Helpers # linux packages default to distro offering def parsed_package_name return new_resource.package_name if new_resource.package_name return 'developer/versioning/git' if platform?('omnios') return 'scmgit' if platform?('smartos') 'git' end def parsed_package_version new_resource.package_version if new_resource.package_version end # source def parsed_source_url return new_resource.source_url if new_resource.source_url "https://nodeload.github.com/git/git/tar.gz/v#{new_resource.source_version}" end def parsed_source_checksum return new_resource.source_checksum if new_resource.source_checksum '690f12cc5691e5adaf2dd390eae6f5acce68ae0d9bd9403814f8a1433833f02a' # 2.17.1 tarball end # windows def parsed_windows_display_name return new_resource.windows_display_name if new_resource.windows_display_name "Git version #{parsed_windows_package_version}" end def parsed_windows_package_version return new_resource.windows_package_version if new_resource.windows_package_version '2.39.2' end def parsed_windows_package_url return new_resource.windows_package_url if new_resource.windows_package_url if node['kernel']['machine'] == 'x86_64' "https://github.com/git-for-windows/git/releases/download/v#{parsed_windows_package_version}.windows.1/Git-#{parsed_windows_package_version}-64-bit.exe" else "https://github.com/git-for-windows/git/releases/download/v#{parsed_windows_package_version}.windows.1/Git-#{parsed_windows_package_version}-32-bit.exe" end end def parsed_windows_package_checksum return new_resource.windows_package_checksum if new_resource.windows_package_checksum if node['kernel']['machine'] == 'x86_64' 'D7608FBD854B3689102FF48B03C8CC77B35138F9F7350D134306DA0BA5751464' else 'ADDF55B0A57F38A7950B3AD37CE5C76752202E6818D9F8995B477496B71FB757' end end end end
ruby
Apache-2.0
83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43
2026-01-04T17:56:43.177115Z
false
sous-chefs/git
https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/resources/client_linux.rb
resources/client_linux.rb
unified_mode true provides :git_client, os: 'linux' # :install property :package_name, String property :package_version, String property :package_action, Symbol, default: :install # :install_from_source property :source_checksum, String property :source_prefix, String, default: '/usr/local' property :source_url, String property :source_use_pcre, [true, false], default: false property :source_version, String action_class do include GitCookbook::Helpers end action :install do # Software installation package "#{new_resource.name} :create #{parsed_package_name}" do package_name parsed_package_name version parsed_package_version action new_resource.package_action end end action :install_from_source do raise "source install is not supported on #{node['platform']}" unless platform_family?('rhel', 'suse', 'fedora', 'debian', 'amazon') build_essential 'install compilation tools for git' case node['platform_family'] when 'rhel', 'fedora', 'amazon' pkgs = %w(tar expat-devel gettext-devel libcurl-devel openssl-devel perl-ExtUtils-MakeMaker zlib-devel) pkgs << 'pcre-devel' if new_resource.source_use_pcre when 'debian' pkgs = %w(libcurl4-gnutls-dev libexpat1-dev gettext libz-dev libssl-dev) pkgs << 'libpcre3-dev' if new_resource.source_use_pcre when 'suse' pkgs = %w(tar libcurl-devel libexpat-devel gettext-tools zlib-devel libopenssl-devel) pkgs << 'libpcre2-devel' if new_resource.source_use_pcre end package pkgs ark 'git' do url parsed_source_url extension 'tar.gz' version new_resource.source_version checksum parsed_source_checksum make_opts ["prefix=#{new_resource.source_prefix}", ('USE_LIBPCRE=1' if new_resource.source_use_pcre)] action :install_with_make end end
ruby
Apache-2.0
83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43
2026-01-04T17:56:43.177115Z
false
sous-chefs/git
https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/resources/client_windows.rb
resources/client_windows.rb
unified_mode true provides :git_client, os: 'windows' property :windows_display_name, String property :windows_package_url, String property :windows_package_checksum, String property :windows_package_version, String action_class do include GitCookbook::Helpers end action :install do windows_package parsed_windows_display_name do source parsed_windows_package_url checksum parsed_windows_package_checksum version parsed_windows_package_version installer_type :inno end # Git is installed to Program Files (x86) on 64-bit machines and # 'Program Files' on 32-bit machines PROGRAM_FILES = if node['git']['architecture'] == '32' ENV['ProgramFiles(x86)'] || ENV['ProgramFiles'] else ENV['ProgramW6432'] || ENV['ProgramFiles'] end GIT_PATH = "#{PROGRAM_FILES}\\Git\\Cmd".freeze # COOK-3482 - windows_path resource doesn't change the current process # environment variables. Therefore, git won't actually be on the PATH # until the next chef-client run ruby_block 'Add Git Path' do block do ENV['PATH'] += ";#{GIT_PATH}" end not_if { ENV['PATH'] =~ /GIT_PATH/ } action :nothing end windows_path GIT_PATH do notifies :run, 'ruby_block[Add Git Path]', :immediately end end
ruby
Apache-2.0
83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43
2026-01-04T17:56:43.177115Z
false
sous-chefs/git
https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/resources/config.rb
resources/config.rb
unified_mode true property :key, String, name_property: true property :value, String property :scope, String, equal_to: %w(local global system file), default: 'global', desired_state: false property :config_file, String, desired_state: false property :path, String, desired_state: false property :user, String, desired_state: false property :group, String, desired_state: false property :password, String, desired_state: false, sensitive: true property :options, String, desired_state: false load_current_value do begin home_dir = ::Dir.home(user) rescue value nil end cmd_env = user ? { 'USER' => user, 'HOME' => home_dir } : nil config_vals = Mixlib::ShellOut.new( "git config --get --#{scope} #{config_file} #{key}", user: user, group: group, password: password, cwd: path, env: cmd_env ) config_vals.run_command if config_vals.stdout.empty? value nil else value config_vals.stdout.chomp end end action :set do converge_if_changed do execute "#{config_cmd} #{new_resource.key} \"#{new_resource.value}\" #{new_resource.options}".rstrip do cwd new_resource.path user new_resource.user group new_resource.group password new_resource.password environment cmd_env end end end action_class do def config_cmd "git config --#{new_resource.scope} #{new_resource.config_file}" end def cmd_env new_resource.user ? { 'USER' => new_resource.user, 'HOME' => ::Dir.home(new_resource.user) } : nil end end
ruby
Apache-2.0
83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43
2026-01-04T17:56:43.177115Z
false
sous-chefs/git
https://github.com/sous-chefs/git/blob/83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43/resources/client_osx.rb
resources/client_osx.rb
unified_mode true provides :git_client, platform: 'mac_os_x' action :install do package 'git' do options '--override' end end
ruby
Apache-2.0
83fff1e6e1fd5a8fa180531ba9f5ac51769a7c43
2026-01-04T17:56:43.177115Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/app/controllers/hotsheet/sheets_controller.rb
app/controllers/hotsheet/sheets_controller.rb
# frozen_string_literal: true class Hotsheet::SheetsController < Hotsheet::ApplicationController before_action :set_sheet before_action :set_column, only: :update before_action :set_resource, only: :update def index @columns = @sheet.columns @cells, @config = @sheet.cells_for @columns, params end def update if @resource.update params[:column_name] => params[:value] respond else respond @resource.errors.full_messages.first end end private def set_sheet @sheet = Hotsheet.sheets[params[:sheet_name]] render "hotsheet/home/error", status: :not_found if @sheet.nil? end def set_column @column = @sheet.columns[params[:column_name]] return respond Hotsheet.t "error_not_found" if @column.nil? respond Hotsheet.t "error_forbidden" unless @column.editable? end def set_resource @resource = @sheet.model.find_by id: params[:id] respond Hotsheet.t "error_not_found" if @resource.nil? end def respond(message = "") respond_to { |format| format.any { render json: message.to_json } } end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/app/controllers/hotsheet/home_controller.rb
app/controllers/hotsheet/home_controller.rb
# frozen_string_literal: true class Hotsheet::HomeController < Hotsheet::ApplicationController def show; end def error render "error", status: :not_found end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/app/controllers/hotsheet/application_controller.rb
app/controllers/hotsheet/application_controller.rb
# frozen_string_literal: true class Hotsheet::ApplicationController < ActionController::Base protect_from_forgery with: :exception # :nocov: ENV["HOTSHEET_BASIC_AUTH"]&.split(":")&.then do |name, password| http_basic_authenticate_with name:, password: end # :nocov: end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true ENV["RAILS_ENV"] = "test" begin require "simplecov" SimpleCov.start "rails" do add_filter %w[lib/generators/templates lib/hotsheet/engine.rb lib/hotsheet/version.rb] enable_coverage :branch minimum_coverage line: 100, branch: 100 end rescue LoadError nil end require_relative "dummy/config/environment" require_relative "support/utils" require "rspec/rails" require "selenium-webdriver" %i[firefox firefox_headless].each do |driver| Capybara.register_driver driver do |app| args = ["--headless"] if driver == :firefox_headless options = Selenium::WebDriver::Firefox::Options.new args: args Capybara::Selenium::Driver.new app, browser: :firefox, options: options end end driver = ENV.fetch("SELENIUM_DRIVER", "firefox_headless").to_sym Capybara.default_driver = :rack_test Capybara.javascript_driver = driver ActionController::Base.allow_forgery_protection = false ActiveRecord::Migration.maintain_test_schema! RSpec.configure do |config| Kernel.srand config.seed config.include Capybara::DSL, type: :system config.include Capybara::RSpecMatchers, type: :request config.disable_monkey_patching! config.filter_rails_from_backtrace! config.infer_spec_type_from_file_location! config.mock_with(:rspec) { |mocks| mocks.verify_partial_doubles = true } config.order = :random config.run_all_when_everything_filtered = true config.use_transactional_fixtures = true if config.respond_to? :fixture_paths config.fixture_paths = ["spec/fixtures"] else config.fixture_path = "spec/fixtures" end config.before :all, type: :system do driven_by driver, screen_size: [1280, 800] end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/system/hotsheet/sheets_controller_spec.rb
spec/system/hotsheet/sheets_controller_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe Hotsheet::SheetsController do fixtures :users let(:user) { users(:admin) } before { prepare { Hotsheet.configure { sheet :User } } } it "updates the cell value" do visit hotsheet.sheets_path :users find(".cell", text: user.name).click.send_keys(:enter).fill_in(with: "Admin").send_keys :enter expect { find(".cell", text: user.email).click } .to change { user.reload.name }.from("Admin User").to "Admin" end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/support/utils.rb
spec/support/utils.rb
# frozen_string_literal: true def prepare(&) Hotsheet.instance_variable_set :@sheets, nil # reset memoized sheets yield end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/requests/hotsheet/home_controller_spec.rb
spec/requests/hotsheet/home_controller_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe Hotsheet::HomeController do describe "#error" do it "shows an error page" do get "/hotsheet/invalid/route" expect(response).to be_not_found expect(response.body).to include Hotsheet.t("error_not_found") end end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/requests/hotsheet/sheets_controller_spec.rb
spec/requests/hotsheet/sheets_controller_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe Hotsheet::SheetsController do fixtures :users let(:user) { users(:admin) } let(:config) { Hotsheet.configure { sheet(:User) { column :name } } } before { prepare { config } } describe "#index" do it "shows a spreadsheet with all values" do get hotsheet.sheets_path :users expect(response).to be_successful expect(response.body).to include user.name expect(response.body).to have_no_css ".load-more" end context "with :per configured" do let(:config) { Hotsheet.configure { sheet(:User, per: 1) { column :name } } } let!(:other_user) { User.create!(name: "2nd Page", handle: "2", email: "2nd@local") } it "has a button to load more" do get hotsheet.sheets_path :users expect(response.body).to include user.name expect(response.body).not_to include other_user.name expect(response.body).to include Hotsheet.t("button_load_more", count: 1, total: User.count) end it "can show the second page directly" do get hotsheet.sheets_path :users, page: 2 expect(response.body).to include other_user.name expect(response.body).not_to include user.name end it "shows the first page if the page count is invalid" do get hotsheet.sheets_path :users, page: 100 expect(response.body).to include user.name expect(response.body).not_to include other_user.name expect(response.body).to have_no_css ".load-more" end end context "when the sheet does not exist" do it "shows an error page" do get "/hotsheet/authors" expect(response).to be_not_found expect(response.body).to include Hotsheet.t("error_not_found") end end end describe "#update" do let(:path) { hotsheet.sheet_path :users, user } it "updates the resource" do expect { put path, params: { column_name: :name, value: "Bob" } } .to change { user.reload.name }.from("Admin User").to "Bob" end context "when the column is not editable" do let(:config) { Hotsheet.configure { sheet(:User) { column :name, editable: false } } } it "does not update the resource" do expect { put path, params: { column_name: :name, value: "Bob" } }.not_to change(user, :reload) expect(response.parsed_body).to eq Hotsheet.t("error_forbidden") end end context "with invalid value" do it "does not update the resource" do expect { put path, params: { column_name: :name, value: "B" } }.not_to change(user, :reload) expect(response.parsed_body).to eq "Name is too short (minimum is 2 characters)" end end context "with nonexistent id" do let(:path) { hotsheet.sheet_path :users, 0 } it "does not update the resource" do expect { put path, params: { column_name: :name, value: "Bob" } }.not_to change(user, :reload) expect(response.parsed_body).to eq Hotsheet.t("error_not_found") end end context "with nonexistent column" do it "does not update the resource" do expect { put path, params: { column_name: :age, value: 21 } }.not_to change(user, :reload) expect(response.parsed_body).to eq Hotsheet.t("error_not_found") end end context "with missing params" do it "does not update the resource" do expect { put path }.not_to change(user, :reload) expect(response.parsed_body).to eq Hotsheet.t("error_not_found") end end end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/dummy/app/controllers/application_controller.rb
spec/dummy/app/controllers/application_controller.rb
# frozen_string_literal: true class ApplicationController < ActionController::Base def index redirect_to "/hotsheet" end protected def current_user @current_user ||= User.first end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/dummy/app/models/tag.rb
spec/dummy/app/models/tag.rb
# frozen_string_literal: true class Tag < ApplicationRecord has_many :post_tags, dependent: :destroy has_many :posts, through: :post_tags validates :name, presence: true, length: { in: 1..20 } validates :color, presence: true, format: { with: /\A[0-9a-f]{6}\z/ } end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/dummy/app/models/post.rb
spec/dummy/app/models/post.rb
# frozen_string_literal: true class Post < ApplicationRecord belongs_to :user has_many :post_tags, dependent: :destroy has_many :tags, through: :post_tags validates :title, presence: true, length: { in: 2..50 } validates :body, presence: true, length: { in: 2..250 } end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/dummy/app/models/application_record.rb
spec/dummy/app/models/application_record.rb
# frozen_string_literal: true class ApplicationRecord < ActiveRecord::Base if Rails::VERSION::MAJOR >= 7 primary_abstract_class else self.abstract_class = true end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/dummy/app/models/post_tag.rb
spec/dummy/app/models/post_tag.rb
# frozen_string_literal: true class PostTag < ApplicationRecord belongs_to :post belongs_to :tag end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/dummy/app/models/user.rb
spec/dummy/app/models/user.rb
# frozen_string_literal: true class User < ApplicationRecord has_many :posts, dependent: :destroy STATUS = { invisible: 0, do_not_disturb: 1, idle: 2, online: 3 }.freeze if Rails::VERSION::MAJOR >= 7 enum :status, STATUS, default: :invisible else enum status: STATUS, _default: :invisible # rubocop:disable Rails/EnumSyntax end validates :name, presence: true, length: { in: 2..40 } validates :handle, presence: true, length: { in: 1..20 }, uniqueness: true validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }, uniqueness: true validates :admin, inclusion: { in: [true, false] } validates :status, presence: true end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/dummy/db/seeds.rb
spec/dummy/db/seeds.rb
# frozen_string_literal: true require "faker" 10.times do handle = Faker::Internet.unique.username specifier: 1..20 User.create! name: Faker::Name.name, handle:, email: Faker::Internet.unique.email(name: handle), birthdate: Faker::Date.birthday, admin: Faker::Boolean.boolean(true_ratio: 0.25), status: User.statuses.keys.sample end 30.times do Post.create! title: Faker::Marketing.buzzwords, body: Faker::Lorem.paragraph, user_id: User.pluck(:id).sample end 5.times do Tag.create! name: Faker::Music.genre.delete(" "), color: Faker::Color.hex_color.slice(1, 6), post_ids: Post.pluck(:id).sample(3) end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/dummy/db/schema.rb
spec/dummy/db/schema.rb
# This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # This file is the source Rails uses to define your schema when running `bin/rails # db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to # be faster and is potentially less error prone than running all of your # migrations from scratch. Old migrations may fail to apply correctly if those # migrations use external dependencies or application code. # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 2025_01_01_010101) do create_table "post_tags", force: :cascade do |t| t.integer "post_id", null: false t.integer "tag_id", null: false t.index ["post_id"], name: "index_post_tags_on_post_id" t.index ["tag_id"], name: "index_post_tags_on_tag_id" end create_table "posts", force: :cascade do |t| t.string "title", null: false t.text "body", null: false t.integer "user_id", null: false t.datetime "created_at", precision: 0, null: false t.datetime "updated_at", precision: 0, null: false t.index ["user_id"], name: "index_posts_on_user_id" end create_table "tags", force: :cascade do |t| t.string "name", null: false t.string "color", null: false t.datetime "created_at", precision: 0, null: false t.datetime "updated_at", precision: 0, null: false end create_table "users", force: :cascade do |t| t.string "name", null: false t.string "handle", null: false t.string "email", null: false t.date "birthdate" t.boolean "admin", default: false, null: false t.integer "status", null: false t.datetime "created_at", precision: 0, null: false t.datetime "updated_at", precision: 0, null: false t.index ["email"], name: "index_users_on_email", unique: true t.index ["handle"], name: "index_users_on_handle", unique: true end add_foreign_key "post_tags", "posts" add_foreign_key "post_tags", "tags" add_foreign_key "posts", "users" end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/dummy/db/migrate/20250101010101_create_models.rb
spec/dummy/db/migrate/20250101010101_create_models.rb
# frozen_string_literal: true class CreateModels < ActiveRecord::Migration[6.1] def change create_users create_posts create_tags create_post_tags end private def create_users create_table :users do |t| t.string :name, null: false t.string :handle, null: false, index: { unique: true } t.string :email, null: false, index: { unique: true } t.date :birthdate t.boolean :admin, null: false, default: false t.integer :status, null: false t.timestamps precision: 0 end end def create_posts create_table :posts do |t| t.string :title, null: false t.text :body, null: false t.references :user, null: false, foreign_key: true t.timestamps precision: 0 end end def create_tags create_table :tags do |t| t.string :name, null: false t.string :color, null: false t.timestamps precision: 0 end end def create_post_tags create_table :post_tags do |t| t.references :post, null: false, foreign_key: true t.references :tag, null: false, foreign_key: true end end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/dummy/config/application.rb
spec/dummy/config/application.rb
# frozen_string_literal: true require "bundler/setup" require "logger" require "action_controller/railtie" require "active_record/railtie" require "active_support/railtie" require "rails" Bundler.require(*Rails.groups) class Dummy < Rails::Application config.load_defaults Rails::VERSION::STRING.to_f config.action_controller.perform_caching = false config.action_dispatch.show_exceptions = :rescuable config.action_view.preload_links_header = false config.active_record.dump_schema_after_migration = true config.active_record.migration_error = :page_load config.active_support.deprecation = :raise config.active_support.report_deprecations = true config.active_support.to_time_preserves_timezone = :zone config.assets.compile = true config.assets.quiet = true config.cache_store = :null_store config.consider_all_requests_local = true config.eager_load = false config.enable_reloading = true config.filter_parameters = %i[passw] config.i18n.available_locales = %i[en de] config.i18n.default_locale = :en config.i18n.fallbacks = false config.i18n.raise_on_missing_translations = true config.log_level = ENV.fetch "LOG_LEVEL", :debug config.session_store :cookie_store, key: "auth", same_site: :strict, secure: false config.time_zone = "Etc/UTC" config.action_dispatch.default_headers = { "Referrer-Policy" => "no-referrer", "X-Content-Type-Options" => "nosniff", "X-Permitted-Cross-Domain-Policies" => "none" } [ ActionDispatch::PermissionsPolicy::Middleware, ActionDispatch::RemoteIp, ActionDispatch::RequestId, Rack::ETag, Rack::Runtime ].each { |middleware| config.middleware.delete middleware } end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/dummy/config/environment.rb
spec/dummy/config/environment.rb
# frozen_string_literal: true require_relative "application" Rails.application.initialize!
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/dummy/config/puma.rb
spec/dummy/config/puma.rb
# frozen_string_literal: true cores = ENV.fetch "RAILS_MAX_THREADS", Concurrent.physical_processor_count env = ENV.fetch "RAILS_ENV", "development" environment env pidfile ENV.fetch "PIDFILE" if ENV.key? "PIDFILE" port ENV.fetch "PORT", 3000 threads cores, cores workers cores if env == "production" plugin :tmp_restart
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/dummy/config/routes.rb
spec/dummy/config/routes.rb
# frozen_string_literal: true Rails.application.routes.draw do mount Hotsheet::Engine, at: :hotsheet root "application#index" end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/dummy/config/initializers/hotsheet.rb
spec/dummy/config/initializers/hotsheet.rb
# frozen_string_literal: true Hotsheet.configure do sheet :Post, per: 10 do column :title column :body column :user_id column :created_at column :updated_at, editable: false end sheet :Tag sheet :User do column :name column :handle, editable: -> { false } column :email column :birthdate column :admin column :status column :created_at, visible: false column :updated_at end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/lib/hotsheet_spec.rb
spec/lib/hotsheet_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe Hotsheet do let(:config) { described_class.configure { sheet :User } } before do described_class.instance_variable_set :@sheets, nil config end it "configures hotsheet" do expect(config.sheets["users"].columns).not_to be_empty end context "with nonexistent sheet" do let(:config) { described_class.configure { sheet :Author } } it "raises an error" do expect { config.sheets }.to raise_error "Unknown model 'Author'" end end describe "#t" do it "falls back to english" do expect { I18n.with_locale(:de) { described_class.t "error_not_found" } }.not_to raise_error end end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/lib/hotsheet/version_spec.rb
spec/lib/hotsheet/version_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe "Hotsheet::VERSION" do it "has a semantic version number" do expect(Hotsheet::VERSION).to match(/\A\d+\.\d+\.\d+\z/) end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/lib/hotsheet/column_spec.rb
spec/lib/hotsheet/column_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe Hotsheet::Column do let(:column) { described_class.new config } let(:config) { {} } it "is editable and visible by default" do expect(column.editable?).to be true expect(column.visible?).to be true end context "with config" do let(:config) { { editable: false, visible: -> { 0 == 1 } } } it "overrides the default" do expect(column.editable?).to be false expect(column.visible?).to be false end end context "with invalid config" do let(:config) { { editable: "no" } } it "raises an error" do expect { column }.to raise_error(/Config 'editable' must be/) end end context "with nonexistent config" do let(:config) { { readonly: true } } it "raises an error" do expect { column }.to raise_error(/Config must be one of/) end end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/lib/hotsheet/sheet_spec.rb
spec/lib/hotsheet/sheet_spec.rb
# frozen_string_literal: true require "spec_helper" RSpec.describe Hotsheet::Sheet do let(:sheet) { described_class.new :User, config, &columns } let(:config) { {} } let(:columns) { ->(_) {} } it "includes the id by default" do expect(sheet.model).to eq User expect(sheet.columns.keys).to eq %w[id] end context "without config" do let(:sheet) { described_class.new :User, config } it "includes all columns" do expect(sheet.columns.keys).to eq %w[id name handle email birthdate admin status created_at updated_at] end end context "with nonexistent column" do let(:columns) { ->(_) { column :age } } it "raises an error" do expect { sheet.column :age }.to raise_error(/Column must be one of/) end end describe "#columns" do let(:columns) { ->(_) { column :name, visible: false } } it "only returns visible columns" do expect(sheet.columns.keys).to eq %w[id] expect(sheet.instance_variable_get(:@columns).keys).to eq %w[id name] end end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/spec/lib/hotsheet/generators/install_generator_spec.rb
spec/lib/hotsheet/generators/install_generator_spec.rb
# frozen_string_literal: true require "spec_helper" require_relative "../../../../lib/generators/hotsheet/install_generator" RSpec.describe Hotsheet::Generators::InstallGenerator do let(:generator) { described_class.new [], [], destination_root: Rails.root.join("tmp") } before do FileUtils.rm_rf Rails.root.join "tmp/config" FileUtils.mkdir_p Rails.root.join "tmp/config" Rails.root.join("tmp/config/routes.rb").write "" end it "creates the initializer and mounts the engine" do out = <<-STDOUT create config/initializers/hotsheet.rb route mount Hotsheet::Engine, at: :hotsheet STDOUT expect { generator.invoke_all }.to output(out).to_stdout end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/lib/hotsheet.rb
lib/hotsheet.rb
# frozen_string_literal: true require "hotsheet/version" require "hotsheet/engine" require "hotsheet/config" module Hotsheet autoload :Column, "#{__dir__}/hotsheet/column" autoload :Sheet, "#{__dir__}/hotsheet/sheet" class Error < StandardError; end class << self include Config attr_reader :config CONFIG = {}.freeze def configure(config = {}, &sheets) @config = [merge_config!(CONFIG, config), sheets] self end def sheets @sheets ||= begin @sheets = {} instance_eval(&@config.pop) @sheets end end I18N = Psych.load_file(Hotsheet::Engine.root.join("config/locales/en.yml"))["en"]["hotsheet"].freeze def t(key, **kwargs) I18n.t "hotsheet.#{key}", default: I18N[key], **kwargs end private def sheet(name, config = {}, &) ensure_sheet_exists! name sheet = Sheet.new(name, config, &) @sheets[sheet.model.table_name] = sheet end def ensure_sheet_exists!(name) return if Object.const_defined? name raise Hotsheet::Error, "Unknown model '#{name}'" end end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/lib/hotsheet/version.rb
lib/hotsheet/version.rb
# frozen_string_literal: true module Hotsheet VERSION = "0.2.2" end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/lib/hotsheet/config.rb
lib/hotsheet/config.rb
# frozen_string_literal: true module Hotsheet::Config def merge_config!(default, custom) config = default.transform_values { |value| value[:default] } custom.each do |key, value| unless default.key? key raise Hotsheet::Error, "Config must be one of #{default.keys}, got '#{key}'" end ensure_allowed_value! key, value, default[key] config[key] = value end config end private def ensure_allowed_value!(key, value, config) allowed = config[:allowed_classes] value = value.class return if allowed.include? value raise Hotsheet::Error, "Config '#{key}' must be one of #{allowed}, got '#{value}'" end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/lib/hotsheet/sheet.rb
lib/hotsheet/sheet.rb
# frozen_string_literal: true class Hotsheet::Sheet include Hotsheet::Config attr_reader :config, :model CONFIG = { per: { allowed_classes: [Integer], default: 100 } }.freeze def initialize(name, config, &columns) @config = merge_config! CONFIG, config @model = name.to_s.constantize @columns = {} column :id, editable: false columns ? instance_eval(&columns) : use_default_configuration end def columns @columns.select { |_name, column| column.visible? } end def cells_for(columns, params) page = page_info params[:page] [@model.order(:id).limit(page[:limit]).offset(page[:offset]).pluck(*columns.keys).transpose, page] end private def page_info(page) total = @model.count page = (page || 1).to_i limit = @config[:per] offset = (1..total.fdiv(limit).ceil).cover?(page) ? page.pred * limit : 0 { count: page * limit, total:, next: page.next, limit:, offset: } end def use_default_configuration @model.column_names[1..].each { |name| column name } end def column(name, config = {}) ensure_column_exists! name @columns[name.to_s] = Hotsheet::Column.new config end def ensure_column_exists!(name) return if @model.column_names.include? name.to_s raise Hotsheet::Error, "Column must be one of #{@model.column_names}, got '#{name}'" end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/lib/hotsheet/engine.rb
lib/hotsheet/engine.rb
# frozen_string_literal: true class Hotsheet::Engine < Rails::Engine isolate_namespace Hotsheet initializer "hotsheet.assets" do |app| app.config.assets.paths << Hotsheet::Engine.root.join("app/assets") app.config.assets.precompile += %w[hotsheet.css hotsheet.js] end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/lib/hotsheet/column.rb
lib/hotsheet/column.rb
# frozen_string_literal: true class Hotsheet::Column include Hotsheet::Config attr_reader :config CONFIG = { editable: { allowed_classes: [FalseClass, Proc], default: true }, visible: { allowed_classes: [FalseClass, Proc], default: true } }.freeze def initialize(config) @config = merge_config! CONFIG, config end def editable? is? :editable end def visible? is? :visible end private def is?(permission) perm = @config[permission] perm.is_a?(Proc) ? perm.call : perm end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/lib/generators/hotsheet/install_generator.rb
lib/generators/hotsheet/install_generator.rb
# frozen_string_literal: true require "rails/generators" module Hotsheet module Generators class InstallGenerator < Rails::Generators::Base source_root File.expand_path "../templates", __dir__ def copy_initializer template "hotsheet.rb", "config/initializers/hotsheet.rb" end def mount_engine route "mount Hotsheet::Engine, at: :hotsheet" end end end end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/lib/generators/templates/hotsheet.rb
lib/generators/templates/hotsheet.rb
# frozen_string_literal: true # Configure the models to be used by Hotsheet. # See https://github.com/renuo/hotsheet/blob/main/README.md#usage. Hotsheet.configure do # Configure the visible and editable columns for each model. # The ID is included as the first column by default. # The number of rows displayed can be configured using the `per` option, # which defaults to 100. # sheet :User, per: 10 do # column :name # column :email, editable: false # column :birthdate, editable: -> { rand > 0.5 } # end # Leave the block out to include all database columns. # sheet :Post end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
renuo/hotsheet
https://github.com/renuo/hotsheet/blob/3855e67e071bdbab46653c03cb6e260a3ec1132e/config/routes.rb
config/routes.rb
# frozen_string_literal: true Hotsheet::Engine.routes.draw do root "home#show" scope ":sheet_name" do resources controller: :sheets, only: %i[index update], as: :sheets end match "*path", to: "home#error", via: :all end
ruby
MIT
3855e67e071bdbab46653c03cb6e260a3ec1132e
2026-01-04T17:56:47.791247Z
false
sstephenson/sprockets-rails
https://github.com/sstephenson/sprockets-rails/blob/8ddad4ce1a93db79187dfbcd06f3d5165568d8d1/install.rb
install.rb
require "fileutils" include FileUtils::Verbose RAILS_ROOT = File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "..")) unless defined?(RAILS_ROOT) mkdir_p File.join(RAILS_ROOT, "vendor", "sprockets") mkdir_p File.join(RAILS_ROOT, "app", "javascripts") touch File.join(RAILS_ROOT, "app", "javascripts", "application.js") cp File.join(File.dirname(__FILE__), "config", "sprockets.yml"), File.join(RAILS_ROOT, "config")
ruby
MIT
8ddad4ce1a93db79187dfbcd06f3d5165568d8d1
2026-01-04T17:56:50.420503Z
false
sstephenson/sprockets-rails
https://github.com/sstephenson/sprockets-rails/blob/8ddad4ce1a93db79187dfbcd06f3d5165568d8d1/init.rb
init.rb
require "sprockets" require "sprockets_helper" require "sprockets_application" class ActionController::Base helper :sprockets end
ruby
MIT
8ddad4ce1a93db79187dfbcd06f3d5165568d8d1
2026-01-04T17:56:50.420503Z
false
sstephenson/sprockets-rails
https://github.com/sstephenson/sprockets-rails/blob/8ddad4ce1a93db79187dfbcd06f3d5165568d8d1/test/sprockets_test.rb
test/sprockets_test.rb
require 'test/unit' class SprocketsTest < Test::Unit::TestCase # Replace this with your real tests. test "the truth" do assert true end end
ruby
MIT
8ddad4ce1a93db79187dfbcd06f3d5165568d8d1
2026-01-04T17:56:50.420503Z
false
sstephenson/sprockets-rails
https://github.com/sstephenson/sprockets-rails/blob/8ddad4ce1a93db79187dfbcd06f3d5165568d8d1/lib/sprockets_helper.rb
lib/sprockets_helper.rb
module SprocketsHelper def sprockets_include_tag javascript_include_tag("/sprockets.js") end end
ruby
MIT
8ddad4ce1a93db79187dfbcd06f3d5165568d8d1
2026-01-04T17:56:50.420503Z
false
sstephenson/sprockets-rails
https://github.com/sstephenson/sprockets-rails/blob/8ddad4ce1a93db79187dfbcd06f3d5165568d8d1/lib/sprockets_controller.rb
lib/sprockets_controller.rb
class SprocketsController < ActionController::Base caches_page :show, :if => Proc.new { SprocketsApplication.use_page_caching } def show render :text => SprocketsApplication.source, :content_type => "text/javascript" end end
ruby
MIT
8ddad4ce1a93db79187dfbcd06f3d5165568d8d1
2026-01-04T17:56:50.420503Z
false
sstephenson/sprockets-rails
https://github.com/sstephenson/sprockets-rails/blob/8ddad4ce1a93db79187dfbcd06f3d5165568d8d1/lib/sprockets_application.rb
lib/sprockets_application.rb
module SprocketsApplication mattr_accessor :use_page_caching self.use_page_caching = true class << self def routes(map) map.resource(:sprockets) end def source concatenation.to_s end def install_script concatenation.save_to(asset_path) end def install_assets secretary.install_assets end protected def secretary @secretary ||= Sprockets::Secretary.new(configuration.merge(:root => RAILS_ROOT)) end def configuration YAML.load(IO.read(File.join(RAILS_ROOT, "config", "sprockets.yml"))) || {} end def concatenation secretary.reset! unless source_is_unchanged? secretary.concatenation end def asset_path File.join(Rails.public_path, "sprockets.js") end def source_is_unchanged? previous_source_last_modified, @source_last_modified = @source_last_modified, secretary.source_last_modified previous_source_last_modified == @source_last_modified end end end
ruby
MIT
8ddad4ce1a93db79187dfbcd06f3d5165568d8d1
2026-01-04T17:56:50.420503Z
false
cqfn/degit
https://github.com/cqfn/degit/blob/9da4f7d055b217ddb1faca63d5b32e51da694257/test/test__helper.rb
test/test__helper.rb
# frozen_string_literal: true # Copyright (c) 2020 Yegor Bugayenko # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the 'Software'), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. STDOUT.sync = true require 'simplecov' SimpleCov.start if ENV['CI'] == 'true' require 'codecov' SimpleCov.formatter = SimpleCov::Formatter::Codecov end require 'minitest/autorun' require_relative '../lib/degit'
ruby
MIT
9da4f7d055b217ddb1faca63d5b32e51da694257
2026-01-04T17:56:53.276611Z
false
cqfn/degit
https://github.com/cqfn/degit/blob/9da4f7d055b217ddb1faca63d5b32e51da694257/test/test_degit.rb
test/test_degit.rb
# frozen_string_literal: true # Copyright (c) 2020 Yegor Bugayenko # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the 'Software'), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. require 'minitest/autorun' require_relative '../lib/degit' # Degit. # Author:: Yegor Bugayenko (yegor256@gmail.com) # Copyright:: Copyright (c) 2020 Yegor Bugayenko # License:: MIT class TestDegit < Minitest::Test def test_works assert_equal(1, 1) end end
ruby
MIT
9da4f7d055b217ddb1faca63d5b32e51da694257
2026-01-04T17:56:53.276611Z
false
cqfn/degit
https://github.com/cqfn/degit/blob/9da4f7d055b217ddb1faca63d5b32e51da694257/features/support/env.rb
features/support/env.rb
# frozen_string_literal: true # Copyright (c) 2020 Yegor Bugayenko # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the 'Software'), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. require 'simplecov' require_relative '../../lib/degit'
ruby
MIT
9da4f7d055b217ddb1faca63d5b32e51da694257
2026-01-04T17:56:53.276611Z
false
cqfn/degit
https://github.com/cqfn/degit/blob/9da4f7d055b217ddb1faca63d5b32e51da694257/features/step_definitions/steps.rb
features/step_definitions/steps.rb
# frozen_string_literal: true # Copyright (c) 2020 Yegor Bugayenko # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the 'Software'), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. require 'tmpdir' require 'slop' require 'English' require_relative '../../lib/degit' Before do @cwd = Dir.pwd @dir = Dir.mktmpdir('test') FileUtils.mkdir_p(@dir) unless File.exist?(@dir) Dir.chdir(@dir) @opts = Slop.parse ['-v', '-s', @dir] do |o| o.bool '-v', '--verbose' o.string '-s', '--source' end end After do Dir.chdir(@cwd) FileUtils.rm_rf(@dir) if File.exist?(@dir) end Given(/^I have a "([^"]*)" file with content:$/) do |file, text| FileUtils.mkdir_p(File.dirname(file)) unless File.exist?(file) File.open(file, 'w') do |f| f.write(text.gsub(/\\xFF/, 0xFF.chr)) end end When(%r{^I run bin/degit with "([^"]*)"$}) do |arg| home = File.join(File.dirname(__FILE__), '../..') @stdout = `ruby -I#{home}/lib #{home}/bin/degit #{arg}` @exitstatus = $CHILD_STATUS.exitstatus end Then(/^Stdout contains "([^"]*)"$/) do |txt| raise "STDOUT doesn't contain '#{txt}':\n#{@stdout}" unless @stdout.include?(txt) end Then(/^Stdout is empty$/) do raise "STDOUT is not empty:\n#{@stdout}" unless @stdout == '' end Then(/^Exit code is zero$/) do raise "Non-zero exit #{@exitstatus}:\n#{@stdout}" unless @exitstatus.zero? end Then(/^Exit code is not zero$/) do raise 'Zero exit code' if @exitstatus.zero? end When(/^I run bash with "([^"]*)"$/) do |text| FileUtils.copy_entry(@cwd, File.join(@dir, 'degit')) @stdout = `#{text}` @exitstatus = $CHILD_STATUS.exitstatus end When(/^I run bash with:$/) do |text| FileUtils.copy_entry(@cwd, File.join(@dir, 'degit')) @stdout = `#{text}` @exitstatus = $CHILD_STATUS.exitstatus end Given(/^It is Unix$/) do pending if Gem.win_platform? end Given(/^It is Windows$/) do pending unless Gem.win_platform? end
ruby
MIT
9da4f7d055b217ddb1faca63d5b32e51da694257
2026-01-04T17:56:53.276611Z
false
cqfn/degit
https://github.com/cqfn/degit/blob/9da4f7d055b217ddb1faca63d5b32e51da694257/lib/degit.rb
lib/degit.rb
# frozen_string_literal: true # Copyright (c) 2020 Yegor Bugayenko # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the 'Software'), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. require_relative 'degit/version' # Degit main class. # # Author:: Yegor Bugayenko (yegor256@gmail.com) # Copyright:: Copyright (c) 2020 Yegor Bugayenko # License:: MIT module Degit end
ruby
MIT
9da4f7d055b217ddb1faca63d5b32e51da694257
2026-01-04T17:56:53.276611Z
false
cqfn/degit
https://github.com/cqfn/degit/blob/9da4f7d055b217ddb1faca63d5b32e51da694257/lib/degit/version.rb
lib/degit/version.rb
# frozen_string_literal: true # Copyright (c) 2020 Yegor Bugayenko # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the 'Software'), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # Degit main class. # Author:: Yegor Bugayenko (yegor256@gmail.com) # Copyright:: Copyright (c) 2020 Yegor Bugayenko # License:: MIT module Degit # Current version of the library. VERSION = '0.0.0' end
ruby
MIT
9da4f7d055b217ddb1faca63d5b32e51da694257
2026-01-04T17:56:53.276611Z
false
cqfn/degit
https://github.com/cqfn/degit/blob/9da4f7d055b217ddb1faca63d5b32e51da694257/lib/degit/dashboard.rb
lib/degit/dashboard.rb
# frozen_string_literal: true # Copyright (c) 2020 Yegor Bugayenko # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the 'Software'), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. require 'loog' # Dashboard. # Author:: Yegor Bugayenko (yegor256@gmail.com) # Copyright:: Copyright (c) 2020 Yegor Bugayenko # License:: MIT class Degit::Dashboard # Current version of the library. def initialize(log: Loog::NULL) @log = log end def go @log.info('To be continued...') end end
ruby
MIT
9da4f7d055b217ddb1faca63d5b32e51da694257
2026-01-04T17:56:53.276611Z
false
cqfn/degit
https://github.com/cqfn/degit/blob/9da4f7d055b217ddb1faca63d5b32e51da694257/lib/degit/deploy.rb
lib/degit/deploy.rb
# frozen_string_literal: true # Copyright (c) 2020 Yegor Bugayenko # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the 'Software'), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. require 'loog' # Deploy. # Author:: Yegor Bugayenko (yegor256@gmail.com) # Copyright:: Copyright (c) 2020 Yegor Bugayenko # License:: MIT class Degit::Deploy # Current version of the library. def initialize(log: Loog::NULL) @log = log end def go @log.info('To be continued...') end end
ruby
MIT
9da4f7d055b217ddb1faca63d5b32e51da694257
2026-01-04T17:56:53.276611Z
false
gdb/embedded-mongo
https://github.com/gdb/embedded-mongo/blob/db309362b9069796ceffdbb494f49e86dc26a7b2/test/imported/test_helper.rb
test/imported/test_helper.rb
$:.unshift(File.join(File.dirname(__FILE__), '..', '..', 'lib')) require 'rubygems' if RUBY_VERSION < '1.9.0' && ENV['C_EXT'] require 'embedded-mongo' require 'test/unit' def silently warn_level = $VERBOSE $VERBOSE = nil result = yield $VERBOSE = warn_level result end begin require 'rubygems' if RUBY_VERSION < "1.9.0" && !ENV['C_EXT'] silently { require 'shoulda' } silently { require 'mocha' } rescue LoadError puts <<MSG This test suite requires shoulda and mocha. You can install them as follows: gem install shoulda gem install mocha MSG exit end require 'bson_ext/cbson' if !(RUBY_PLATFORM =~ /java/) && ENV['C_EXT'] unless defined? MONGO_TEST_DB MONGO_TEST_DB = 'ruby-test-db' end unless defined? TEST_PORT TEST_PORT = ENV['MONGO_RUBY_DRIVER_PORT'] ? ENV['MONGO_RUBY_DRIVER_PORT'].to_i : Mongo::Connection::DEFAULT_PORT end unless defined? TEST_HOST TEST_HOST = ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost' end class Test::Unit::TestCase include Mongo include BSON def self.standard_connection(options={}) EmbeddedMongo::Connection.new(TEST_HOST, TEST_PORT, options) end def standard_connection(options={}) self.class.standard_connection(options) end def self.host_port "#{mongo_host}:#{mongo_port}" end def self.mongo_host TEST_HOST end def self.mongo_port TEST_PORT end def host_port self.class.host_port end def mongo_host self.class.mongo_host end def mongo_port self.class.mongo_port end def new_mock_socket(host='localhost', port=27017) socket = Object.new socket.stubs(:setsockopt).with(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) socket.stubs(:close) socket end def new_mock_db db = Object.new end def assert_raise_error(klass, message) begin yield rescue => e assert_equal klass, e.class assert e.message.include?(message), "#{e.message} does not include #{message}." else flunk "Expected assertion #{klass} but none was raised." end end end
ruby
MIT
db309362b9069796ceffdbb494f49e86dc26a7b2
2026-01-04T17:57:03.242146Z
false
gdb/embedded-mongo
https://github.com/gdb/embedded-mongo/blob/db309362b9069796ceffdbb494f49e86dc26a7b2/test/imported/db_api_test.rb
test/imported/db_api_test.rb
require File.join(File.dirname(__FILE__), 'test_helper') class DBAPITest < Test::Unit::TestCase include Mongo include BSON @@conn = standard_connection @@db = @@conn.db(MONGO_TEST_DB) @@coll = @@db.collection('test') @@version = @@conn.server_version def setup @@coll.remove @r1 = {'a' => 1} @@coll.insert(@r1) # collection not created until it's used @@coll_full_name = "#{MONGO_TEST_DB}.test" end def teardown @@coll.remove @@db.get_last_error end def test_clear assert_equal 1, @@coll.count @@coll.remove assert_equal 0, @@coll.count end def test_insert assert_kind_of BSON::ObjectId, @@coll.insert('a' => 2) assert_kind_of BSON::ObjectId, @@coll.insert('b' => 3) assert_equal 3, @@coll.count docs = @@coll.find().to_a assert_equal 3, docs.length assert docs.detect { |row| row['a'] == 1 } assert docs.detect { |row| row['a'] == 2 } assert docs.detect { |row| row['b'] == 3 } @@coll << {'b' => 4} docs = @@coll.find().to_a assert_equal 4, docs.length assert docs.detect { |row| row['b'] == 4 } end def test_save_ordered_hash oh = BSON::OrderedHash.new oh['a'] = -1 oh['b'] = 'foo' oid = @@coll.save(oh) assert_equal 'foo', @@coll.find_one(oid)['b'] oh = BSON::OrderedHash['a' => 1, 'b' => 'foo'] oid = @@coll.save(oh) assert_equal 'foo', @@coll.find_one(oid)['b'] end def test_insert_multiple ids = @@coll.insert([{'a' => 2}, {'b' => 3}]) ids.each do |i| assert_kind_of BSON::ObjectId, i end assert_equal 3, @@coll.count docs = @@coll.find().to_a assert_equal 3, docs.length assert docs.detect { |row| row['a'] == 1 } assert docs.detect { |row| row['a'] == 2 } assert docs.detect { |row| row['b'] == 3 } end def test_count_on_nonexisting @@db.drop_collection('foo') assert_equal 0, @@db.collection('foo').count() end def test_find_simple @r2 = @@coll.insert('a' => 2) @r3 = @@coll.insert('b' => 3) # Check sizes docs = @@coll.find().to_a assert_equal 3, docs.size assert_equal 3, @@coll.count # Find by other value docs = @@coll.find('a' => @r1['a']).to_a assert_equal 1, docs.size doc = docs.first # Can't compare _id values because at insert, an _id was added to @r1 by # the database but we don't know what it is without re-reading the record # (which is what we are doing right now). # assert_equal doc['_id'], @r1['_id'] assert_equal doc['a'], @r1['a'] end def test_find_advanced @@coll.insert('a' => 2) @@coll.insert('b' => 3) # Find by advanced query (less than) docs = @@coll.find('a' => { '$lt' => 10 }).to_a assert_equal 2, docs.size assert docs.detect { |row| row['a'] == 1 } assert docs.detect { |row| row['a'] == 2 } # Find by advanced query (greater than) docs = @@coll.find('a' => { '$gt' => 1 }).to_a assert_equal 1, docs.size assert docs.detect { |row| row['a'] == 2 } # Find by advanced query (less than or equal to) docs = @@coll.find('a' => { '$lte' => 1 }).to_a assert_equal 1, docs.size assert docs.detect { |row| row['a'] == 1 } # Find by advanced query (greater than or equal to) docs = @@coll.find('a' => { '$gte' => 1 }).to_a assert_equal 2, docs.size assert docs.detect { |row| row['a'] == 1 } assert docs.detect { |row| row['a'] == 2 } # Find by advanced query (between) docs = @@coll.find('a' => { '$gt' => 1, '$lt' => 3 }).to_a assert_equal 1, docs.size assert docs.detect { |row| row['a'] == 2 } # Find by advanced query (in clause) docs = @@coll.find('a' => {'$in' => [1,2]}).to_a assert_equal 2, docs.size assert docs.detect { |row| row['a'] == 1 } assert docs.detect { |row| row['a'] == 2 } end def test_find_sorting @@coll.remove @@coll.insert('a' => 1, 'b' => 2) @@coll.insert('a' => 2, 'b' => 1) @@coll.insert('a' => 3, 'b' => 2) @@coll.insert('a' => 4, 'b' => 1) # Sorting (ascending) docs = @@coll.find({'a' => { '$lt' => 10 }}, :sort => [['a', 1]]).to_a assert_equal 4, docs.size assert_equal 1, docs[0]['a'] assert_equal 2, docs[1]['a'] assert_equal 3, docs[2]['a'] assert_equal 4, docs[3]['a'] # Sorting (descending) docs = @@coll.find({'a' => { '$lt' => 10 }}, :sort => [['a', -1]]).to_a assert_equal 4, docs.size assert_equal 4, docs[0]['a'] assert_equal 3, docs[1]['a'] assert_equal 2, docs[2]['a'] assert_equal 1, docs[3]['a'] # Sorting using array of names; assumes ascending order. docs = @@coll.find({'a' => { '$lt' => 10 }}, :sort => 'a').to_a assert_equal 4, docs.size assert_equal 1, docs[0]['a'] assert_equal 2, docs[1]['a'] assert_equal 3, docs[2]['a'] assert_equal 4, docs[3]['a'] # Sorting using single name; assumes ascending order. docs = @@coll.find({'a' => { '$lt' => 10 }}, :sort => 'a').to_a assert_equal 4, docs.size assert_equal 1, docs[0]['a'] assert_equal 2, docs[1]['a'] assert_equal 3, docs[2]['a'] assert_equal 4, docs[3]['a'] docs = @@coll.find({'a' => { '$lt' => 10 }}, :sort => [['b', 'asc'], ['a', 'asc']]).to_a assert_equal 4, docs.size assert_equal 2, docs[0]['a'] assert_equal 4, docs[1]['a'] assert_equal 1, docs[2]['a'] assert_equal 3, docs[3]['a'] # Sorting using empty array; no order guarantee should not blow up. docs = @@coll.find({'a' => { '$lt' => 10 }}, :sort => []).to_a assert_equal 4, docs.size # Sorting using ordered hash. You can use an unordered one, but then the # order of the keys won't be guaranteed thus your sort won't make sense. oh = BSON::OrderedHash.new oh['a'] = -1 assert_raise InvalidSortValueError do docs = @@coll.find({'a' => { '$lt' => 10 }}, :sort => oh).to_a end end def test_find_limits @@coll.insert('b' => 2) @@coll.insert('c' => 3) @@coll.insert('d' => 4) docs = @@coll.find({}, :limit => 1).to_a assert_equal 1, docs.size docs = @@coll.find({}, :limit => 2).to_a assert_equal 2, docs.size docs = @@coll.find({}, :limit => 3).to_a assert_equal 3, docs.size docs = @@coll.find({}, :limit => 4).to_a assert_equal 4, docs.size docs = @@coll.find({}).to_a assert_equal 4, docs.size docs = @@coll.find({}, :limit => 99).to_a assert_equal 4, docs.size end def test_find_one_no_records @@coll.remove x = @@coll.find_one('a' => 1) assert_nil x end def test_drop_collection assert @@db.drop_collection(@@coll.name), "drop of collection #{@@coll.name} failed" assert !@@db.collection_names.include?(@@coll.name) end def test_other_drop assert @@db.collection_names.include?(@@coll.name) @@coll.drop assert !@@db.collection_names.include?(@@coll.name) end def test_collection_names names = @@db.collection_names assert names.length >= 1 assert names.include?(@@coll.name) coll2 = @@db.collection('test2') coll2.insert('a' => 1) # collection not created until it's used names = @@db.collection_names assert names.length >= 2 assert names.include?(@@coll.name) assert names.include?('test2') ensure @@db.drop_collection('test2') end def test_collections_info cursor = @@db.collections_info rows = cursor.to_a assert rows.length >= 1 row = rows.detect { |r| r['name'] == @@coll_full_name } assert_not_nil row end def test_collection_options @@db.drop_collection('foobar') @@db.strict = true begin coll = @@db.create_collection('foobar', :capped => true, :size => 1024) options = coll.options() assert_equal 'foobar', options['create'] assert_equal true, options['capped'] assert_equal 1024, options['size'] rescue => ex @@db.drop_collection('foobar') fail "did not expect exception \"#{ex}\"" ensure @@db.strict = false end end def test_collection_options_are_passed_to_the_existing_ones @@db.drop_collection('foobar') @@db.create_collection('foobar') opts = {:safe => true} coll = @@db.create_collection('foobar', opts) assert_equal true, coll.safe end def test_index_information assert_equal @@coll.index_information.length, 1 name = @@coll.create_index('a') info = @@db.index_information(@@coll.name) assert_equal name, "a_1" assert_equal @@coll.index_information, info assert_equal 2, info.length assert info.has_key?(name) assert_equal info[name]["key"], {"a" => 1} ensure @@db.drop_index(@@coll.name, name) end def test_index_create_with_symbol assert_equal @@coll.index_information.length, 1 name = @@coll.create_index([['a', 1]]) info = @@db.index_information(@@coll.name) assert_equal name, "a_1" assert_equal @@coll.index_information, info assert_equal 2, info.length assert info.has_key?(name) assert_equal info[name]['key'], {"a" => 1} ensure @@db.drop_index(@@coll.name, name) end def test_multiple_index_cols name = @@coll.create_index([['a', DESCENDING], ['b', ASCENDING], ['c', DESCENDING]]) info = @@db.index_information(@@coll.name) assert_equal 2, info.length assert_equal name, 'a_-1_b_1_c_-1' assert info.has_key?(name) assert_equal info[name]['key'], {"a" => -1, "b" => 1, "c" => -1} ensure @@db.drop_index(@@coll.name, name) end def test_multiple_index_cols_with_symbols name = @@coll.create_index([[:a, DESCENDING], [:b, ASCENDING], [:c, DESCENDING]]) info = @@db.index_information(@@coll.name) assert_equal 2, info.length assert_equal name, 'a_-1_b_1_c_-1' assert info.has_key?(name) assert_equal info[name]['key'], {"a" => -1, "b" => 1, "c" => -1} ensure @@db.drop_index(@@coll.name, name) end def test_unique_index @@db.drop_collection("blah") test = @@db.collection("blah") test.create_index("hello") test.insert("hello" => "world") test.insert("hello" => "mike") test.insert("hello" => "world") assert !@@db.error? @@db.drop_collection("blah") test = @@db.collection("blah") test.create_index("hello", :unique => true) test.insert("hello" => "world") test.insert("hello" => "mike") test.insert("hello" => "world") assert @@db.error? end def test_index_on_subfield @@db.drop_collection("blah") test = @@db.collection("blah") test.insert("hello" => {"a" => 4, "b" => 5}) test.insert("hello" => {"a" => 7, "b" => 2}) test.insert("hello" => {"a" => 4, "b" => 10}) assert !@@db.error? @@db.drop_collection("blah") test = @@db.collection("blah") test.create_index("hello.a", :unique => true) test.insert("hello" => {"a" => 4, "b" => 5}) test.insert("hello" => {"a" => 7, "b" => 2}) test.insert("hello" => {"a" => 4, "b" => 10}) assert @@db.error? end def test_array @@coll.remove @@coll.insert({'b' => [1, 2, 3]}) @@coll.insert({'b' => [1, 2, 3]}) rows = @@coll.find({}, {:fields => ['b']}).to_a assert_equal 2, rows.length assert_equal [1, 2, 3], rows[1]['b'] end def test_regex regex = /foobar/i @@coll << {'b' => regex} rows = @@coll.find({}, {:fields => ['b']}).to_a if @@version < "1.1.3" assert_equal 1, rows.length assert_equal regex, rows[0]['b'] else assert_equal 2, rows.length assert_equal regex, rows[1]['b'] end end def test_non_oid_id # Note: can't use Time.new because that will include fractional seconds, # which Mongo does not store. t = Time.at(1234567890) @@coll << {'_id' => t} rows = @@coll.find({'_id' => t}).to_a assert_equal 1, rows.length assert_equal t, rows[0]['_id'] end def test_strict assert !@@db.strict? @@db.strict = true assert @@db.strict? ensure @@db.strict = false end def test_strict_access_collection @@db.strict = true begin @@db.collection('does-not-exist') fail "expected exception" rescue => ex assert_equal Mongo::MongoDBError, ex.class assert_equal "Collection does-not-exist doesn't exist. Currently in strict mode.", ex.to_s ensure @@db.strict = false @@db.drop_collection('does-not-exist') end end def test_strict_create_collection @@db.drop_collection('foobar') @@db.strict = true begin @@db.create_collection('foobar') assert true rescue => ex fail "did not expect exception \"#{ex}\"" end # Now the collection exists. This time we should see an exception. assert_raise Mongo::MongoDBError do @@db.create_collection('foobar') end @@db.strict = false @@db.drop_collection('foobar') # Now we're not in strict mode - should succeed @@db.create_collection('foobar') @@db.create_collection('foobar') @@db.drop_collection('foobar') end def test_where return @@coll.insert('a' => 2) @@coll.insert('a' => 3) assert_equal 3, @@coll.count assert_equal 1, @@coll.find('$where' => BSON::Code.new('this.a > 2')).count() assert_equal 2, @@coll.find('$where' => BSON::Code.new('this.a > i', {'i' => 1})).count() end def test_eval return assert_equal 3, @@db.eval('function (x) {return x;}', 3) assert_equal nil, @@db.eval("function (x) {db.test_eval.save({y:x});}", 5) assert_equal 5, @@db.collection('test_eval').find_one['y'] assert_equal 5, @@db.eval("function (x, y) {return x + y;}", 2, 3) assert_equal 5, @@db.eval("function () {return 5;}") assert_equal 5, @@db.eval("2 + 3;") assert_equal 5, @@db.eval(Code.new("2 + 3;")) assert_equal 2, @@db.eval(Code.new("return i;", {"i" => 2})) assert_equal 5, @@db.eval(Code.new("i + 3;", {"i" => 2})) assert_raise OperationFailure do @@db.eval("5 ++ 5;") end end def test_hint name = @@coll.create_index('a') begin assert_nil @@coll.hint assert_equal 1, @@coll.find({'a' => 1}, :hint => 'a').to_a.size assert_equal 1, @@coll.find({'a' => 1}, :hint => ['a']).to_a.size assert_equal 1, @@coll.find({'a' => 1}, :hint => {'a' => 1}).to_a.size @@coll.hint = 'a' assert_equal({'a' => 1}, @@coll.hint) assert_equal 1, @@coll.find('a' => 1).to_a.size @@coll.hint = ['a'] assert_equal({'a' => 1}, @@coll.hint) assert_equal 1, @@coll.find('a' => 1).to_a.size @@coll.hint = {'a' => 1} assert_equal({'a' => 1}, @@coll.hint) assert_equal 1, @@coll.find('a' => 1).to_a.size @@coll.hint = nil assert_nil @@coll.hint assert_equal 1, @@coll.find('a' => 1).to_a.size ensure @@coll.drop_index(name) end end def test_hash_default_value_id val = Hash.new(0) val["x"] = 5 @@coll.insert val id = @@coll.find_one("x" => 5)["_id"] assert id != 0 end def test_group @@db.drop_collection("test") test = @@db.collection("test") assert_equal [], test.group(:initial => {"count" => 0}, :reduce => "function (obj, prev) { prev.count++; }") assert_equal [], test.group(:initial => {"count" => 0}, :reduce => "function (obj, prev) { prev.count++; }") test.insert("a" => 2) test.insert("b" => 5) test.insert("a" => 1) assert_equal 3, test.group(:initial => {"count" => 0}, :reduce => "function (obj, prev) { prev.count++; }")[0]["count"] assert_equal 3, test.group(:initial => {"count" => 0}, :reduce => "function (obj, prev) { prev.count++; }")[0]["count"] assert_equal 1, test.group(:cond => {"a" => {"$gt" => 1}}, :initial => {"count" => 0}, :reduce => "function (obj, prev) { prev.count++; }")[0]["count"] assert_equal 1, test.group(:cond => {"a" => {"$gt" => 1}}, :initial => {"count" => 0}, :reduce => "function (obj, prev) { prev.count++; }")[0]["count"] finalize = "function (obj) { obj.f = obj.count - 1; }" assert_equal 2, test.group(:initial => {"count" => 0}, :reduce => "function (obj, prev) { prev.count++; }", :finalize => finalize)[0]["f"] test.insert("a" => 2, "b" => 3) expected = [{"a" => 2, "count" => 2}, {"a" => nil, "count" => 1}, {"a" => 1, "count" => 1}] assert_equal expected, test.group(:key => ["a"], :initial => {"count" => 0}, :reduce => "function (obj, prev) { prev.count++; }") assert_equal expected, test.group(:key => :a, :initial => {"count" => 0}, :reduce => "function (obj, prev) { prev.count++; }") assert_raise OperationFailure do test.group(:initial => {}, :reduce => "5 ++ 5") end end def test_deref @@coll.remove assert_equal nil, @@db.dereference(DBRef.new("test", ObjectId.new)) @@coll.insert({"x" => "hello"}) key = @@coll.find_one()["_id"] assert_equal "hello", @@db.dereference(DBRef.new("test", key))["x"] assert_equal nil, @@db.dereference(DBRef.new("test", 4)) obj = {"_id" => 4} @@coll.insert(obj) assert_equal obj, @@db.dereference(DBRef.new("test", 4)) @@coll.remove @@coll.insert({"x" => "hello"}) assert_equal nil, @@db.dereference(DBRef.new("test", nil)) end def test_save @@coll.remove a = {"hello" => "world"} id = @@coll.save(a) assert_kind_of ObjectId, id assert_equal 1, @@coll.count assert_equal id, @@coll.save(a) assert_equal 1, @@coll.count assert_equal "world", @@coll.find_one()["hello"] a["hello"] = "mike" @@coll.save(a) assert_equal 1, @@coll.count assert_equal "mike", @@coll.find_one()["hello"] @@coll.save({"hello" => "world"}) assert_equal 2, @@coll.count end def test_save_long @@coll.remove @@coll.insert("x" => 9223372036854775807) assert_equal 9223372036854775807, @@coll.find_one()["x"] end def test_find_by_oid @@coll.remove @@coll.save("hello" => "mike") id = @@coll.save("hello" => "world") assert_kind_of ObjectId, id assert_equal "world", @@coll.find_one(:_id => id)["hello"] @@coll.find(:_id => id).to_a.each do |doc| assert_equal "world", doc["hello"] end id = ObjectId.from_string(id.to_s) assert_equal "world", @@coll.find_one(:_id => id)["hello"] end def test_save_with_object_that_has_id_but_does_not_actually_exist_in_collection @@coll.remove a = {'_id' => '1', 'hello' => 'world'} @@coll.save(a) assert_equal(1, @@coll.count) assert_equal("world", @@coll.find_one()["hello"]) a["hello"] = "mike" @@coll.save(a) assert_equal(1, @@coll.count) assert_equal("mike", @@coll.find_one()["hello"]) end def test_collection_names_errors assert_raise TypeError do @@db.collection(5) end assert_raise Mongo::InvalidNSName do @@db.collection("") end assert_raise Mongo::InvalidNSName do @@db.collection("te$t") end assert_raise Mongo::InvalidNSName do @@db.collection(".test") end assert_raise Mongo::InvalidNSName do @@db.collection("test.") end assert_raise Mongo::InvalidNSName do @@db.collection("tes..t") end end def test_rename_collection @@db.drop_collection("foo") @@db.drop_collection("bar") a = @@db.collection("foo") b = @@db.collection("bar") assert_raise TypeError do a.rename(5) end assert_raise Mongo::InvalidNSName do a.rename("") end assert_raise Mongo::InvalidNSName do a.rename("te$t") end assert_raise Mongo::InvalidNSName do a.rename(".test") end assert_raise Mongo::InvalidNSName do a.rename("test.") end assert_raise Mongo::InvalidNSName do a.rename("tes..t") end assert_equal 0, a.count() assert_equal 0, b.count() a.insert("x" => 1) a.insert("x" => 2) assert_equal 2, a.count() a.rename("bar") assert_equal 2, a.count() end # doesn't really test functionality, just that the option is set correctly def test_snapshot @@db.collection("test").find({}, :snapshot => true).to_a assert_raise OperationFailure do @@db.collection("test").find({}, :snapshot => true, :sort => 'a').to_a end end def test_encodings if RUBY_VERSION >= '1.9' ascii = "hello world" utf8 = "hello world".encode("UTF-8") iso8859 = "hello world".encode("ISO-8859-1") if RUBY_PLATFORM =~ /jruby/ assert_equal "ASCII-8BIT", ascii.encoding.name else assert_equal "US-ASCII", ascii.encoding.name end assert_equal "UTF-8", utf8.encoding.name assert_equal "ISO-8859-1", iso8859.encoding.name @@coll.remove @@coll.save("ascii" => ascii, "utf8" => utf8, "iso8859" => iso8859) doc = @@coll.find_one() assert_equal "UTF-8", doc["ascii"].encoding.name assert_equal "UTF-8", doc["utf8"].encoding.name assert_equal "UTF-8", doc["iso8859"].encoding.name end end end
ruby
MIT
db309362b9069796ceffdbb494f49e86dc26a7b2
2026-01-04T17:57:03.242146Z
false
gdb/embedded-mongo
https://github.com/gdb/embedded-mongo/blob/db309362b9069796ceffdbb494f49e86dc26a7b2/test/functional/interface_test.rb
test/functional/interface_test.rb
require 'rubygems' require 'test/unit' require File.join(File.dirname(__FILE__), '../../lib/embedded-mongo') class InterfaceTest < Test::Unit::TestCase def setup # Tests should pass with either of the following lines @conn = EmbeddedMongo::Connection.new # @conn = Mongo::Connection.new @test_db = @conn['test'] @foo_collection = @test_db['foo'] @foo_collection.remove end def test_insert_and_find id = @foo_collection.insert({ 'bar' => 'baz' }) cursor = @foo_collection.find({ '_id' => id }) assert_equal(1, cursor.count) assert_equal({ '_id' => id, 'bar' => 'baz'}, cursor.first) end def test_insert_update_and_find id = @foo_collection.insert({ 'zombie' => 'baz' }) @foo_collection.update({ 'zombie' => 'baz' }, { 'test' => 'tar' }) cursor = @foo_collection.find({ '_id' => id }) assert_equal(1, cursor.count) assert_equal({ '_id' => id, 'test' => 'tar'}, cursor.first) end def test_update_upsert_record_not_present selector = {'schubar'=>'mubar'} @foo_collection.update( selector, {'$set'=>{'baz'=>'bingo'}}, :upsert => true ) cursor = @foo_collection.find(selector) assert_equal 1, cursor.count entry = cursor.first assert_equal 'bingo', (entry['baz'] rescue nil) end def test_update_upsert_record_present selector = {'fubar'=>'rubar'} @foo_collection.insert( selector.merge('tweedle'=>'dee') ) @foo_collection.update( selector, {'$set'=>{'baz'=>'bingo'}}, :upsert => true ) cursor = @foo_collection.find(selector) assert_equal 1, cursor.count entry = cursor.first assert_equal 'bingo', (entry['baz'] rescue nil), 'failed to set new value' assert_equal 'dee', (entry['tweedle'] rescue nil), 'overwrote unrelated value in record' end def test_update_increment_record_field selector = {'fubar'=>'rubar'} @foo_collection.insert( selector.merge('baz'=>1) ) @foo_collection.update( selector, {'$inc'=>{'baz'=>2}} ) cursor = @foo_collection.find(selector) assert_equal 1, cursor.count entry = cursor.first assert_equal 3, (entry['baz'] rescue nil), 'failed to increment value' end def test_update_increment_record_field_with_incorrect_type selector = {'fubar'=>'rubar'} @foo_collection.insert( selector.merge('baz'=>'not an integer') ) assert_raise(Mongo::OperationFailure) do @foo_collection.update( selector, {'$inc'=>{'baz'=>2}} ) end end def test_update_upsert_record_with_id @foo_collection.update( {'foo' => 'bart','_id'=>0xdeadbeef}, {'$set'=>{'baz'=>'bingo'}}, :upsert => true ) cursor = @foo_collection.find({ 'foo' => 'bart' }) assert_equal 1, cursor.count entry = cursor.first assert_equal 0xdeadbeef, (entry['_id'] rescue nil), 'overwrote id' end def test_changing_ids id = @foo_collection.insert({ 'zing' => 'zong' }) @foo_collection.update({ '_id' => id }, { '_id' => 'other_id' }) cursor = @foo_collection.find({ '_id' => id }) assert_equal(0, cursor.count) cursor = @foo_collection.find({ '_id' => 'other_id' }) assert_equal(1, cursor.count) assert_equal({ '_id' => 'other_id' }, cursor.first) end def test_remove id1 = @foo_collection.insert({ 'lime' => 'limit' }) id2 = @foo_collection.insert({ 'lemon' => 'limit' }) @foo_collection.remove({ 'lime' => 'limit' }) cursor = @foo_collection.find({ '_id' => id1 }) assert_equal(0, cursor.count) cursor = @foo_collection.find({ '_id' => id2 }) assert_equal(1, cursor.count) assert_equal({ '_id' => id2, 'lemon' => 'limit' }, cursor.first) end def test_sort @foo_collection.insert({ 'a' => 10 }) @foo_collection.insert({ 'a' => 20 }) @foo_collection.insert({ 'b' => 'foo' }) cursor1 = @foo_collection.find.sort([['a', 'asc']]) res1 = cursor1.to_a assert_equal(nil, res1[0]['a']) assert_equal(10, res1[1]['a']) assert_equal(20, res1[2]['a']) cursor2 = @foo_collection.find.sort([['a', 'desc']]) res2 = cursor2.to_a assert_equal(20, res2[0]['a']) assert_equal(10, res2[1]['a']) assert_equal(nil, res2[2]['a']) end def test_or_support @foo_collection.insert({ 'e' => 10 }) @foo_collection.insert({ 'e' => 20 }) @foo_collection.insert({ 'e' => 30 }) cursor1 = @foo_collection.find(:$or=>[{'e'=>10}, {'e'=>20}]) res1 = cursor1.to_a assert_equal(2, res1.length) p res1 end def test_and_support @foo_collection.insert({ 'e' => 10 }) @foo_collection.insert({ 'e' => 20 }) @foo_collection.insert({ 'e' => 30 }) cursor1 = @foo_collection.find({:$or=>[{'e'=>10}, {'e'=>20}], :$and=>[{'e'=>10}]}) res1 = cursor1.to_a assert_equal(1, res1.length) end def test_for_in @foo_collection.insert({'q'=>['der', 'dor']}) @foo_collection.insert({'q'=>['dar', 'dot']}) @foo_collection.insert({'q'=>['dot']}) cursor1 = @foo_collection.find({'q'=>'dot'}) res1 = cursor1.to_a assert_equal(2, res1.length) end end
ruby
MIT
db309362b9069796ceffdbb494f49e86dc26a7b2
2026-01-04T17:57:03.242146Z
false
gdb/embedded-mongo
https://github.com/gdb/embedded-mongo/blob/db309362b9069796ceffdbb494f49e86dc26a7b2/lib/embedded-mongo.rb
lib/embedded-mongo.rb
require 'logger' require 'rubygems' require 'mongo' $:.unshift(File.dirname(__FILE__)) module EmbeddedMongo def self.log unless @log @log = Logger.new(STDOUT) @log.level = Logger::WARN end @log end end require "embedded-mongo/version" require 'embedded-mongo/backend' require 'embedded-mongo/backend/collection' require 'embedded-mongo/backend/db' require 'embedded-mongo/backend/manager' require 'embedded-mongo/connection' require 'embedded-mongo/collection' require 'embedded-mongo/cursor' require 'embedded-mongo/db' require 'embedded-mongo/util'
ruby
MIT
db309362b9069796ceffdbb494f49e86dc26a7b2
2026-01-04T17:57:03.242146Z
false
gdb/embedded-mongo
https://github.com/gdb/embedded-mongo/blob/db309362b9069796ceffdbb494f49e86dc26a7b2/lib/embedded-mongo/collection.rb
lib/embedded-mongo/collection.rb
module EmbeddedMongo class Collection < Mongo::Collection def insert_documents(documents, collection_name=@name, check_keys=true, safe=false, opts={}) # TODO: do something with check_keys / safe EmbeddedMongo.log.debug("insert_documents: #{documents.inspect}, #{collection_name.inspect}, #{check_keys.inspect}, #{safe.inspect}, #{opts.inspect}") @connection.request(:insert_documents, @db.name, collection_name, documents) end def update(selector, document, opts={}) EmbeddedMongo.log.debug("update: #{selector.inspect}, #{document.inspect}, #{opts.inspect}") opts = { :safe => @safe }.merge(opts) @connection.request(:update, @db.name, @name, selector, document, opts) end def remove(selector={}, opts={}) opts = { :safe => @safe }.merge(opts) @connection.request(:remove, @db.name, @name, selector, opts) end # verbatim def find(selector={}, opts={}) fields = opts.delete(:fields) fields = ["_id"] if fields && fields.empty? skip = opts.delete(:skip) || skip || 0 limit = opts.delete(:limit) || 0 sort = opts.delete(:sort) hint = opts.delete(:hint) snapshot = opts.delete(:snapshot) batch_size = opts.delete(:batch_size) timeout = (opts.delete(:timeout) == false) ? false : true transformer = opts.delete(:transformer) if timeout == false && !block_given? raise ArgumentError, "Collection#find must be invoked with a block when timeout is disabled." end if hint hint = normalize_hint_fields(hint) else hint = @hint # assumed to be normalized already end raise RuntimeError, "Unknown options [#{opts.inspect}]" unless opts.empty? cursor = Cursor.new(self, { :selector => selector, :fields => fields, :skip => skip, :limit => limit, :order => sort, :hint => hint, :snapshot => snapshot, :timeout => timeout, :batch_size => batch_size, :transformer => transformer, }) if block_given? yield cursor cursor.close nil else cursor end end end end
ruby
MIT
db309362b9069796ceffdbb494f49e86dc26a7b2
2026-01-04T17:57:03.242146Z
false
gdb/embedded-mongo
https://github.com/gdb/embedded-mongo/blob/db309362b9069796ceffdbb494f49e86dc26a7b2/lib/embedded-mongo/version.rb
lib/embedded-mongo/version.rb
module EmbeddedMongo VERSION = "0.0.1" end
ruby
MIT
db309362b9069796ceffdbb494f49e86dc26a7b2
2026-01-04T17:57:03.242146Z
false
gdb/embedded-mongo
https://github.com/gdb/embedded-mongo/blob/db309362b9069796ceffdbb494f49e86dc26a7b2/lib/embedded-mongo/db.rb
lib/embedded-mongo/db.rb
module EmbeddedMongo class DB < Mongo::DB # verbatim def rename_collection(from, to) oh = BSON::OrderedHash.new oh[:renameCollection] = "#{@name}.#{from}" oh[:to] = "#{@name}.#{to}" doc = DB.new('admin', @connection).command(oh, :check_response => false) ok?(doc) || raise(MongoDBError, "Error renaming collection: #{doc.inspect}") end # mostly verbatim def command(selector, opts={}) check_response = opts.fetch(:check_response, true) socket = opts[:socket] raise MongoArgumentError, "command must be given a selector" unless selector.is_a?(Hash) && !selector.empty? if selector.keys.length > 1 && RUBY_VERSION < '1.9' && selector.class != BSON::OrderedHash raise MongoArgumentError, "DB#command requires an OrderedHash when hash contains multiple keys" end begin result = Cursor.new(system_command_collection, :limit => -1, :selector => selector, :socket => socket).next_document rescue Mongo::OperationFailure => ex raise OperationFailure, "Database command '#{selector.keys.first}' failed: #{ex.message}" end if result.nil? raise Mongo::OperationFailure, "Database command '#{selector.keys.first}' failed: returned null." elsif (check_response && !ok?(result)) raise Mongo::OperationFailure, "Database command '#{selector.keys.first}' failed: #{result.inspect}" else result end end # verbatim def collection(name, opts={}) if strict? && !collection_names.include?(name) raise Mongo::MongoDBError, "Collection #{name} doesn't exist. Currently in strict mode." else opts[:safe] = opts.fetch(:safe, @safe) opts.merge!(:pk => @pk_factory) unless opts[:pk] Collection.new(name, self, opts) end end alias_method :[], :collection # verbatim def collections collection_names.map do |name| Collection.new(name, self) end end # verbatim def collections_info(coll_name=nil) selector = {} selector[:name] = full_collection_name(coll_name) if coll_name Cursor.new(Collection.new(SYSTEM_NAMESPACE_COLLECTION, self), :selector => selector) end end end
ruby
MIT
db309362b9069796ceffdbb494f49e86dc26a7b2
2026-01-04T17:57:03.242146Z
false
gdb/embedded-mongo
https://github.com/gdb/embedded-mongo/blob/db309362b9069796ceffdbb494f49e86dc26a7b2/lib/embedded-mongo/cursor.rb
lib/embedded-mongo/cursor.rb
module EmbeddedMongo class Cursor < Mongo::Cursor def refresh send_initial_query end def send_initial_query if @query_run false else results = @connection.request(:find, @db.name, @collection.name, selector, :limit => @limit, :sort => @order) @returned += results.length @cache += results @query_run = true end end def count(skip_and_limit=false) raise NotImplementedError.new if skip_and_limit send_initial_query @cache.length end end end
ruby
MIT
db309362b9069796ceffdbb494f49e86dc26a7b2
2026-01-04T17:57:03.242146Z
false
gdb/embedded-mongo
https://github.com/gdb/embedded-mongo/blob/db309362b9069796ceffdbb494f49e86dc26a7b2/lib/embedded-mongo/backend.rb
lib/embedded-mongo/backend.rb
module EmbeddedMongo module Backend @@backends = {} def self.connect_backend(spec) @@backends[spec] ||= Backend::Manager.new(spec) end end end
ruby
MIT
db309362b9069796ceffdbb494f49e86dc26a7b2
2026-01-04T17:57:03.242146Z
false
gdb/embedded-mongo
https://github.com/gdb/embedded-mongo/blob/db309362b9069796ceffdbb494f49e86dc26a7b2/lib/embedded-mongo/connection.rb
lib/embedded-mongo/connection.rb
module EmbeddedMongo class Connection < Mongo::Connection # mock methods def request(method, *args) @backend.send(method, *args) end def connect EmbeddedMongo.log.debug "Connecting to #{@host_to_try.inspect}" @backend = Backend.connect_backend(@host_to_try) end def send_message(operation, message, log_message=nil) EmbeddedMongo.log.debug "Calling send_message with: #{operation.inspect}, #{message.inspect}, #{log_message.inspect}" raise "send_message" end def receive_message(operation, message, log_message=nil, socket=nil, command=false) EmbeddedMongo.log.debug "Calling receive_message with: #{operation.inspect}, #{message.inspect}, #{log_message.inspect}, #{command.inspect}" raise "receive_message" end # verbatim def db(db_name, opts={}) DB.new(db_name, self, opts) end # verbatim def [](db_name) DB.new(db_name, self, :safe => @safe) end end end
ruby
MIT
db309362b9069796ceffdbb494f49e86dc26a7b2
2026-01-04T17:57:03.242146Z
false
gdb/embedded-mongo
https://github.com/gdb/embedded-mongo/blob/db309362b9069796ceffdbb494f49e86dc26a7b2/lib/embedded-mongo/util.rb
lib/embedded-mongo/util.rb
module EmbeddedMongo module Util def self.stringify_hash!(hash) raise ArgumentError.new("Argument is not a hash: #{hash.inspect}") unless hash.kind_of?(Hash) stringify!(hash) end def self.deep_clone(obj) case obj when Hash clone = {} obj.each { |k, v| clone[deep_clone(k)] = deep_clone(v) } clone when Array obj.map { |v| deep_clone(v) } when Numeric, true, false, nil obj else obj.dup end end private def self.stringify!(struct) case struct when Hash struct.keys.each do |key| struct[key.to_s] = stringify!(struct.delete(key)) end struct when Array struct.each_with_index { |entry, i| struct[i] = stringify!(entry) } when Symbol struct.to_s when String, Numeric, BSON::ObjectId, Regexp, TrueClass, FalseClass, Time, nil struct else raise "Cannot stringify #{struct.inspect}" end end end end
ruby
MIT
db309362b9069796ceffdbb494f49e86dc26a7b2
2026-01-04T17:57:03.242146Z
false
gdb/embedded-mongo
https://github.com/gdb/embedded-mongo/blob/db309362b9069796ceffdbb494f49e86dc26a7b2/lib/embedded-mongo/backend/collection.rb
lib/embedded-mongo/backend/collection.rb
module EmbeddedMongo::Backend class Collection class DuplicateKeyError < StandardError; end def initialize(db, name) # TODO: system.namespaces @db = db @name = name @data = [] if name == 'system.namespaces' # mark as system? elsif name['.'] or name['$'] raise ArgumentError.new("Invalid collection name #{name.inspect}") end end def insert_documents(documents) documents.each { |doc| insert(EmbeddedMongo::Util.deep_clone(doc)) } documents.map { |doc| doc['_id'] } end def find(selector, opts) limit = opts.delete(:limit) sort = opts.delete(:sort) raise ArgumentError.new("Unrecognized opts: #{opts.inspect}") unless opts.empty? results = [] data.each do |doc| if selector_match?(selector, doc) results << doc break if limit > 0 and results.length >= limit end end EmbeddedMongo.log.debug("Query has #{results.length} matches") if sort case sort when String sort = [[sort]] when Array sort = [sort] unless sort.first.kind_of?(Array) else raise Mongo::InvalidSortValueError.new("invalid sort type: #{sort.inspect}") end results.sort! { |x, y| sort_cmp(sort, x, y) } end results end def update(selector, update, opts) # TODO: return value? multi = opts.delete(:multi) upsert = opts.delete(:upsert) safe = opts.delete(:safe) # TODO: do something with this raise ArgumentError.new("Unrecognized opts: #{opts.inspect}") unless opts.empty? n = 0 @data.each do |doc| next unless selector_match?(selector, doc) apply_update!(update, doc) n += 1 break unless multi end if n == 0 and upsert selector = EmbeddedMongo::Util.deep_clone(selector) selector['_id'] ||= BSON::ObjectId.new apply_update!(update, selector) insert(selector) @db.set_last_error({ 'updatedExisting' => false, 'upserted' => update['_id'], 'n' => 1 }) else @db.set_last_error({ 'updatedExisting' => n > 0, 'n' => n }) end end def remove(selector={}, opts={}) @data.reject! { |doc| selector_match?(selector, doc) } end private def data if @name == 'system.namespaces' @db.collections.keys.map { |name| { 'name' => "#{@db.name}.#{name}" } } else @data end end def check_id(doc) id = doc['_id'] raise NotImplementedError.new("#{doc.inspect} has no '_id' attribute") unless id end def check_duplicate_key(doc) raise DuplicateKeyError if @data.any? { |other| doc['_id'] == other['_id'] } end # Make sure to clone at call sites def insert(doc) begin check_id(doc) check_duplicate_key(doc) rescue DuplicateKeyError EmbeddedMongo.log.info("Duplicate key error: #{id}") return end @data << doc end def sort_cmp(sort, x, y) sort.each do |spec| case spec when String field = spec direction = nil when Array field, direction = spec else raise Mongo::InvalidSortValueError.new("invalid sort directive: #{spec.inspect}") end x_val = x[field.to_s] y_val = y[field.to_s] if direction.to_s == 'ascending' or direction.to_s == 'asc' or (direction.kind_of?(Numeric) and direction > 0) or direction.nil? if x_val.kind_of?(Numeric) and y_val.kind_of?(Numeric) cmp = x_val <=> y_val elsif x_val.kind_of?(Numeric) cmp = 1 elsif y_val.kind_of?(Numeric) cmp = -1 else cmp = 0 end return cmp if cmp != 0 elsif direction.to_s == 'descending' or direction.to_s == 'desc' or (direction.kind_of?(Numeric) and direction < 0) if x_val.kind_of?(Numeric) and y_val.kind_of?(Numeric) cmp = y_val <=> x_val elsif x_val.kind_of?(Numeric) cmp = -1 elsif y_val.kind_of?(Numeric) cmp = 1 else cmp = 0 end return cmp if cmp != 0 else raise NotImplementedError.new("Unrecognized sort [field, direction] = [#{field.inspect}, #{direction.inspect}] (full spec #{sort.inspect}") end end 0 end def selector_match?(selector, doc) raise NotImplementedError.new('Does not current support $where queries') if selector.has_key?('$where') selector.all? do |k, v| if(k == "$or") v.any? do |partial_selector| selector_match?(partial_selector, doc) end elsif(k == "$and") v.all? do |partial_selector| selector_match?(partial_selector, doc) end else partial_match?(v, doc[k]) end end end def partial_match?(partial_selector, value) EmbeddedMongo.log.debug("partial_match? #{partial_selector.inspect} #{value.inspect}") case partial_selector when Array, Numeric, String, BSON::ObjectId, TrueClass, FalseClass, Time, nil if value.kind_of? Array then value.include? partial_selector else partial_selector == value end when Hash if no_directive?(partial_selector) partial_selector == value else raise NotImplementedError.new("Cannot mix $ directives with non: #{partial_selector.inspect}") if has_non_directive?(partial_selector) partial_selector.all? do |k, v| directive_match?(k, v, value) end end else raise "Unsupported selector #{partial_selector.inspect}" end end def directive_match?(directive_key, directive_value, value) case directive_key when '$lt' raise NotImplementedError.new("Only implemented for numeric directive values: #{directive_value.inspect}") unless directive_value.kind_of?(Numeric) value and value < directive_value when '$gt' raise NotImplementedError.new("Only implemented for numeric directive values: #{directive_value.inspect}") unless directive_value.kind_of?(Numeric) value and value > directive_value when '$gte' raise NotImplementedError.new("Only implemented for numeric directive values: #{directive_value.inspect}") unless directive_value.kind_of?(Numeric) value and value >= directive_value when '$lte' raise NotImplementedError.new("Only implemented for numeric directive values: #{directive_value.inspect}") unless directive_value.kind_of?(Numeric) value and value <= directive_value when '$in' raise NotImplementedError.new("Only implemented for arrays: #{directive_value.inspect}") unless directive_value.kind_of?(Array) directive_value.include?(value) when '$ne' directive_value != value else raise NotImplementedError.new("Have yet to implement: #{directive_key}") # raise Mongo::OperationFailure.new("invalid operator: #{directive_key}") end end def apply_update!(update, doc) EmbeddedMongo.log.info("Applying update: #{update.inspect} to #{doc.inspect}") id = doc['_id'] if no_directive?(update) doc.clear update.each { |k, v| doc[k] = v } else # TODO: should set_last_error to {"err"=>"Modifiers and non-modifiers cannot be mixed", "code"=>10154, "n"=>0, "ok"=>1.0} raise NotImplementedError.new("Modifiers and non-modifiers cannot be mixed #{update.inspect}") if has_non_directive?(update) update.each do |directive_key, directive_value| apply_update_directive!(directive_key, directive_value, doc) end end doc['_id'] ||= id end def apply_update_directive!(directive_key, directive_value, doc) case directive_key when '$set' directive_value.each { |k, v| doc[k] = v } when '$inc' directive_value.each do |k, v| unless doc[k].kind_of?(Numeric) raise Mongo::OperationFailure.new("Cannot apply $inc modifier to non-number", 10140) end doc[k] += v end else raise NotImplementedError.new("Have yet to implement updating: #{directive_key}") end end def has_non_directive?(document) document.any? { |k, v| !k.start_with?('$') } end def no_directive?(document) document.all? { |k, v| !k.start_with?('$') } end end end
ruby
MIT
db309362b9069796ceffdbb494f49e86dc26a7b2
2026-01-04T17:57:03.242146Z
false
gdb/embedded-mongo
https://github.com/gdb/embedded-mongo/blob/db309362b9069796ceffdbb494f49e86dc26a7b2/lib/embedded-mongo/backend/db.rb
lib/embedded-mongo/backend/db.rb
module EmbeddedMongo::Backend class DB attr_reader :collections, :name def initialize(manager, name) raise ArgumentError.new("Invalid collection name #{name.inspect}") if name['.'] or name['$'] @manager = manager @name = name @collections = {} set_last_error({}) end def run_command(cmd) if cmd['dropDatabase'] @manager.drop_db(@name) [{ 'dropped' => @name, 'ok' => 1.0 }] elsif collection_name = cmd['drop'] @collections.delete(collection_name) [{ 'ok' => 1.0 }] elsif collection_name = cmd['create'] get_collection(collection_name) [{ 'ok' => 1.0 }] elsif cmd['buildinfo'] raise "Command #{cmd.inspect} only allowed for admin database" unless @name == 'admin' # {"ok"=>1, "debug"=>false, "bits"=>64, "versionArray"=>[2, 0, 4, 0], "version"=>"2.0.4", "maxBsonObjectSize"=>16777216, "sysInfo"=>"Linux yellow 2.6.24-29-server #1 SMP Tue Oct 11 15:57:27 UTC 2011 x86_64 BOOST_LIB_VERSION=1_46_1", "gitVersion"=>"nogitversion"} [{ 'version' => '2.0.4.0', # sure, this seems like a good version 'gitVersion' => 'nogitversion', 'sysInfo' => 'fake sysinfo', 'bits' => 64, 'debug' => false, 'ok' => 1.0 }] elsif cmd['getlasterror'] [@last_error] elsif cmd.has_key?('$eval') raise NotImplementedError.new('Does not currently support $eval commands') else raise NotImplementedError.new("Unrecognized command #{cmd.inspect}") end end def set_last_error(opts) @last_error = { 'err' => nil, 'n' => 0, 'ok' => 1.0 }.merge(opts) end # TODO: don't think we always create a collection def get_collection(collection_name) @collections[collection_name] ||= Collection.new(self, collection_name) end end end
ruby
MIT
db309362b9069796ceffdbb494f49e86dc26a7b2
2026-01-04T17:57:03.242146Z
false
gdb/embedded-mongo
https://github.com/gdb/embedded-mongo/blob/db309362b9069796ceffdbb494f49e86dc26a7b2/lib/embedded-mongo/backend/manager.rb
lib/embedded-mongo/backend/manager.rb
module EmbeddedMongo::Backend class Manager def initialize(spec) @spec = spec @dbs = {} end def insert_documents(db_name, collection_name, documents) documents.each { |doc| EmbeddedMongo::Util.stringify_hash!(doc) } EmbeddedMongo.log.info("INSERT: #{db_name.inspect} #{collection_name.inspect} #{documents.inspect}") collection = get_collection(db_name, collection_name) collection.insert_documents(documents) end def find(db_name, collection_name, selector, opts) EmbeddedMongo::Util.stringify_hash!(selector) EmbeddedMongo.log.info("FIND: #{db_name.inspect} #{collection_name.inspect} #{selector.inspect}") if collection_name == '$cmd' db = get_db(db_name) return db.run_command(selector) end collection = get_collection(db_name, collection_name) collection.find(selector, opts) end def update(db_name, collection_name, selector, update, opts) EmbeddedMongo::Util.stringify_hash!(selector) EmbeddedMongo::Util.stringify_hash!(update) EmbeddedMongo.log.info("UPDATE: #{db_name.inspect} #{collection_name.inspect} #{selector.inspect} #{update.inspect} #{opts.inspect}") collection = get_collection(db_name, collection_name) collection.update(selector, update, opts) end def remove(db_name, collection_name, selector, opts) EmbeddedMongo::Util.stringify_hash!(selector) EmbeddedMongo.log.info("REMOVE: #{db_name.inspect} #{collection_name.inspect} #{selector.inspect} #{opts.inspect}") collection = get_collection(db_name, collection_name) collection.remove(selector, opts) end # Management functions def drop_db(db_name) @dbs.delete(db_name) end private def get_db(db_name) @dbs[db_name] ||= DB.new(self, db_name) end def get_collection(db_name, collection_name) db = get_db(db_name) collection = db.get_collection(collection_name) collection end end end
ruby
MIT
db309362b9069796ceffdbb494f49e86dc26a7b2
2026-01-04T17:57:03.242146Z
false
pedro/heroku-mongo-sync
https://github.com/pedro/heroku-mongo-sync/blob/878899260c37a412b80e613f2b04f63ac3b3f5f4/init.rb
init.rb
$stderr.puts "the heroku-mongo-sync plugin has moved to a new owner" $stderr.puts "please refer to the fork at https://github.com/marcofognog/heroku-mongo-sync" require 'heroku/command/mongo'
ruby
MIT
878899260c37a412b80e613f2b04f63ac3b3f5f4
2026-01-04T17:57:04.256009Z
false
pedro/heroku-mongo-sync
https://github.com/pedro/heroku-mongo-sync/blob/878899260c37a412b80e613f2b04f63ac3b3f5f4/spec/mongo_spec.rb
spec/mongo_spec.rb
require 'rubygems' require 'mongo' require 'baconmocha' $: << File.dirname(__FILE__) + '/../lib' require 'heroku' require 'heroku/command' require 'heroku/command/mongo' describe Heroku::Command::Mongo do before do @mongo = Heroku::Command::Mongo.new ['--app', 'myapp'] @mongo.stubs(:app).returns('myapp') @mongo.stubs(:display) end it "rescues exceptions when establishing a connection" do @mongo.expects(:error) Mongo::Connection.stubs(:new).raises(Mongo::ConnectionFailure) @mongo.send(:make_connection, URI.parse('mongodb://localhost')) end it "rejects urls without host" do @mongo.expects(:error) @mongo.send(:make_uri, 'test') end it "rescues URI parsing errors" do @mongo.expects(:error) @mongo.send(:make_uri, 'test:') end it "fixes mongohq addresses so it can connect from outside EC2" do uri = @mongo.send(:make_uri, 'mongodb://root:secret@hatch.local.mongohq.com/mydb') uri.host.should == 'hatch.mongohq.com' end describe "Integration test" do before do conn = Mongo::Connection.new @from = conn.db('heroku-mongo-sync-origin') @from_uri = URI.parse('mongodb://localhost/heroku-mongo-sync-origin') @to = conn.db('heroku-mongo-sync-dest') @to_uri = URI.parse('mongodb://localhost/heroku-mongo-sync-dest') clear_collections end after do clear_collections end def clear_collections @from.collections.each { |c| c.drop } @to.collections.each { |c| c.drop } end it "transfers records" do col = @from.create_collection('a') col.insert(:id => 1, :name => 'first') col.insert(:id => 2, :name => 'second') @mongo.send(:transfer, @from_uri, @to_uri) @to.collection_names.should.include('a') @to.collection('a').find_one(:id => 1)['name'].should == 'first' end it "replaces existing data" do col1 = @from.create_collection('a') col1.insert(:id => 1, :name => 'first') col2 = @to.create_collection('a') col2.insert(:id => 2, :name => 'second') @mongo.send(:transfer, @from_uri, @to_uri) @to.collection('a').size.should == 1 end end end
ruby
MIT
878899260c37a412b80e613f2b04f63ac3b3f5f4
2026-01-04T17:57:04.256009Z
false
pedro/heroku-mongo-sync
https://github.com/pedro/heroku-mongo-sync/blob/878899260c37a412b80e613f2b04f63ac3b3f5f4/lib/heroku/command/mongo.rb
lib/heroku/command/mongo.rb
module Heroku::Command class Mongo < BaseWithApp def initialize(*args) super require 'mongo' rescue LoadError error "Install the Mongo gem to use mongo commands:\nsudo gem install mongo" end def push display "THIS WILL REPLACE ALL DATA for #{app} ON #{heroku_mongo_uri.host} WITH #{local_mongo_uri.host}" display "Are you sure? (y/n) ", false return unless ask.downcase == 'y' transfer(local_mongo_uri, heroku_mongo_uri) end def pull display "Replacing the #{app} db at #{local_mongo_uri.host} with #{heroku_mongo_uri.host}" transfer(heroku_mongo_uri, local_mongo_uri) end protected def transfer(from, to) origin = make_connection(from) dest = make_connection(to) origin.collections.each do |col| next if col.name =~ /^system\./ display "Syncing #{col.name} (#{col.size})...", false dest.drop_collection(col.name) dest_col = dest.create_collection(col.name) col.find().each do |record| dest_col.insert record end display " done" end display "Syncing indexes...", false dest_index_col = dest.collection('system.indexes') origin_index_col = origin.collection('system.indexes') origin_index_col.find().each do |index| if index['_id'] index['ns'] = index['ns'].sub(origin_index_col.db.name, dest_index_col.db.name) dest_index_col.insert index end end display " done" end def heroku_mongo_uri config = heroku.config_vars(app) url = config['MONGO_URL'] || config['MONGOHQ_URL'] || config['MONGOLAB_URI'] error("Could not find the MONGO_URL for #{app}") unless url make_uri(url) end def local_mongo_uri url = ENV['MONGO_URL'] || "mongodb://localhost:27017/#{app}" make_uri(url) end def make_uri(url) urlsub = url.gsub('local.mongohq.com', 'mongohq.com') uri = URI.parse(urlsub) raise URI::InvalidURIError unless uri.host uri rescue URI::InvalidURIError error("Invalid mongo url: #{url}") end def make_connection(uri) connection = ::Mongo::Connection.new(uri.host, uri.port) db = connection.db(uri.path.gsub(/^\//, '')) db.authenticate(uri.user, uri.password) if uri.user db rescue ::Mongo::ConnectionFailure error("Could not connect to the mongo server at #{uri}") end Help.group 'Mongo' do |group| group.command 'mongo:push', 'push the local mongo database' group.command 'mongo:pull', 'pull from the production mongo database' end end end
ruby
MIT
878899260c37a412b80e613f2b04f63ac3b3f5f4
2026-01-04T17:57:04.256009Z
false
indirect/middleman-heroku-static-app
https://github.com/indirect/middleman-heroku-static-app/blob/84b1b849021c62ee759d75fdc99845a697253ddd/config.rb
config.rb
activate :automatic_image_sizes activate :directory_indexes set :css_dir, 'stylesheets' set :js_dir, 'javascripts' set :images_dir, 'images' configure :build do activate :minify_css activate :minify_javascript activate :asset_hash end # silence i18n warning ::I18n.config.enforce_available_locales = false
ruby
MIT
84b1b849021c62ee759d75fdc99845a697253ddd
2026-01-04T17:57:06.631567Z
false
c10l/vagrant-butcher
https://github.com/c10l/vagrant-butcher/blob/169cc1d9deeadae3ffc450d454aa065100617e5d/spec/spec_helper.rb
spec/spec_helper.rb
require 'rubygems' require 'bundler/setup' require 'vagrant-butcher'
ruby
MIT
169cc1d9deeadae3ffc450d454aa065100617e5d
2026-01-04T17:57:07.755956Z
false
c10l/vagrant-butcher
https://github.com/c10l/vagrant-butcher/blob/169cc1d9deeadae3ffc450d454aa065100617e5d/spec/unit/vagrant_butcher_spec.rb
spec/unit/vagrant_butcher_spec.rb
require 'spec_helper.rb' describe Vagrant::Butcher::Plugin do end
ruby
MIT
169cc1d9deeadae3ffc450d454aa065100617e5d
2026-01-04T17:57:07.755956Z
false
c10l/vagrant-butcher
https://github.com/c10l/vagrant-butcher/blob/169cc1d9deeadae3ffc450d454aa065100617e5d/spec/unit/vagrant_butcher/config_spec.rb
spec/unit/vagrant_butcher/config_spec.rb
require 'spec_helper.rb' describe Vagrant::Butcher::Config do subject { described_class.new } it "permits the user to (en|dis)able the plugin" do expect(subject).to respond_to(:enabled=) end it "has the option to set guest chef client pem path" do expect(subject).to respond_to(:guest_key_path=) end it "has the option to verify SSL certs" do expect(subject).to respond_to(:verify_ssl=) end it "allows the user to configure a proxy" do expect(subject).to respond_to(:proxy=) end it "has an option to set a custom client_name" do expect(subject).to respond_to(:client_name=) end it "has an option to point to a local client key" do expect(subject).to respond_to(:client_key=) end it "does not have the option to set knife.rb path" do expect(subject).to_not respond_to(:knife_config_file=) end it "does not have the option to set cache dir path" do expect(subject).to_not respond_to(:cache_dir=) end it "sets guest chef client pem default path" do subject.finalize! expect(subject.guest_key_path).to eql(:DEFAULT) end it "sets cache dir path" do subject.finalize! expect(subject.cache_dir).to eql(".vagrant/butcher") end end
ruby
MIT
169cc1d9deeadae3ffc450d454aa065100617e5d
2026-01-04T17:57:07.755956Z
false
c10l/vagrant-butcher
https://github.com/c10l/vagrant-butcher/blob/169cc1d9deeadae3ffc450d454aa065100617e5d/lib/vagrant-butcher.rb
lib/vagrant-butcher.rb
begin require "vagrant" rescue LoadError raise "This plugin must run within Vagrant." end require 'vagrant-butcher/version' require 'vagrant-butcher/errors' # Work around logger spam from hashie # https://github.com/intridea/hashie/issues/394 begin require "hashie" require "hashie/logger" # We cannot `disable_warnings` in a subclass because # Hashie::Mash is used directly in the Ridley dependency: # https://github.com/berkshelf/ridley/search?q=Hashie&unscoped_q=Hashie # Therefore, we completely silence the Hashie logger as done in Berkshelf: # https://github.com/berkshelf/berkshelf/pull/1668/files#diff-3eca4e8b32b88ae6a1f14498e3ef7b25R5 Hashie.logger = Logger.new(nil) rescue LoadError # intentionally left blank end module Vagrant module Butcher autoload :Action, 'vagrant-butcher/action' autoload :Config, 'vagrant-butcher/config' autoload :Helpers, 'vagrant-butcher/helpers' end end require 'vagrant-butcher/plugin'
ruby
MIT
169cc1d9deeadae3ffc450d454aa065100617e5d
2026-01-04T17:57:07.755956Z
false
c10l/vagrant-butcher
https://github.com/c10l/vagrant-butcher/blob/169cc1d9deeadae3ffc450d454aa065100617e5d/lib/vagrant-butcher/version.rb
lib/vagrant-butcher/version.rb
module Vagrant module Butcher VERSION = "2.3.2.pre" end end
ruby
MIT
169cc1d9deeadae3ffc450d454aa065100617e5d
2026-01-04T17:57:07.755956Z
false
c10l/vagrant-butcher
https://github.com/c10l/vagrant-butcher/blob/169cc1d9deeadae3ffc450d454aa065100617e5d/lib/vagrant-butcher/errors.rb
lib/vagrant-butcher/errors.rb
require 'vagrant/errors' module Vagrant module Butcher module Errors class KeyCopyFailure < ::Vagrant::Errors::VagrantError end class NoSyncedFolder < ::Vagrant::Errors::VagrantError end end end end
ruby
MIT
169cc1d9deeadae3ffc450d454aa065100617e5d
2026-01-04T17:57:07.755956Z
false
c10l/vagrant-butcher
https://github.com/c10l/vagrant-butcher/blob/169cc1d9deeadae3ffc450d454aa065100617e5d/lib/vagrant-butcher/plugin.rb
lib/vagrant-butcher/plugin.rb
module Vagrant module Butcher class Plugin < Vagrant.plugin('2') name "vagrant-butcher" description <<-DESC Delete node and client from the Chef server when destroying the VM. DESC class << self def provision(hook) # This should be at the end so that it can copy the chef client pem. hook.before(::Vagrant::Action::Builtin::Provision, Vagrant::Butcher::Action.copy_guest_key) end end action_hook(:vagrant_butcher_copy_guest_key, :machine_action_up, &method(:provision)) action_hook(:vagrant_butcher_copy_guest_key, :machine_action_reload, &method(:provision)) action_hook(:vagrant_butcher_copy_guest_key, :machine_action_provision, &method(:provision)) action_hook(:vagrant_butcher_cleanup, :machine_action_destroy) do |hook| hook.before(::Vagrant::Action::Builtin::ProvisionerCleanup, Vagrant::Butcher::Action.cleanup) end config("butcher") do Config end end end end
ruby
MIT
169cc1d9deeadae3ffc450d454aa065100617e5d
2026-01-04T17:57:07.755956Z
false
c10l/vagrant-butcher
https://github.com/c10l/vagrant-butcher/blob/169cc1d9deeadae3ffc450d454aa065100617e5d/lib/vagrant-butcher/helpers.rb
lib/vagrant-butcher/helpers.rb
module Vagrant module Butcher module Helpers autoload :Config, 'vagrant-butcher/helpers/config' autoload :Action, 'vagrant-butcher/helpers/action' autoload :KeyFiles, 'vagrant-butcher/helpers/key_files' autoload :Connection, 'vagrant-butcher/helpers/connection' autoload :Guest, 'vagrant-butcher/helpers/guest' end end end
ruby
MIT
169cc1d9deeadae3ffc450d454aa065100617e5d
2026-01-04T17:57:07.755956Z
false
c10l/vagrant-butcher
https://github.com/c10l/vagrant-butcher/blob/169cc1d9deeadae3ffc450d454aa065100617e5d/lib/vagrant-butcher/config.rb
lib/vagrant-butcher/config.rb
module Vagrant module Butcher class Config < ::Vagrant.plugin('2', :config) include Helpers::Guest attr_accessor :enabled attr_accessor :guest_key_path attr_reader :cache_dir attr_accessor :verify_ssl attr_accessor :retries attr_accessor :retry_interval attr_accessor :proxy attr_accessor :client_name attr_accessor :client_key def initialize super @enabled = UNSET_VALUE @guest_key_path = UNSET_VALUE @cache_dir = ".vagrant/butcher" @verify_ssl = UNSET_VALUE @retries = UNSET_VALUE @retry_interval = UNSET_VALUE @proxy = UNSET_VALUE @client_name = UNSET_VALUE @client_key = UNSET_VALUE end def finalize! @enabled = true if @enabled == UNSET_VALUE @guest_key_path = :DEFAULT if @guest_key_path == UNSET_VALUE @verify_ssl = true if @verify_ssl == UNSET_VALUE @retries = 0 if @retries == UNSET_VALUE @retry_interval = 0 if @retry_interval == UNSET_VALUE @proxy = nil if @proxy == UNSET_VALUE @client_name = nil if @client_name == UNSET_VALUE @client_key = nil if @client_key == UNSET_VALUE end end end end
ruby
MIT
169cc1d9deeadae3ffc450d454aa065100617e5d
2026-01-04T17:57:07.755956Z
false
c10l/vagrant-butcher
https://github.com/c10l/vagrant-butcher/blob/169cc1d9deeadae3ffc450d454aa065100617e5d/lib/vagrant-butcher/action.rb
lib/vagrant-butcher/action.rb
module Vagrant module Butcher module Action autoload :Cleanup, 'vagrant-butcher/action/cleanup' autoload :CopyGuestKey, 'vagrant-butcher/action/copy_guest_key' def self.cleanup ::Vagrant::Action::Builder.new.tap do |b| b.use Vagrant::Butcher::Action::Cleanup end end def self.copy_guest_key ::Vagrant::Action::Builder.new.tap do |b| b.use Vagrant::Butcher::Action::CopyGuestKey end end end end end
ruby
MIT
169cc1d9deeadae3ffc450d454aa065100617e5d
2026-01-04T17:57:07.755956Z
false
c10l/vagrant-butcher
https://github.com/c10l/vagrant-butcher/blob/169cc1d9deeadae3ffc450d454aa065100617e5d/lib/vagrant-butcher/helpers/connection.rb
lib/vagrant-butcher/helpers/connection.rb
require 'ridley' # Silence celluloid warnings and errors: https://github.com/RiotGames/ridley/issues/220 ::Ridley::Logging.logger.level = Logger.const_get 'FATAL' module Vagrant module Butcher module Helpers module Connection include ::Vagrant::Butcher::Helpers::KeyFiles def setup_connection(env) begin @conn = ::Ridley.new( server_url: chef_provisioner(env).chef_server_url, client_name: client_name(env), client_key: client_key_path(env), ssl: { verify: butcher_config(env).verify_ssl }, retries: butcher_config(env).retries, retry_interval: butcher_config(env).retry_interval, proxy: butcher_config(env).proxy ) rescue Ridley::Errors::ClientKeyFileNotFoundOrInvalid env[:ui].error "Chef client key not found at #{client_key_path(env)}" rescue Exception => e env[:ui].error "Could not connect to Chef Server: #{e}" end end def delete_resource(resource, env) begin @conn.send(resource.to_sym).delete(victim(env)) env[:ui].success "Chef #{resource} '#{victim(env)}' successfully butchered from the server..." rescue Exception => e env[:ui].warn "Could not butcher #{resource} #{victim(env)}: #{e.message}" @failed_deletions ||= [] @failed_deletions << resource end end def cleanup(env) if chef_client?(env) setup_connection(env) %w(node client).each { |resource| delete_resource(resource, env) } cleanup_cache_dir(env) end end end end end end
ruby
MIT
169cc1d9deeadae3ffc450d454aa065100617e5d
2026-01-04T17:57:07.755956Z
false
c10l/vagrant-butcher
https://github.com/c10l/vagrant-butcher/blob/169cc1d9deeadae3ffc450d454aa065100617e5d/lib/vagrant-butcher/helpers/guest.rb
lib/vagrant-butcher/helpers/guest.rb
module Vagrant module Butcher module Helpers module Guest def windows?(env) machine(env).guest.capability_host_chain.last.first == :windows end def get_guest_key_path(env) return butcher_config(env).guest_key_path unless butcher_config(env).guest_key_path == :DEFAULT return 'c:\etc\chef\client.pem' if windows?(env) return '/etc/chef/client.pem' end end end end end
ruby
MIT
169cc1d9deeadae3ffc450d454aa065100617e5d
2026-01-04T17:57:07.755956Z
false
c10l/vagrant-butcher
https://github.com/c10l/vagrant-butcher/blob/169cc1d9deeadae3ffc450d454aa065100617e5d/lib/vagrant-butcher/helpers/config.rb
lib/vagrant-butcher/helpers/config.rb
module Vagrant module Butcher module Helpers module Config def vm_config(env) @vm_config ||= machine(env).config.vm end def butcher_config(env) @butcher_config ||= machine(env).config.butcher end def chef_provisioner(env) @chef_provisioner ||= vm_config(env).provisioners.find do |p| p.config.is_a? VagrantPlugins::Chef::Config::ChefClient end.config end def chef_client?(env) vm_config(env).provisioners.select do |p| # At some point, Vagrant changed from name to type. p.name == :chef_client || \ p.type == :chef_client end.any? end def client_name(env) @client_name ||= butcher_config(env).client_name || victim(env) end def victim(env) @victim ||= chef_provisioner(env).node_name || vm_config(env).hostname || vm_config(env).box end end end end end
ruby
MIT
169cc1d9deeadae3ffc450d454aa065100617e5d
2026-01-04T17:57:07.755956Z
false