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 |
|---|---|---|---|---|---|---|---|---|
Netflix/fast_jsonapi | https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/lib/fast_jsonapi/instrumentation/skylight/normalizers/base.rb | lib/fast_jsonapi/instrumentation/skylight/normalizers/base.rb | require 'skylight'
SKYLIGHT_NORMALIZER_BASE_CLASS = begin
::Skylight::Core::Normalizers::Normalizer
rescue NameError
::Skylight::Normalizers::Normalizer
end
| ruby | Apache-2.0 | 68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7 | 2026-01-04T15:44:27.122992Z | false |
Netflix/fast_jsonapi | https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/lib/fast_jsonapi/instrumentation/skylight/normalizers/serializable_hash.rb | lib/fast_jsonapi/instrumentation/skylight/normalizers/serializable_hash.rb | require 'fast_jsonapi/instrumentation/skylight/normalizers/base'
require 'fast_jsonapi/instrumentation/serializable_hash'
module FastJsonapi
module Instrumentation
module Skylight
module Normalizers
class SerializableHash < SKYLIGHT_NORMALIZER_BASE_CLASS
register FastJsonapi::ObjectSerializer::SERIALIZABLE_HASH_NOTIFICATION
CAT = "view.#{FastJsonapi::ObjectSerializer::SERIALIZABLE_HASH_NOTIFICATION}".freeze
def normalize(trace, name, payload)
[ CAT, payload[:name], nil ]
end
end
end
end
end
end
| ruby | Apache-2.0 | 68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7 | 2026-01-04T15:44:27.122992Z | false |
Netflix/fast_jsonapi | https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/lib/extensions/has_one.rb | lib/extensions/has_one.rb | # frozen_string_literal: true
::ActiveRecord::Associations::Builder::HasOne.class_eval do
# Based on
# https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/builder/collection_association.rb#L50
# https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/builder/singular_association.rb#L11
def self.define_accessors(mixin, reflection)
super
name = reflection.name
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
def #{name}_id
# if an attribute is already defined with this methods name we should just use it
return read_attribute(__method__) if has_attribute?(__method__)
association(:#{name}).reader.try(:id)
end
CODE
end
end
| ruby | Apache-2.0 | 68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7 | 2026-01-04T15:44:27.122992Z | false |
Netflix/fast_jsonapi | https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/lib/generators/serializer/serializer_generator.rb | lib/generators/serializer/serializer_generator.rb | # frozen_string_literal: true
require 'rails/generators/base'
class SerializerGenerator < Rails::Generators::NamedBase
source_root File.expand_path('templates', __dir__)
argument :attributes, type: :array, default: [], banner: 'field field'
def create_serializer_file
template 'serializer.rb.tt', File.join('app', 'serializers', class_path, "#{file_name}_serializer.rb")
end
private
def attributes_names
attributes.map { |a| a.name.to_sym.inspect }
end
end
| ruby | Apache-2.0 | 68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7 | 2026-01-04T15:44:27.122992Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/db/migrate/1_setup_acts_as_taggable_on.rb | db/migrate/1_setup_acts_as_taggable_on.rb | # frozen_string_literal: true
# Combined migration for acts_as_taggable_on setup
# Combines migrations 1-7 from acts_as_taggable_on_engine
class SetupActsAsTaggableOn < ActiveRecord::Migration[7.1]
def up
# Create tags table
unless table_exists?(ActsAsTaggableOn.tags_table)
create_table ActsAsTaggableOn.tags_table do |t|
t.string :name
t.integer :taggings_count, default: 0
t.timestamps
end
end
# Add unique index on tag name
unless index_exists?(ActsAsTaggableOn.tags_table, :name)
add_index ActsAsTaggableOn.tags_table, :name, unique: true
end
# Create taggings table
unless table_exists?(ActsAsTaggableOn.taggings_table)
create_table ActsAsTaggableOn.taggings_table do |t|
t.references :tag, foreign_key: { to_table: ActsAsTaggableOn.tags_table }
t.references :taggable, polymorphic: true
t.references :tagger, polymorphic: true
t.string :context, limit: 128
t.string :tenant, limit: 128
t.datetime :created_at
end
end
# Add all indexes
add_index ActsAsTaggableOn.taggings_table,
%i[tag_id taggable_id taggable_type context tagger_id tagger_type],
unique: true, name: "taggings_idx" unless index_exists?(ActsAsTaggableOn.taggings_table, "taggings_idx", name: true)
add_index ActsAsTaggableOn.taggings_table, %i[taggable_id taggable_type context],
name: "taggings_taggable_context_idx" unless index_exists?(ActsAsTaggableOn.taggings_table, "taggings_taggable_context_idx", name: true)
add_index ActsAsTaggableOn.taggings_table, :tag_id unless index_exists?(ActsAsTaggableOn.taggings_table, :tag_id)
add_index ActsAsTaggableOn.taggings_table, :taggable_id unless index_exists?(ActsAsTaggableOn.taggings_table, :taggable_id)
add_index ActsAsTaggableOn.taggings_table, :taggable_type unless index_exists?(ActsAsTaggableOn.taggings_table, :taggable_type)
add_index ActsAsTaggableOn.taggings_table, :tagger_id unless index_exists?(ActsAsTaggableOn.taggings_table, :tagger_id)
add_index ActsAsTaggableOn.taggings_table, :context unless index_exists?(ActsAsTaggableOn.taggings_table, :context)
add_index ActsAsTaggableOn.taggings_table, %i[tagger_id tagger_type] unless index_exists?(ActsAsTaggableOn.taggings_table, %i[tagger_id tagger_type])
add_index ActsAsTaggableOn.taggings_table, %i[taggable_id taggable_type tagger_id context],
name: "taggings_idy" unless index_exists?(ActsAsTaggableOn.taggings_table, "taggings_idy", name: true)
add_index ActsAsTaggableOn.taggings_table, :tenant unless index_exists?(ActsAsTaggableOn.taggings_table, :tenant)
# Change collation for MySQL
return unless ActsAsTaggableOn::Utils.using_mysql?
return if table_exists?(ActsAsTaggableOn.tags_table) && column_exists?(ActsAsTaggableOn.tags_table, :name)
execute("ALTER TABLE #{ActsAsTaggableOn.tags_table} MODIFY name varchar(255) CHARACTER SET utf8 COLLATE utf8_bin;")
end
def down
# Depdending on your needs, you might want to implement the down method.
# Uncomment the lines below for new installations where rollback is necessary.
# drop_table ActsAsTaggableOn.taggings_table
# drop_table ActsAsTaggableOn.tags_table
raise ActiveRecord::IrreversibleMigration
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/spec_helper.rb | spec/spec_helper.rb | begin
require 'byebug'
rescue LoadError
end
$LOAD_PATH << '.' unless $LOAD_PATH.include?('.')
$LOAD_PATH.unshift(File.expand_path('../../lib', __FILE__))
require 'logger'
require File.expand_path('../../lib/acts-as-taggable-on', __FILE__)
I18n.enforce_available_locales = true
require 'rails'
require 'rspec/its'
require 'barrier'
require 'database_cleaner'
Dir['./spec/support/**/*.rb'].sort.each { |f| require f }
RSpec.configure do |config|
config.raise_errors_for_deprecations!
config.color = true
# disable monkey patching
# see: https://rspec.info/features/3-13/rspec-core/configuration/zero-monkey-patching-mode/
config.disable_monkey_patching!
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean
end
config.before(:each, :database_cleaner_delete) do
DatabaseCleaner.strategy = :truncation
end
config.after(:suite) do
DatabaseCleaner.clean
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/support/0-helpers.rb | spec/support/0-helpers.rb | def using_sqlite?
ActsAsTaggableOn::Utils.connection && ActsAsTaggableOn::Utils.connection.adapter_name == 'SQLite'
end
def supports_concurrency?
!using_sqlite?
end
def using_postgresql?
ActsAsTaggableOn::Utils.using_postgresql?
end
def postgresql_version
if using_postgresql?
ActsAsTaggableOn::Utils.connection.execute('SHOW SERVER_VERSION').first['server_version'].to_f
else
0.0
end
end
def postgresql_support_json?
postgresql_version >= 9.2
end
def using_mysql?
ActsAsTaggableOn::Utils.using_mysql?
end
def using_case_insensitive_collation?
using_mysql? && ActsAsTaggableOn::Utils.connection.collation =~ /_ci\Z/
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/support/array.rb | spec/support/array.rb | unless [].respond_to?(:freq)
class Array
def freq
k=Hash.new(0)
each { |e| k[e]+=1 }
k
end
end
end | ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/support/database.rb | spec/support/database.rb | # frozen_string_literal: true
# set adapter to use, default is sqlite3
# to use an alternative adapter run => rake spec DB='postgresql'
db_name = ENV['DB'] || 'sqlite3'
database_yml = File.expand_path('../internal/config/database.yml', __dir__)
unless File.exist?(database_yml)
raise "Please create #{database_yml} first to configure your database. Take a look at: #{database_yml}.sample"
end
ActiveRecord::Base.configurations = YAML.load_file(database_yml)
ActiveRecord::Base.logger = Logger.new(File.join(File.dirname(__FILE__), '../debug.log'))
ActiveRecord::Base.logger.level = ENV['CI'] ? ::Logger::ERROR : ::Logger::DEBUG
ActiveRecord::Migration.verbose = false
ActiveRecord.default_timezone = :utc
config = ActiveRecord::Base.configurations.configs_for(env_name: db_name)
begin
ActiveRecord::Base.establish_connection(db_name.to_sym)
ActiveRecord::Base.connection
rescue StandardError
case db_name
when /(mysql)/
ActiveRecord::Base.establish_connection(config.merge('database' => nil))
ActiveRecord::Base.connection.create_database(config['database'],
{ charset: 'utf8', collation: 'utf8_unicode_ci' })
when 'postgresql'
ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres',
'schema_search_path' => 'public'))
ActiveRecord::Base.connection.create_database(config['database'], config.merge('encoding' => 'utf8'))
end
ActiveRecord::Base.establish_connection(config)
end
require "#{File.dirname(__FILE__)}/../internal/db/schema.rb"
Dir["#{File.dirname(__dir__)}/internal/app/models/*.rb"].each { |f| require f }
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/acts_as_taggable_on/tag_list_spec.rb | spec/acts_as_taggable_on/tag_list_spec.rb | require 'spec_helper'
RSpec.describe ActsAsTaggableOn::TagList do
let(:tag_list) { ActsAsTaggableOn::TagList.new('awesome', 'radical') }
let(:another_tag_list) { ActsAsTaggableOn::TagList.new('awesome','crazy', 'alien') }
it { should be_kind_of Array }
describe '#add' do
it 'should be able to be add a new tag word' do
tag_list.add('cool')
expect(tag_list.include?('cool')).to be_truthy
end
it 'should be able to add delimited lists of words' do
tag_list.add('cool, wicked', parse: true)
expect(tag_list).to include('cool', 'wicked')
end
it 'should be able to add delimited list of words with quoted delimiters' do
tag_list.add("'cool, wicked', \"really cool, really wicked\"", parse: true)
expect(tag_list).to include('cool, wicked', 'really cool, really wicked')
end
it 'should be able to handle other uses of quotation marks correctly' do
tag_list.add("john's cool car, mary's wicked toy", parse: true)
expect(tag_list).to include("john's cool car", "mary's wicked toy")
end
it 'should be able to add an array of words' do
tag_list.add(%w(cool wicked), parse: true)
expect(tag_list).to include('cool', 'wicked')
end
it 'should quote escape tags with commas in them' do
tag_list.add('cool', 'rad,bodacious')
expect(tag_list.to_s).to eq("awesome, radical, cool, \"rad,bodacious\"")
end
end
describe '#remove' do
it 'should be able to remove words' do
tag_list.remove('awesome')
expect(tag_list).to_not include('awesome')
end
it 'should be able to remove delimited lists of words' do
tag_list.remove('awesome, radical', parse: true)
expect(tag_list).to be_empty
end
it 'should be able to remove an array of words' do
tag_list.remove(%w(awesome radical), parse: true)
expect(tag_list).to be_empty
end
end
describe '#+' do
it 'should not have duplicate tags' do
new_tag_list = tag_list + another_tag_list
expect(tag_list).to eq(%w[awesome radical])
expect(another_tag_list).to eq(%w[awesome crazy alien])
expect(new_tag_list).to eq(%w[awesome radical crazy alien])
end
it 'should have class : ActsAsTaggableOn::TagList' do
new_tag_list = tag_list + another_tag_list
expect(new_tag_list.class).to eq(ActsAsTaggableOn::TagList)
end
end
describe '#concat' do
it 'should not have duplicate tags' do
expect(tag_list.concat(another_tag_list)).to eq(%w[awesome radical crazy alien])
end
it 'should have class : ActsAsTaggableOn::TagList' do
new_tag_list = tag_list.concat(another_tag_list)
expect(new_tag_list.class).to eq(ActsAsTaggableOn::TagList)
end
context 'without duplicates' do
let(:arr) { ['crazy', 'alien'] }
let(:another_tag_list) { ActsAsTaggableOn::TagList.new(*arr) }
it 'adds other list' do
expect(tag_list.concat(another_tag_list)).to eq(%w[awesome radical crazy alien])
end
it 'adds other array' do
expect(tag_list.concat(arr)).to eq(%w[awesome radical crazy alien])
end
end
end
describe '#to_s' do
it 'should give a delimited list of words when converted to string' do
expect(tag_list.to_s).to eq('awesome, radical')
end
it 'should be able to call to_s on a frozen tag list' do
tag_list.freeze
expect { tag_list.add('cool', 'rad,bodacious') }.to raise_error(RuntimeError)
expect { tag_list.to_s }.to_not raise_error
end
end
describe 'cleaning' do
it 'should parameterize if force_parameterize is set to true' do
ActsAsTaggableOn.force_parameterize = true
tag_list = ActsAsTaggableOn::TagList.new('awesome()', 'radical)(cc')
expect(tag_list.to_s).to eq('awesome, radical-cc')
ActsAsTaggableOn.force_parameterize = false
end
it 'should lowercase if force_lowercase is set to true' do
ActsAsTaggableOn.force_lowercase = true
tag_list = ActsAsTaggableOn::TagList.new('aweSomE', 'RaDicaL', 'Entrée')
expect(tag_list.to_s).to eq('awesome, radical, entrée')
ActsAsTaggableOn.force_lowercase = false
end
it 'should ignore case when removing duplicates if strict_case_match is false' do
tag_list = ActsAsTaggableOn::TagList.new('Junglist', 'JUNGLIST', 'Junglist', 'Massive', 'MASSIVE', 'MASSIVE')
expect(tag_list.to_s).to eq('Junglist, Massive')
end
it 'should not ignore case when removing duplicates if strict_case_match is true' do
ActsAsTaggableOn.strict_case_match = true
tag_list = ActsAsTaggableOn::TagList.new('Junglist', 'JUNGLIST', 'Junglist', 'Massive', 'MASSIVE', 'MASSIVE')
expect(tag_list.to_s).to eq('Junglist, JUNGLIST, Massive, MASSIVE')
ActsAsTaggableOn.strict_case_match = false
end
end
describe 'custom parser' do
let(:parser) { double(parse: %w(cool wicked)) }
let(:parser_class) { stub_const('MyParser', Class) }
it 'should use a the default parser if none is set as parameter' do
allow(ActsAsTaggableOn.default_parser).to receive(:new).and_return(parser)
ActsAsTaggableOn::TagList.new('cool, wicked', parse: true)
expect(parser).to have_received(:parse)
end
it 'should use the custom parser passed as parameter' do
allow(parser_class).to receive(:new).and_return(parser)
ActsAsTaggableOn::TagList.new('cool, wicked', parser: parser_class)
expect(parser).to have_received(:parse)
end
it 'should use the parser set as attribute' do
allow(parser_class).to receive(:new).with('new, tag').and_return(parser)
tag_list = ActsAsTaggableOn::TagList.new('example')
tag_list.parser = parser_class
tag_list.add('new, tag', parse: true)
expect(parser).to have_received(:parse)
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/acts_as_taggable_on/single_table_inheritance_spec.rb | spec/acts_as_taggable_on/single_table_inheritance_spec.rb | require 'spec_helper'
RSpec.describe 'Single Table Inheritance' do
let(:taggable) { TaggableModel.new(name: 'taggable model') }
let(:inheriting_model) { InheritingTaggableModel.new(name: 'Inheriting Taggable Model') }
let(:altered_inheriting) { AlteredInheritingTaggableModel.new(name: 'Altered Inheriting Model') }
1.upto(4) do |n|
let(:"inheriting_#{n}") { InheritingTaggableModel.new(name: "Inheriting Model #{n}") }
end
let(:student) { Student.create! }
describe 'tag contexts' do
it 'should pass on to STI-inherited models' do
expect(inheriting_model).to respond_to(:tag_list, :skill_list, :language_list)
expect(altered_inheriting).to respond_to(:tag_list, :skill_list, :language_list)
end
it 'should pass on to altered STI models' do
expect(altered_inheriting).to respond_to(:part_list)
end
end
context 'matching contexts' do
before do
inheriting_1.offering_list = 'one, two'
inheriting_1.need_list = 'one, two'
inheriting_1.save!
inheriting_2.need_list = 'one, two'
inheriting_2.save!
inheriting_3.offering_list = 'one, two'
inheriting_3.save!
inheriting_4.tag_list = 'one, two, three, four'
inheriting_4.save!
taggable.need_list = 'one, two'
taggable.save!
end
it 'should find objects with tags of matching contexts' do
expect(inheriting_1.find_matching_contexts(:offerings, :needs)).to include(inheriting_2)
expect(inheriting_1.find_matching_contexts(:offerings, :needs)).to_not include(inheriting_3)
expect(inheriting_1.find_matching_contexts(:offerings, :needs)).to_not include(inheriting_4)
expect(inheriting_1.find_matching_contexts(:offerings, :needs)).to_not include(taggable)
expect(inheriting_1.find_matching_contexts_for(TaggableModel, :offerings, :needs)).to include(inheriting_2)
expect(inheriting_1.find_matching_contexts_for(TaggableModel, :offerings, :needs)).to_not include(inheriting_3)
expect(inheriting_1.find_matching_contexts_for(TaggableModel, :offerings, :needs)).to_not include(inheriting_4)
expect(inheriting_1.find_matching_contexts_for(TaggableModel, :offerings, :needs)).to include(taggable)
end
it 'should not include the object itself in the list of related objects with tags of matching contexts' do
expect(inheriting_1.find_matching_contexts(:offerings, :needs)).to_not include(inheriting_1)
expect(inheriting_1.find_matching_contexts_for(InheritingTaggableModel, :offerings, :needs)).to_not include(inheriting_1)
expect(inheriting_1.find_matching_contexts_for(TaggableModel, :offerings, :needs)).to_not include(inheriting_1)
end
end
context 'find related tags' do
before do
inheriting_1.tag_list = 'one, two'
inheriting_1.save
inheriting_2.tag_list = 'three, four'
inheriting_2.save
inheriting_3.tag_list = 'one, four'
inheriting_3.save
taggable.tag_list = 'one, two, three, four'
taggable.save
end
it 'should find related objects based on tag names on context' do
expect(inheriting_1.find_related_tags).to include(inheriting_3)
expect(inheriting_1.find_related_tags).to_not include(inheriting_2)
expect(inheriting_1.find_related_tags).to_not include(taggable)
expect(inheriting_1.find_related_tags_for(TaggableModel)).to include(inheriting_3)
expect(inheriting_1.find_related_tags_for(TaggableModel)).to_not include(inheriting_2)
expect(inheriting_1.find_related_tags_for(TaggableModel)).to include(taggable)
end
it 'should not include the object itself in the list of related objects' do
expect(inheriting_1.find_related_tags).to_not include(inheriting_1)
expect(inheriting_1.find_related_tags_for(InheritingTaggableModel)).to_not include(inheriting_1)
expect(inheriting_1.find_related_tags_for(TaggableModel)).to_not include(inheriting_1)
end
end
describe 'tag list' do
before do
@inherited_same = InheritingTaggableModel.new(name: 'inherited same')
@inherited_different = AlteredInheritingTaggableModel.new(name: 'inherited different')
end
#TODO, shared example
it 'should be able to save tags for inherited models' do
inheriting_model.tag_list = 'bob, kelso'
inheriting_model.save
expect(InheritingTaggableModel.tagged_with('bob').first).to eq(inheriting_model)
end
it 'should find STI tagged models on the superclass' do
inheriting_model.tag_list = 'bob, kelso'
inheriting_model.save
expect(TaggableModel.tagged_with('bob').first).to eq(inheriting_model)
end
it 'should be able to add on contexts only to some subclasses' do
altered_inheriting.part_list = 'fork, spoon'
altered_inheriting.save
expect(InheritingTaggableModel.tagged_with('fork', on: :parts)).to be_empty
expect(AlteredInheritingTaggableModel.tagged_with('fork', on: :parts).first).to eq(altered_inheriting)
end
it 'should have different tag_counts_on for inherited models' do
inheriting_model.tag_list = 'bob, kelso'
inheriting_model.save!
altered_inheriting.tag_list = 'fork, spoon'
altered_inheriting.save!
expect(InheritingTaggableModel.tag_counts_on(:tags, order: "#{ActsAsTaggableOn.tags_table}.id").map(&:name)).to eq(%w(bob kelso))
expect(AlteredInheritingTaggableModel.tag_counts_on(:tags, order: "#{ActsAsTaggableOn.tags_table}.id").map(&:name)).to eq(%w(fork spoon))
expect(TaggableModel.tag_counts_on(:tags, order: "#{ActsAsTaggableOn.tags_table}.id").map(&:name)).to eq(%w(bob kelso fork spoon))
end
it 'should have different tags_on for inherited models' do
inheriting_model.tag_list = 'bob, kelso'
inheriting_model.save!
altered_inheriting.tag_list = 'fork, spoon'
altered_inheriting.save!
expect(InheritingTaggableModel.tags_on(:tags, order: "#{ActsAsTaggableOn.tags_table}.id").map(&:name)).to eq(%w(bob kelso))
expect(AlteredInheritingTaggableModel.tags_on(:tags, order: "#{ActsAsTaggableOn.tags_table}.id").map(&:name)).to eq(%w(fork spoon))
expect(TaggableModel.tags_on(:tags, order: "#{ActsAsTaggableOn.tags_table}.id").map(&:name)).to eq(%w(bob kelso fork spoon))
end
it 'should store same tag without validation conflict' do
taggable.tag_list = 'one'
taggable.save!
inheriting_model.tag_list = 'one'
inheriting_model.save!
inheriting_model.update! name: 'foo'
end
it "should only join with taggable's table to check type for inherited models" do
expect(TaggableModel.tag_counts_on(:tags).to_sql).to_not match /INNER JOIN taggable_models ON/
expect(InheritingTaggableModel.tag_counts_on(:tags).to_sql).to match /INNER JOIN taggable_models ON/
end
end
describe 'ownership' do
it 'should have taggings' do
student.tag(taggable, with: 'ruby,scheme', on: :tags)
expect(student.owned_taggings.count).to eq(2)
end
it 'should have tags' do
student.tag(taggable, with: 'ruby,scheme', on: :tags)
expect(student.owned_tags.count).to eq(2)
end
it 'should return tags for the inheriting tagger' do
student.tag(taggable, with: 'ruby, scheme', on: :tags)
expect(taggable.tags_from(student)).to eq(%w(ruby scheme))
end
it 'returns all owner tags on the taggable' do
student.tag(taggable, with: 'ruby, scheme', on: :tags)
student.tag(taggable, with: 'skill_one', on: :skills)
student.tag(taggable, with: 'english, spanish', on: :language)
expect(taggable.owner_tags(student).count).to eq(5)
expect(taggable.owner_tags(student).sort == %w(english ruby scheme skill_one spanish))
end
it 'returns owner tags on the tagger' do
student.tag(taggable, with: 'ruby, scheme', on: :tags)
expect(taggable.owner_tags_on(student, :tags).count).to eq(2)
end
it 'returns owner tags on the taggable for an array of contexts' do
student.tag(taggable, with: 'ruby, scheme', on: :tags)
student.tag(taggable, with: 'skill_one, skill_two', on: :skills)
expect(taggable.owner_tags_on(student, [:tags, :skills]).count).to eq(4)
expect(taggable.owner_tags_on(student, [:tags, :skills]).sort == %w(ruby scheme skill_one skill_two))
end
it 'should scope objects returned by tagged_with by owners' do
student.tag(taggable, with: 'ruby, scheme', on: :tags)
expect(TaggableModel.tagged_with(%w(ruby scheme), owned_by: student).count).to eq(1)
end
end
describe 'a subclass of Tag' do
let(:company) { Company.new(:name => 'Dewey, Cheatham & Howe') }
let(:user) { User.create! }
subject { Market.create! :name => 'finance' }
its(:type) { should eql 'Market' }
it 'sets STI type through string list' do
company.market_list = 'law, accounting'
company.save!
expect(Market.count).to eq(2)
end
it 'does not interfere with a normal Tag context on the same model' do
company.location_list = 'cambridge'
company.save!
expect(ActsAsTaggableOn::Tag.where(name: 'cambridge', type: nil)).to_not be_empty
end
it 'is returned with proper type through ownership' do
user.tag(company, :with => 'ripoffs, rackets', :on => :markets)
tags = company.owner_tags_on(user, :markets)
expect(tags.all? { |tag| tag.is_a? Market }).to be_truthy
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/acts_as_taggable_on/related_spec.rb | spec/acts_as_taggable_on/related_spec.rb | require 'spec_helper'
RSpec.describe 'Acts As Taggable On' do
describe 'Related Objects' do
#TODO, shared example
it 'should find related objects based on tag names on context' do
taggable1 = TaggableModel.create!(name: 'Taggable 1',tag_list: 'one, two')
taggable2 = TaggableModel.create!(name: 'Taggable 2',tag_list: 'three, four')
taggable3 = TaggableModel.create!(name: 'Taggable 3',tag_list: 'one, four')
expect(taggable1.find_related_tags).to include(taggable3)
expect(taggable1.find_related_tags).to_not include(taggable2)
end
it 'finds related tags for ordered taggable on' do
taggable1 = OrderedTaggableModel.create!(name: 'Taggable 1',colour_list: 'one, two')
taggable2 = OrderedTaggableModel.create!(name: 'Taggable 2',colour_list: 'three, four')
taggable3 = OrderedTaggableModel.create!(name: 'Taggable 3',colour_list: 'one, four')
expect(taggable1.find_related_colours).to include(taggable3)
expect(taggable1.find_related_colours).to_not include(taggable2)
end
it 'should find related objects based on tag names on context - non standard id' do
taggable1 = NonStandardIdTaggableModel.create!(name: 'Taggable 1',tag_list: 'one, two')
taggable2 = NonStandardIdTaggableModel.create!(name: 'Taggable 2',tag_list: 'three, four')
taggable3 = NonStandardIdTaggableModel.create!(name: 'Taggable 3',tag_list: 'one, four')
expect(taggable1.find_related_tags).to include(taggable3)
expect(taggable1.find_related_tags).to_not include(taggable2)
end
it 'should find other related objects based on tag names on context' do
taggable1 = TaggableModel.create!(name: 'Taggable 1',tag_list: 'one, two')
taggable2 = OtherTaggableModel.create!(name: 'Taggable 2',tag_list: 'three, four')
taggable3 = OtherTaggableModel.create!(name: 'Taggable 3',tag_list: 'one, four')
expect(taggable1.find_related_tags_for(OtherTaggableModel)).to include(taggable3)
expect(taggable1.find_related_tags_for(OtherTaggableModel)).to_not include(taggable2)
end
it 'should find other related objects based on tags only from particular context' do
taggable1 = TaggableModel.create!(name: 'Taggable 1',tag_list: 'one, two')
taggable2 = TaggableModel.create!(name: 'Taggable 2',tag_list: 'three, four', skill_list: 'one, two')
taggable3 = TaggableModel.create!(name: 'Taggable 3',tag_list: 'one, four')
expect(taggable1.find_related_tags).to include(taggable3)
expect(taggable1.find_related_tags).to_not include(taggable2)
end
shared_examples "a collection" do
it do
taggable1 = described_class.create!(name: 'Taggable 1', tag_list: 'one')
taggable2 = described_class.create!(name: 'Taggable 2', tag_list: 'one, two')
expect(taggable1.find_related_tags).to include(taggable2)
expect(taggable1.find_related_tags).to_not include(taggable1)
end
end
# it 'should not include the object itself in the list of related objects' do
describe TaggableModel do
it_behaves_like "a collection"
end
# it 'should not include the object itself in the list of related objects - non standard id' do
describe NonStandardIdTaggableModel do
it_behaves_like "a collection"
end
context 'Ignored Tags' do
let(:taggable1) { TaggableModel.create!(name: 'Taggable 1', tag_list: 'one, two, four') }
let(:taggable2) { TaggableModel.create!(name: 'Taggable 2', tag_list: 'two, three') }
let(:taggable3) { TaggableModel.create!(name: 'Taggable 3', tag_list: 'one, three') }
it 'should not include ignored tags in related search' do
expect(taggable1.find_related_tags(ignore: 'two')).to_not include(taggable2)
expect(taggable1.find_related_tags(ignore: 'two')).to include(taggable3)
end
it 'should accept array of ignored tags' do
taggable4 = TaggableModel.create!(name: 'Taggable 4', tag_list: 'four')
expect(taggable1.find_related_tags(ignore: ['two', 'four'])).to_not include(taggable2)
expect(taggable1.find_related_tags(ignore: ['two', 'four'])).to_not include(taggable4)
end
it 'should accept symbols as ignored tags' do
expect(taggable1.find_related_tags(ignore: :two)).to_not include(taggable2)
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/acts_as_taggable_on/utils_spec.rb | spec/acts_as_taggable_on/utils_spec.rb | require 'spec_helper'
RSpec.describe ActsAsTaggableOn::Utils do
describe '#like_operator' do
it 'should return \'ILIKE\' when the adapter is PostgreSQL' do
allow(ActsAsTaggableOn::Utils.connection).to receive(:adapter_name) { 'PostgreSQL' }
expect(ActsAsTaggableOn::Utils.like_operator).to eq('ILIKE')
end
it 'should return \'LIKE\' when the adapter is not PostgreSQL' do
allow(ActsAsTaggableOn::Utils.connection).to receive(:adapter_name) { 'MySQL' }
expect(ActsAsTaggableOn::Utils.like_operator).to eq('LIKE')
end
end
describe '#sha_prefix' do
it 'should return a consistent prefix for a given word' do
expect(ActsAsTaggableOn::Utils.sha_prefix('kittens')).to eq(ActsAsTaggableOn::Utils.sha_prefix('kittens'))
expect(ActsAsTaggableOn::Utils.sha_prefix('puppies')).not_to eq(ActsAsTaggableOn::Utils.sha_prefix('kittens'))
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/acts_as_taggable_on/tagging_spec.rb | spec/acts_as_taggable_on/tagging_spec.rb | require 'spec_helper'
RSpec.describe ActsAsTaggableOn::Tagging do
before(:each) do
@tagging = ActsAsTaggableOn::Tagging.new
end
it 'should not be valid with a invalid tag' do
@tagging.taggable = TaggableModel.create(name: 'Bob Jones')
@tagging.tag = ActsAsTaggableOn::Tag.new(name: '')
@tagging.context = 'tags'
expect(@tagging).to_not be_valid
expect(@tagging.errors[:tag_id]).to eq(['can\'t be blank'])
end
it 'should not create duplicate taggings' do
@taggable = TaggableModel.create(name: 'Bob Jones')
@tag = ActsAsTaggableOn::Tag.create(name: 'awesome')
expect {
2.times { ActsAsTaggableOn::Tagging.create(taggable: @taggable, tag: @tag, context: 'tags') }
}.to change(ActsAsTaggableOn::Tagging, :count).by(1)
end
it 'should not delete tags of other records' do
6.times { TaggableModel.create(name: 'Bob Jones', tag_list: 'very, serious, bug') }
expect(ActsAsTaggableOn::Tag.count).to eq(3)
taggable = TaggableModel.first
taggable.tag_list = 'bug'
taggable.save
expect(taggable.tag_list).to eq(['bug'])
another_taggable = TaggableModel.where('id != ?', taggable.id).sample
expect(another_taggable.tag_list.sort).to eq(%w(very serious bug).sort)
end
it 'should destroy unused tags after tagging destroyed' do
previous_setting = ActsAsTaggableOn.remove_unused_tags
ActsAsTaggableOn.remove_unused_tags = true
ActsAsTaggableOn::Tag.destroy_all
@taggable = TaggableModel.create(name: 'Bob Jones')
@taggable.update_attribute :tag_list, 'aaa,bbb,ccc'
@taggable.update_attribute :tag_list, ''
expect(ActsAsTaggableOn::Tag.count).to eql(0)
ActsAsTaggableOn.remove_unused_tags = previous_setting
end
it 'should destroy unused tags after tagging destroyed when not using tags_counter' do
remove_unused_tags_previous_setting = ActsAsTaggableOn.remove_unused_tags
tags_counter_previous_setting = ActsAsTaggableOn.tags_counter
ActsAsTaggableOn.remove_unused_tags = true
ActsAsTaggableOn.tags_counter = false
ActsAsTaggableOn::Tag.destroy_all
@taggable = TaggableModel.create(name: 'Bob Jones')
@taggable.update_attribute :tag_list, 'aaa,bbb,ccc'
@taggable.update_attribute :tag_list, ''
expect(ActsAsTaggableOn::Tag.count).to eql(0)
ActsAsTaggableOn.remove_unused_tags = remove_unused_tags_previous_setting
ActsAsTaggableOn.tags_counter = tags_counter_previous_setting
end
describe 'context scopes' do
before do
@tagging_2 = ActsAsTaggableOn::Tagging.new
@tagging_3 = ActsAsTaggableOn::Tagging.new
@tagger = User.new
@tagger_2 = User.new
@tagging.taggable = TaggableModel.create(name: "Black holes")
@tagging.tag = ActsAsTaggableOn::Tag.create(name: "Physics")
@tagging.tagger = @tagger
@tagging.context = 'Science'
@tagging.tenant = 'account1'
@tagging.save
@tagging_2.taggable = TaggableModel.create(name: "Satellites")
@tagging_2.tag = ActsAsTaggableOn::Tag.create(name: "Technology")
@tagging_2.tagger = @tagger_2
@tagging_2.context = 'Science'
@tagging_2.tenant = 'account1'
@tagging_2.save
@tagging_3.taggable = TaggableModel.create(name: "Satellites")
@tagging_3.tag = ActsAsTaggableOn::Tag.create(name: "Engineering")
@tagging_3.tagger = @tagger_2
@tagging_3.context = 'Astronomy'
@tagging_3.save
end
describe '.owned_by' do
it "should belong to a specific user" do
expect(ActsAsTaggableOn::Tagging.owned_by(@tagger).first).to eq(@tagging)
end
end
describe '.by_context' do
it "should be found by context" do
expect(ActsAsTaggableOn::Tagging.by_context('Science').length).to eq(2);
end
end
describe '.by_contexts' do
it "should find taggings by contexts" do
expect(ActsAsTaggableOn::Tagging.by_contexts(['Science', 'Astronomy']).first).to eq(@tagging);
expect(ActsAsTaggableOn::Tagging.by_contexts(['Science', 'Astronomy']).second).to eq(@tagging_2);
expect(ActsAsTaggableOn::Tagging.by_contexts(['Science', 'Astronomy']).third).to eq(@tagging_3);
expect(ActsAsTaggableOn::Tagging.by_contexts(['Science', 'Astronomy']).length).to eq(3);
end
end
describe '.by_tenant' do
it "should find taggings by tenant" do
expect(ActsAsTaggableOn::Tagging.by_tenant('account1').length).to eq(2);
expect(ActsAsTaggableOn::Tagging.by_tenant('account1').first).to eq(@tagging);
expect(ActsAsTaggableOn::Tagging.by_tenant('account1').second).to eq(@tagging_2);
end
end
describe '.not_owned' do
before do
@tagging_4 = ActsAsTaggableOn::Tagging.new
@tagging_4.taggable = TaggableModel.create(name: "Gravity")
@tagging_4.tag = ActsAsTaggableOn::Tag.create(name: "Space")
@tagging_4.context = "Science"
@tagging_4.save
end
it "should found the taggings that do not have owner" do
expect(ActsAsTaggableOn::Tagging.all.length).to eq(4)
expect(ActsAsTaggableOn::Tagging.not_owned.length).to eq(1)
expect(ActsAsTaggableOn::Tagging.not_owned.first).to eq(@tagging_4)
end
end
end
describe 'base_class' do
before do
class Foo < ActiveRecord::Base; end
end
context "default" do
it "inherits from ActiveRecord::Base" do
expect(ActsAsTaggableOn::Tagging.ancestors).to include(ActiveRecord::Base)
expect(ActsAsTaggableOn::Tagging.ancestors).to_not include(Foo)
end
end
context "custom" do
it "inherits from custom class" do
ActsAsTaggableOn.base_class = 'Foo'
hide_const("ActsAsTaggableOn::Tagging")
load("lib/acts-as-taggable-on/tagging.rb")
expect(ActsAsTaggableOn::Tagging.ancestors).to include(Foo)
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/acts_as_taggable_on/default_parser_spec.rb | spec/acts_as_taggable_on/default_parser_spec.rb | require 'spec_helper'
RSpec.describe ActsAsTaggableOn::DefaultParser do
it '#parse should return empty array if empty array is passed' do
parser = ActsAsTaggableOn::DefaultParser.new([])
expect(parser.parse).to be_empty
end
describe 'Multiple Delimiter' do
before do
@old_delimiter = ActsAsTaggableOn.delimiter
end
after do
ActsAsTaggableOn.delimiter = @old_delimiter
end
it 'should separate tags by delimiters' do
ActsAsTaggableOn.delimiter = [',', ' ', '\|']
parser = ActsAsTaggableOn::DefaultParser.new('cool, data|I have')
expect(parser.parse.to_s).to eq('cool, data, I, have')
end
it 'should escape quote' do
ActsAsTaggableOn.delimiter = [',', ' ', '\|']
parser = ActsAsTaggableOn::DefaultParser.new("'I have'|cool, data")
expect(parser.parse.to_s).to eq('"I have", cool, data')
parser = ActsAsTaggableOn::DefaultParser.new('"I, have"|cool, data')
expect(parser.parse.to_s).to eq('"I, have", cool, data')
end
it 'should work for utf8 delimiter and long delimiter' do
ActsAsTaggableOn.delimiter = [',', '的', '可能是']
parser = ActsAsTaggableOn::DefaultParser.new('我的东西可能是不见了,还好有备份')
expect(parser.parse.to_s).to eq('我, 东西, 不见了, 还好有备份')
end
it 'should work for multiple quoted tags' do
ActsAsTaggableOn.delimiter = [',']
parser = ActsAsTaggableOn::DefaultParser.new('"Ruby Monsters","eat Katzenzungen"')
expect(parser.parse.to_s).to eq('Ruby Monsters, eat Katzenzungen')
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/acts_as_taggable_on/tags_helper_spec.rb | spec/acts_as_taggable_on/tags_helper_spec.rb | require 'spec_helper'
RSpec.describe ActsAsTaggableOn::TagsHelper do
before(:each) do
@bob = TaggableModel.create(name: 'Bob Jones', language_list: 'ruby, php')
@tom = TaggableModel.create(name: 'Tom Marley', language_list: 'ruby, java')
@eve = TaggableModel.create(name: 'Eve Nodd', language_list: 'ruby, c++')
@helper =
class Helper
include ActsAsTaggableOn::TagsHelper
end.new
end
it 'should yield the proper css classes' do
tags = {}
@helper.tag_cloud(TaggableModel.tag_counts_on(:languages), %w(sucky awesome)) do |tag, css_class|
tags[tag.name] = css_class
end
expect(tags['ruby']).to eq('awesome')
expect(tags['java']).to eq('sucky')
expect(tags['c++']).to eq('sucky')
expect(tags['php']).to eq('sucky')
end
it 'should handle tags with zero counts (build for empty)' do
ActsAsTaggableOn::Tag.create(name: 'php')
ActsAsTaggableOn::Tag.create(name: 'java')
ActsAsTaggableOn::Tag.create(name: 'c++')
tags = {}
@helper.tag_cloud(ActsAsTaggableOn::Tag.all, %w(sucky awesome)) do |tag, css_class|
tags[tag.name] = css_class
end
expect(tags['java']).to eq('sucky')
expect(tags['c++']).to eq('sucky')
expect(tags['php']).to eq('sucky')
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/acts_as_taggable_on/acts_as_tagger_spec.rb | spec/acts_as_taggable_on/acts_as_tagger_spec.rb | require 'spec_helper'
RSpec.describe 'acts_as_tagger' do
describe 'Tagger Method Generation' do
before(:each) do
@tagger = User.new
end
it 'should add #is_tagger? query method to the class-side' do
expect(User).to respond_to(:is_tagger?)
end
it 'should return true from the class-side #is_tagger?' do
expect(User.is_tagger?).to be_truthy
end
it 'should return false from the base #is_tagger?' do
expect(ActiveRecord::Base.is_tagger?).to be_falsy
end
it 'should add #is_tagger? query method to the singleton' do
expect(@tagger).to respond_to(:is_tagger?)
end
it 'should add #tag method on the instance-side' do
expect(@tagger).to respond_to(:tag)
end
it 'should generate an association for #owned_taggings and #owned_tags' do
expect(@tagger).to respond_to(:owned_taggings, :owned_tags)
end
end
describe '#tag' do
context 'when called with a non-existent tag context' do
before(:each) do
@tagger = User.new
@taggable = TaggableModel.new(name: 'Richard Prior')
end
it 'should by default not throw an exception ' do
expect(@taggable.tag_list_on(:foo)).to be_empty
expect(-> {
@tagger.tag(@taggable, with: 'this, and, that', on: :foo)
}).to_not raise_error
end
it 'should by default create the tag context on-the-fly' do
expect(@taggable.tag_list_on(:here_ond_now)).to be_empty
@tagger.tag(@taggable, with: 'that', on: :here_ond_now)
expect(@taggable.tag_list_on(:here_ond_now)).to_not include('that')
expect(@taggable.all_tags_list_on(:here_ond_now)).to include('that')
end
it 'should show all the tag list when both public and owned tags exist' do
@taggable.tag_list = 'ruby, python'
@tagger.tag(@taggable, with: 'java, lisp', on: :tags)
expect(@taggable.all_tags_on(:tags).map(&:name).sort).to eq(%w(ruby python java lisp).sort)
end
it 'should not add owned tags to the common list' do
@taggable.tag_list = 'ruby, python'
@tagger.tag(@taggable, with: 'java, lisp', on: :tags)
expect(@taggable.tag_list).to eq(%w(ruby python))
@tagger.tag(@taggable, with: '', on: :tags)
expect(@taggable.tag_list).to eq(%w(ruby python))
end
it 'should throw an exception when the default is over-ridden' do
expect(@taggable.tag_list_on(:foo_boo)).to be_empty
expect {
@tagger.tag(@taggable, with: 'this, and, that', on: :foo_boo, force: false)
}.to raise_error(RuntimeError)
end
it 'should not create the tag context on-the-fly when the default is over-ridden' do
expect(@taggable.tag_list_on(:foo_boo)).to be_empty
@tagger.tag(@taggable, with: 'this, and, that', on: :foo_boo, force: false) rescue
expect(@taggable.tag_list_on(:foo_boo)).to be_empty
end
end
describe "when called by multiple tagger's" do
before(:each) do
@user_x = User.create(name: 'User X')
@user_y = User.create(name: 'User Y')
@taggable = TaggableModel.create(name: 'acts_as_taggable_on', tag_list: 'plugin')
@user_x.tag(@taggable, with: 'ruby, rails', on: :tags)
@user_y.tag(@taggable, with: 'ruby, plugin', on: :tags)
@user_y.tag(@taggable, with: '', on: :tags)
@user_y.tag(@taggable, with: '', on: :tags)
end
it 'should delete owned tags' do
expect(@user_y.owned_tags).to be_empty
end
it 'should not delete other taggers tags' do
expect(@user_x.owned_tags.count).to eq(2)
end
it 'should not delete original tags' do
expect(@taggable.all_tags_list_on(:tags)).to include('plugin')
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/acts_as_taggable_on/generic_parser_spec.rb | spec/acts_as_taggable_on/generic_parser_spec.rb | require 'spec_helper'
RSpec.describe ActsAsTaggableOn::GenericParser do
it '#parse should return empty array if empty tag string is passed' do
tag_list = ActsAsTaggableOn::GenericParser.new('')
expect(tag_list.parse).to be_empty
end
it '#parse should separate tags by comma' do
tag_list = ActsAsTaggableOn::GenericParser.new('cool,data,,I,have')
expect(tag_list.parse).to eq(%w(cool data I have))
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/acts_as_taggable_on/dirty_spec.rb | spec/acts_as_taggable_on/dirty_spec.rb | require 'spec_helper'
RSpec.describe 'Dirty behavior of taggable objects' do
context 'with un-contexted tags' do
before(:each) do
@taggable = TaggableModel.create(tag_list: 'awesome, epic')
end
context 'when tag_list changed' do
before(:each) do
expect(@taggable.changes).to be_empty
@taggable.tag_list = 'one'
end
it 'should show changes of dirty object' do
expect(@taggable.changes).to eq({'tag_list' => [['awesome', 'epic'], ['one']]})
end
it 'should show changes of freshly initialized dirty object' do
taggable = TaggableModel.find(@taggable.id)
taggable.tag_list = 'one'
expect(taggable.changes).to eq({'tag_list' => [['awesome', 'epic'], ['one']]})
end
if Rails.version >= "5.1"
it 'flags tag_list as changed' do
expect(@taggable.will_save_change_to_tag_list?).to be_truthy
end
end
it 'preserves original value' do
expect(@taggable.tag_list_was).to eq(['awesome', 'epic'])
end
it 'shows what the change was' do
expect(@taggable.tag_list_change).to eq([['awesome', 'epic'], ['one']])
end
context 'without order' do
it 'should not mark attribute if order change ' do
taggable = TaggableModel.create(name: 'Dirty Harry', tag_list: %w(d c b a))
taggable.tag_list = %w(a b c d)
expect(taggable.tag_list_changed?).to be_falsey
end
end
context 'with order' do
it 'should mark attribute if order change' do
taggable = OrderedTaggableModel.create(name: 'Clean Harry', tag_list: 'd,c,b,a')
taggable.save
taggable.tag_list = %w(a b c d)
expect(taggable.tag_list_changed?).to be_truthy
end
end
end
context 'when tag_list is the same' do
before(:each) do
@taggable.tag_list = 'awesome, epic'
end
it 'is not flagged as changed' do
expect(@taggable.tag_list_changed?).to be_falsy
end
it 'does not show any changes to the taggable item' do
expect(@taggable.changes).to be_empty
end
context "and using a delimiter different from a ','" do
before do
@old_delimiter = ActsAsTaggableOn.delimiter
ActsAsTaggableOn.delimiter = ';'
end
after do
ActsAsTaggableOn.delimiter = @old_delimiter
end
it 'does not show any changes to the taggable item when using array assignments' do
@taggable.tag_list = %w(awesome epic)
expect(@taggable.changes).to be_empty
end
end
end
end
context 'with context tags' do
before(:each) do
@taggable = TaggableModel.create('language_list' => 'awesome, epic')
end
context 'when language_list changed' do
before(:each) do
expect(@taggable.changes).to be_empty
@taggable.language_list = 'one'
end
it 'should show changes of dirty object' do
expect(@taggable.changes).to eq({'language_list' => [['awesome', 'epic'], ['one']]})
end
it 'flags language_list as changed' do
expect(@taggable.language_list_changed?).to be_truthy
end
it 'preserves original value' do
expect(@taggable.language_list_was).to eq(['awesome', 'epic'])
end
it 'shows what the change was' do
expect(@taggable.language_list_change).to eq([['awesome', 'epic'], ['one']])
end
end
context 'when language_list is the same' do
before(:each) do
@taggable.language_list = 'awesome, epic'
end
it 'is not flagged as changed' do
expect(@taggable.language_list_changed?).to be_falsy
end
it 'does not show any changes to the taggable item' do
expect(@taggable.changes).to be_empty
end
end
context 'when language_list changed by association' do
let(:tag) { ActsAsTaggableOn::Tag.new(name: 'one') }
it 'flags language_list as changed' do
expect(@taggable.changes).to be_empty
@taggable.languages << tag
expect(@taggable.language_list_changed?).to be_truthy
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/acts_as_taggable_on/tag_spec.rb | spec/acts_as_taggable_on/tag_spec.rb | require 'spec_helper'
require 'db/migrate/2_add_missing_unique_indices.rb'
RSpec.shared_examples_for 'without unique index' do
prepend_before(:all) { AddMissingUniqueIndices.down }
append_after(:all) do
ActsAsTaggableOn::Tag.delete_all
AddMissingUniqueIndices.up
end
end
RSpec.describe ActsAsTaggableOn::Tag do
before(:each) do
@tag = ActsAsTaggableOn::Tag.new
@user = TaggableModel.create(name: 'Pablo', tenant_id: 100)
end
describe 'named like any' do
context 'case insensitive collation and unique index on tag name', if: using_case_insensitive_collation? do
before(:each) do
ActsAsTaggableOn::Tag.create(name: 'Awesome')
ActsAsTaggableOn::Tag.create(name: 'epic')
end
it 'should find both tags' do
expect(ActsAsTaggableOn::Tag.named_like_any(%w(awesome epic)).count).to eq(2)
end
end
context 'case insensitive collation without indexes or case sensitive collation with indexes' do
if using_case_insensitive_collation?
include_context 'without unique index'
end
before(:each) do
ActsAsTaggableOn::Tag.create(name: 'Awesome')
ActsAsTaggableOn::Tag.create(name: 'awesome')
ActsAsTaggableOn::Tag.create(name: 'epic')
end
it 'should find both tags' do
expect(ActsAsTaggableOn::Tag.named_like_any(%w(awesome epic)).count).to eq(3)
end
end
end
describe 'named any' do
context 'with some special characters combinations', if: using_mysql? do
it 'should not raise an invalid encoding exception' do
expect{ActsAsTaggableOn::Tag.named_any(["holä", "hol'ä"])}.not_to raise_error
end
end
end
describe 'for context' do
before(:each) do
@user.skill_list.add('ruby')
@user.save
end
it 'should return tags that have been used in the given context' do
expect(ActsAsTaggableOn::Tag.for_context('skills').pluck(:name)).to include('ruby')
end
it 'should not return tags that have been used in other contexts' do
expect(ActsAsTaggableOn::Tag.for_context('needs').pluck(:name)).to_not include('ruby')
end
end
describe 'for tenant' do
before(:each) do
@user.skill_list.add('ruby')
@user.save
end
it 'should return tags for the tenant' do
expect(ActsAsTaggableOn::Tag.for_tenant('100').pluck(:name)).to include('ruby')
end
it 'should not return tags for other tenants' do
expect(ActsAsTaggableOn::Tag.for_tenant('200').pluck(:name)).to_not include('ruby')
end
end
describe 'find or create by name' do
before(:each) do
@tag.name = 'awesome'
@tag.save
end
it 'should find by name' do
expect(ActsAsTaggableOn::Tag.find_or_create_with_like_by_name('awesome')).to eq(@tag)
end
it 'should find by name case insensitive' do
expect(ActsAsTaggableOn::Tag.find_or_create_with_like_by_name('AWESOME')).to eq(@tag)
end
it 'should create by name' do
expect {
ActsAsTaggableOn::Tag.find_or_create_with_like_by_name('epic')
}.to change(ActsAsTaggableOn::Tag, :count).by(1)
end
end
describe 'find or create by unicode name', unless: using_sqlite? do
before(:each) do
@tag.name = 'привет'
@tag.save
end
it 'should find by name' do
expect(ActsAsTaggableOn::Tag.find_or_create_with_like_by_name('привет')).to eq(@tag)
end
it 'should find by name case insensitive' do
expect(ActsAsTaggableOn::Tag.find_or_create_with_like_by_name('ПРИВЕТ')).to eq(@tag)
end
it 'should find by name accent insensitive', if: using_case_insensitive_collation? do
@tag.name = 'inupiat'
@tag.save
expect(ActsAsTaggableOn::Tag.find_or_create_with_like_by_name('Iñupiat')).to eq(@tag)
end
end
describe 'find or create all by any name' do
before(:each) do
@tag.name = 'awesome'
@tag.save
end
it 'should find by name' do
expect(ActsAsTaggableOn::Tag.find_or_create_all_with_like_by_name('awesome')).to eq([@tag])
end
it 'should find by name case insensitive' do
expect(ActsAsTaggableOn::Tag.find_or_create_all_with_like_by_name('AWESOME')).to eq([@tag])
end
context 'case sensitive' do
if using_case_insensitive_collation?
include_context 'without unique index'
end
it 'should find by name case sensitive' do
ActsAsTaggableOn.strict_case_match = true
expect {
ActsAsTaggableOn::Tag.find_or_create_all_with_like_by_name('AWESOME')
}.to change(ActsAsTaggableOn::Tag, :count).by(1)
end
end
it 'should create by name' do
expect {
ActsAsTaggableOn::Tag.find_or_create_all_with_like_by_name('epic')
}.to change(ActsAsTaggableOn::Tag, :count).by(1)
end
context 'case sensitive' do
if using_case_insensitive_collation?
include_context 'without unique index'
end
it 'should find or create by name case sensitive' do
ActsAsTaggableOn.strict_case_match = true
expect {
expect(ActsAsTaggableOn::Tag.find_or_create_all_with_like_by_name('AWESOME', 'awesome').map(&:name)).to eq(%w(AWESOME awesome))
}.to change(ActsAsTaggableOn::Tag, :count).by(1)
end
end
it 'should find or create by name' do
expect {
expect(ActsAsTaggableOn::Tag.find_or_create_all_with_like_by_name('awesome', 'epic').map(&:name)).to eq(%w(awesome epic))
}.to change(ActsAsTaggableOn::Tag, :count).by(1)
end
it 'should return an empty array if no tags are specified' do
expect(ActsAsTaggableOn::Tag.find_or_create_all_with_like_by_name([])).to be_empty
end
context 'another tag is created concurrently', :database_cleaner_delete, if: supports_concurrency? do
it 'retries and finds tag if tag with same name created concurrently' do
tag_name = 'super'
expect(ActsAsTaggableOn::Tag).to receive(:create).with(name: tag_name) do
# Simulate concurrent tag creation
Thread.new do
ActsAsTaggableOn::Tag.new(name: tag_name).save!
end.join
raise ActiveRecord::RecordNotUnique
end
expect {
ActsAsTaggableOn::Tag.find_or_create_all_with_like_by_name(tag_name)
}.to change(ActsAsTaggableOn::Tag, :count).by(1)
end
end
end
it 'should require a name' do
@tag.valid?
#TODO, we should find another way to check this
expect(@tag.errors[:name]).to eq(["can't be blank"])
@tag.name = 'something'
@tag.valid?
expect(@tag.errors[:name]).to be_empty
end
it 'should limit the name length to 255 or less characters' do
@tag.name = 'fgkgnkkgjymkypbuozmwwghblmzpqfsgjasflblywhgkwndnkzeifalfcpeaeqychjuuowlacmuidnnrkprgpcpybarbkrmziqihcrxirlokhnzfvmtzixgvhlxzncyywficpraxfnjptxxhkqmvicbcdcynkjvziefqzyndxkjmsjlvyvbwraklbalykyxoliqdlreeykuphdtmzfdwpphmrqvwvqffojkqhlzvinqajsxbszyvrqqyzusxranr'
@tag.valid?
#TODO, we should find another way to check this
expect(@tag.errors[:name]).to eq(['is too long (maximum is 255 characters)'])
@tag.name = 'fgkgnkkgjymkypbuozmwwghblmzpqfsgjasflblywhgkwndnkzeifalfcpeaeqychjuuowlacmuidnnrkprgpcpybarbkrmziqihcrxirlokhnzfvmtzixgvhlxzncyywficpraxfnjptxxhkqmvicbcdcynkjvziefqzyndxkjmsjlvyvbwraklbalykyxoliqdlreeykuphdtmzfdwpphmrqvwvqffojkqhlzvinqajsxbszyvrqqyzusxran'
@tag.valid?
expect(@tag.errors[:name]).to be_empty
end
it 'should equal a tag with the same name' do
@tag.name = 'awesome'
new_tag = ActsAsTaggableOn::Tag.new(name: 'awesome')
expect(new_tag).to eq(@tag)
end
it 'should return its name when to_s is called' do
@tag.name = 'cool'
expect(@tag.to_s).to eq('cool')
end
it 'have named_scope named(something)' do
@tag.name = 'cool'
@tag.save!
expect(ActsAsTaggableOn::Tag.named('cool')).to include(@tag)
end
it 'have named_scope named_like(something)' do
@tag.name = 'cool'
@tag.save!
@another_tag = ActsAsTaggableOn::Tag.create!(name: 'coolip')
expect(ActsAsTaggableOn::Tag.named_like('cool')).to include(@tag, @another_tag)
end
describe 'escape wildcard symbols in like requests' do
before(:each) do
@tag.name = 'cool'
@tag.save
@another_tag = ActsAsTaggableOn::Tag.create!(name: 'coo%')
@another_tag2 = ActsAsTaggableOn::Tag.create!(name: 'coolish')
end
it "return escaped result when '%' char present in tag" do
expect(ActsAsTaggableOn::Tag.named_like('coo%')).to_not include(@tag)
expect(ActsAsTaggableOn::Tag.named_like('coo%')).to include(@another_tag)
end
end
describe 'when using strict_case_match' do
before do
ActsAsTaggableOn.strict_case_match = true
@tag.name = 'awesome'
@tag.save!
end
after do
ActsAsTaggableOn.strict_case_match = false
end
it 'should find by name' do
expect(ActsAsTaggableOn::Tag.find_or_create_with_like_by_name('awesome')).to eq(@tag)
end
context 'case sensitive' do
if using_case_insensitive_collation?
include_context 'without unique index'
end
it 'should find by name case sensitively' do
expect {
ActsAsTaggableOn::Tag.find_or_create_with_like_by_name('AWESOME')
}.to change(ActsAsTaggableOn::Tag, :count)
expect(ActsAsTaggableOn::Tag.last.name).to eq('AWESOME')
end
end
context 'case sensitive' do
if using_case_insensitive_collation?
include_context 'without unique index'
end
it 'should have a named_scope named(something) that matches exactly' do
uppercase_tag = ActsAsTaggableOn::Tag.create(name: 'Cool')
@tag.name = 'cool'
@tag.save!
expect(ActsAsTaggableOn::Tag.named('cool')).to include(@tag)
expect(ActsAsTaggableOn::Tag.named('cool')).to_not include(uppercase_tag)
end
end
it 'should not change encoding' do
name = "\u3042"
original_encoding = name.encoding
record = ActsAsTaggableOn::Tag.find_or_create_with_like_by_name(name)
record.reload
expect(record.name.encoding).to eq(original_encoding)
end
context 'named any with some special characters combinations', if: using_mysql? do
it 'should not raise an invalid encoding exception' do
expect{ActsAsTaggableOn::Tag.named_any(["holä", "hol'ä"])}.not_to raise_error
end
end
end
describe 'name uniqeness validation' do
let(:duplicate_tag) { ActsAsTaggableOn::Tag.new(name: 'ror') }
before { ActsAsTaggableOn::Tag.create(name: 'ror') }
context "when don't need unique names" do
include_context 'without unique index'
it 'should not run uniqueness validation' do
allow(duplicate_tag).to receive(:validates_name_uniqueness?) { false }
duplicate_tag.save
expect(duplicate_tag).to be_persisted
end
end
context 'when do need unique names' do
it 'should run uniqueness validation' do
expect(duplicate_tag).to_not be_valid
end
it 'add error to name' do
duplicate_tag.save
expect(duplicate_tag.errors.size).to eq(1)
expect(duplicate_tag.errors.messages[:name]).to include('has already been taken')
end
end
end
describe 'popular tags' do
before do
%w(sports rails linux tennis golden_syrup).each_with_index do |t, i|
tag = ActsAsTaggableOn::Tag.new(name: t)
tag.taggings_count = i
tag.save!
end
end
it 'should find the most popular tags' do
expect(ActsAsTaggableOn::Tag.most_used(3).first.name).to eq("golden_syrup")
expect(ActsAsTaggableOn::Tag.most_used(3).length).to eq(3)
end
it 'should find the least popular tags' do
expect(ActsAsTaggableOn::Tag.least_used(3).first.name).to eq("sports")
expect(ActsAsTaggableOn::Tag.least_used(3).length).to eq(3)
end
end
describe 'base_class' do
before do
class Foo < ActiveRecord::Base; end
end
context "default" do
it "inherits from ActiveRecord::Base" do
expect(ActsAsTaggableOn::Tag.ancestors).to include(ActiveRecord::Base)
expect(ActsAsTaggableOn::Tag.ancestors).to_not include(Foo)
end
end
context "custom" do
it "inherits from custom class" do
ActsAsTaggableOn.base_class = 'Foo'
hide_const("ActsAsTaggableOn::Tag")
load("lib/acts-as-taggable-on/tag.rb")
expect(ActsAsTaggableOn::Tag.ancestors).to include(Foo)
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/acts_as_taggable_on/taggable_spec.rb | spec/acts_as_taggable_on/taggable_spec.rb | require 'spec_helper'
RSpec.describe 'Taggable To Preserve Order' do
before(:each) do
@taggable = OrderedTaggableModel.new(name: 'Bob Jones')
end
it 'should have tag associations' do
[:tags, :colours].each do |type|
expect(@taggable.respond_to?(type)).to be_truthy
expect(@taggable.respond_to?("#{type.to_s.singularize}_taggings")).to be_truthy
end
end
it 'should have tag methods' do
[:tags, :colours].each do |type|
expect(@taggable.respond_to?("#{type.to_s.singularize}_list")).to be_truthy
expect(@taggable.respond_to?("#{type.to_s.singularize}_list=")).to be_truthy
expect(@taggable.respond_to?("all_#{type}_list")).to be_truthy
end
end
it 'should return tag list in the order the tags were created' do
# create
@taggable.tag_list = 'rails, ruby, css'
expect(@taggable.instance_variable_get('@tag_list').instance_of?(ActsAsTaggableOn::TagList)).to be_truthy
expect{
@taggable.save
}.to change(ActsAsTaggableOn::Tag, :count).by(3)
@taggable.reload
expect(@taggable.tag_list).to eq(%w(rails ruby css))
# update
@taggable.tag_list = 'pow, ruby, rails'
@taggable.save
@taggable.reload
expect(@taggable.tag_list).to eq(%w(pow ruby rails))
# update with no change
@taggable.tag_list = 'pow, ruby, rails'
@taggable.save
@taggable.reload
expect(@taggable.tag_list).to eq(%w(pow ruby rails))
# update to clear tags
@taggable.tag_list = ''
@taggable.save
@taggable.reload
expect(@taggable.tag_list).to be_empty
end
it 'should return tag objects in the order the tags were created' do
# create
@taggable.tag_list = 'pow, ruby, rails'
expect(@taggable.instance_variable_get('@tag_list').instance_of?(ActsAsTaggableOn::TagList)).to be_truthy
expect {
@taggable.save
}.to change(ActsAsTaggableOn::Tag, :count).by(3)
@taggable.reload
expect(@taggable.tags.map { |t| t.name }).to eq(%w(pow ruby rails))
# update
@taggable.tag_list = 'rails, ruby, css, pow'
@taggable.save
@taggable.reload
expect(@taggable.tags.map { |t| t.name }).to eq(%w(rails ruby css pow))
end
it 'should return tag objects in tagging id order' do
# create
@taggable.tag_list = 'pow, ruby, rails'
@taggable.save
@taggable.reload
ids = @taggable.tags.map { |t| t.taggings.first.id }
expect(ids).to eq(ids.sort)
# update
@taggable.tag_list = 'rails, ruby, css, pow'
@taggable.save
@taggable.reload
ids = @taggable.tags.map { |t| t.taggings.first.id }
expect(ids).to eq(ids.sort)
end
end
RSpec.describe 'Taggable' do
before(:each) do
@taggable = TaggableModel.new(name: 'Bob Jones')
@taggables = [@taggable, TaggableModel.new(name: 'John Doe')]
end
it 'should have tag types' do
[:tags, :languages, :skills, :needs, :offerings].each do |type|
expect(TaggableModel.tag_types).to include type
end
expect(@taggable.tag_types).to eq(TaggableModel.tag_types)
end
it 'should have tenant column' do
expect(TaggableModel.tenant_column).to eq(:tenant_id)
end
it 'should have tag_counts_on' do
expect(TaggableModel.tag_counts_on(:tags)).to be_empty
@taggable.tag_list = %w(awesome epic)
@taggable.save
expect(TaggableModel.tag_counts_on(:tags).length).to eq(2)
expect(@taggable.tag_counts_on(:tags).length).to eq(2)
end
context 'tag_counts on a collection' do
context 'a select clause is specified on the collection' do
it 'should return tag counts without raising an error' do
expect(TaggableModel.tag_counts_on(:tags)).to be_empty
@taggable.tag_list = %w(awesome epic)
@taggable.save
expect {
expect(TaggableModel.select(:name).tag_counts_on(:tags).length).to eq(2)
}.not_to raise_error
end
end
end
it 'should have tags_on' do
expect(TaggableModel.tags_on(:tags)).to be_empty
@taggable.tag_list = %w(awesome epic)
@taggable.save
expect(TaggableModel.tags_on(:tags).length).to eq(2)
expect(@taggable.tags_on(:tags).length).to eq(2)
end
it 'should return [] right after create' do
blank_taggable = TaggableModel.new(name: 'Bob Jones')
expect(blank_taggable.tag_list).to be_empty
end
it 'should be able to create tags' do
@taggable.skill_list = 'ruby, rails, css'
expect(@taggable.instance_variable_get('@skill_list').instance_of?(ActsAsTaggableOn::TagList)).to be_truthy
expect{
@taggable.save
}.to change(ActsAsTaggableOn::Tag, :count).by(3)
@taggable.reload
expect(@taggable.skill_list.sort).to eq(%w(ruby rails css).sort)
end
it 'should be able to create tags through the tag list directly' do
@taggable.tag_list_on(:test).add('hello')
expect(@taggable.tag_list_cache_on(:test)).to_not be_empty
expect(@taggable.tag_list_on(:test)).to eq(['hello'])
@taggable.save
@taggable.save_tags
@taggable.reload
expect(@taggable.tag_list_on(:test)).to eq(['hello'])
end
it 'should differentiate between contexts' do
@taggable.skill_list = 'ruby, rails, css'
@taggable.tag_list = 'ruby, bob, charlie'
@taggable.save
@taggable.reload
expect(@taggable.skill_list).to include('ruby')
expect(@taggable.skill_list).to_not include('bob')
end
it 'should be able to remove tags through list alone' do
@taggable.skill_list = 'ruby, rails, css'
@taggable.save
@taggable.reload
expect(@taggable.skills.count).to eq(3)
@taggable.skill_list = 'ruby, rails'
@taggable.save
@taggable.reload
expect(@taggable.skills.count).to eq(2)
end
it 'should be able to select taggables by subset of tags using ActiveRelation methods' do
@taggables[0].tag_list = 'bob'
@taggables[1].tag_list = 'charlie'
@taggables[0].skill_list = 'ruby'
@taggables[1].skill_list = 'css'
@taggables.each { |taggable| taggable.save }
@found_taggables_by_tag = TaggableModel.joins(:tags).where(ActsAsTaggableOn.tags_table => {name: ['bob']})
@found_taggables_by_skill = TaggableModel.joins(:skills).where(ActsAsTaggableOn.tags_table => {name: ['ruby']})
expect(@found_taggables_by_tag).to include @taggables[0]
expect(@found_taggables_by_tag).to_not include @taggables[1]
expect(@found_taggables_by_skill).to include @taggables[0]
expect(@found_taggables_by_skill).to_not include @taggables[1]
end
it 'should be able to find by tag' do
@taggable.skill_list = 'ruby, rails, css'
@taggable.save
expect(TaggableModel.tagged_with('ruby').first).to eq(@taggable)
end
it 'should be able to get a count with find by tag when using a group by' do
@taggable.skill_list = 'ruby'
@taggable.save
expect(TaggableModel.tagged_with('ruby').group(:created_at).count.count).to eq(1)
end
it 'can be used as scope' do
@taggable.skill_list = 'ruby'
@taggable.save
untaggable_model = @taggable.untaggable_models.create!(name:'foobar')
scope_tag = TaggableModel.tagged_with('ruby', any: 'distinct', order: 'taggable_models.name asc')
expect(UntaggableModel.joins(:taggable_model).merge(scope_tag).except(:select)).to eq([untaggable_model])
end
it "shouldn't generate a query with DISTINCT by default" do
@taggable.skill_list = 'ruby, rails, css'
@taggable.save
expect(TaggableModel.tagged_with('ruby').to_sql).to_not match /DISTINCT/
end
it "should be able to find a tag using dates" do
@taggable.skill_list = "ruby"
@taggable.save
today = Date.today.to_time.utc
tomorrow = Date.tomorrow.to_time.utc
expect(TaggableModel.tagged_with("ruby", :start_at => today, :end_at => tomorrow).count).to eq(1)
end
it "shouldn't be able to find a tag outside date range" do
@taggable.skill_list = "ruby"
@taggable.save
expect(TaggableModel.tagged_with("ruby", :start_at => Date.today - 2.days, :end_at => Date.today - 1.day).count).to eq(0)
end
it 'should be able to find by tag with context' do
@taggable.skill_list = 'ruby, rails, css, julia'
@taggable.tag_list = 'bob, charlie, julia'
@taggable.save
expect(TaggableModel.tagged_with('ruby').first).to eq(@taggable)
expect(TaggableModel.tagged_with('ruby, css').first).to eq(@taggable)
expect(TaggableModel.tagged_with('bob', on: :skills).first).to_not eq(@taggable)
expect(TaggableModel.tagged_with('bob', on: :tags).first).to eq(@taggable)
expect(TaggableModel.tagged_with('julia', on: :skills).size).to eq(1)
expect(TaggableModel.tagged_with('julia', on: :tags).size).to eq(1)
expect(TaggableModel.tagged_with('julia', on: nil).size).to eq(2)
end
it 'should not care about case' do
TaggableModel.create(name: 'Bob', tag_list: 'ruby')
TaggableModel.create(name: 'Frank', tag_list: 'Ruby')
expect(ActsAsTaggableOn::Tag.all.size).to eq(1)
expect(TaggableModel.tagged_with('ruby').to_a).to eq(TaggableModel.tagged_with('Ruby').to_a)
end
it 'should be able to find by tags with other joins in the query' do
@taggable.skill_list = 'ruby, rails, css'
@taggable.tag_list = 'bob, charlie'
@taggable.save
expect(TaggableModel.tagged_with(['bob', 'css'], :any => true).to_a).to eq([@taggable])
bob = TaggableModel.create(:name => 'Bob', :tag_list => 'ruby, rails, css')
frank = TaggableModel.create(:name => 'Frank', :tag_list => 'ruby, rails')
charlie = TaggableModel.create(:name => 'Charlie', :skill_list => 'ruby, java')
# Test for explicit distinct in select
bob.untaggable_models.create!
frank.untaggable_models.create!
charlie.untaggable_models.create!
expect(TaggableModel.select('distinct(taggable_models.id), taggable_models.*').joins(:untaggable_models).tagged_with(['css', 'java'], :any => true).to_a.sort).to eq([bob, charlie].sort)
expect(TaggableModel.select('distinct(taggable_models.id), taggable_models.*').joins(:untaggable_models).tagged_with(['rails', 'ruby'], :any => false).to_a.sort).to eq([bob, frank].sort)
end
it 'should not care about case for unicode names', unless: using_sqlite? do
ActsAsTaggableOn.strict_case_match = false
TaggableModel.create(name: 'Anya', tag_list: 'ПРИВЕТ')
TaggableModel.create(name: 'Igor', tag_list: 'привет')
TaggableModel.create(name: 'Katia', tag_list: 'ПРИВЕТ')
expect(ActsAsTaggableOn::Tag.all.size).to eq(1)
expect(TaggableModel.tagged_with('привет').to_a).to eq(TaggableModel.tagged_with('ПРИВЕТ').to_a)
end
context 'should be able to create and find tags in languages without capitalization :' do
ActsAsTaggableOn.strict_case_match = false
{
japanese: {name: 'Chihiro', tag_list: '日本の'},
hebrew: {name: 'Salim', tag_list: 'עברית'},
chinese: {name: 'Ieie', tag_list: '中国的'},
arabic: {name: 'Yasser', tag_list: 'العربية'},
emo: {name: 'Emo', tag_list: '✏'}
}.each do |language, values|
it language do
TaggableModel.create(values)
expect(TaggableModel.tagged_with(values[:tag_list]).count).to eq(1)
end
end
end
it 'should be able to get tag counts on model as a whole' do
TaggableModel.create(name: 'Bob', tag_list: 'ruby, rails, css')
TaggableModel.create(name: 'Frank', tag_list: 'ruby, rails')
TaggableModel.create(name: 'Charlie', skill_list: 'ruby')
expect(TaggableModel.tag_counts).to_not be_empty
expect(TaggableModel.skill_counts).to_not be_empty
end
it 'should be able to get all tag counts on model as whole' do
TaggableModel.create(name: 'Bob', tag_list: 'ruby, rails, css')
TaggableModel.create(name: 'Frank', tag_list: 'ruby, rails')
TaggableModel.create(name: 'Charlie', skill_list: 'ruby')
expect(TaggableModel.all_tag_counts).to_not be_empty
expect(TaggableModel.all_tag_counts(order: "#{ActsAsTaggableOn.tags_table}.id").first.count).to eq(3) # ruby
end
it 'should be able to get all tags on model as whole' do
TaggableModel.create(name: 'Bob', tag_list: 'ruby, rails, css')
TaggableModel.create(name: 'Frank', tag_list: 'ruby, rails')
TaggableModel.create(name: 'Charlie', skill_list: 'ruby')
expect(TaggableModel.all_tags).to_not be_empty
expect(TaggableModel.all_tags(order: "#{ActsAsTaggableOn.tags_table}.id").first.name).to eq('ruby')
end
it 'should be able to use named scopes to chain tag finds by any tags by context' do
bob = TaggableModel.create(name: 'Bob', need_list: 'rails', offering_list: 'c++')
TaggableModel.create(name: 'Frank', need_list: 'css', offering_list: 'css')
TaggableModel.create(name: 'Steve', need_list: 'c++', offering_list: 'java')
# Let's only find those who need rails or css and are offering c++ or java
expect(TaggableModel.tagged_with(['rails, css'], on: :needs, any: true).tagged_with(['c++', 'java'], on: :offerings, any: true).to_a).to eq([bob])
end
it 'should not return read-only records' do
TaggableModel.create(name: 'Bob', tag_list: 'ruby, rails, css')
expect(TaggableModel.tagged_with('ruby').first).to_not be_readonly
end
it 'should be able to get scoped tag counts' do
TaggableModel.create(name: 'Bob', tag_list: 'ruby, rails, css')
TaggableModel.create(name: 'Frank', tag_list: 'ruby, rails')
TaggableModel.create(name: 'Charlie', skill_list: 'ruby')
expect(TaggableModel.tagged_with('ruby').tag_counts(order: "#{ActsAsTaggableOn.tags_table}.id").first.count).to eq(2) # ruby
expect(TaggableModel.tagged_with('ruby').skill_counts.first.count).to eq(1) # ruby
end
it 'should be able to get all scoped tag counts' do
TaggableModel.create(name: 'Bob', tag_list: 'ruby, rails, css')
TaggableModel.create(name: 'Frank', tag_list: 'ruby, rails')
TaggableModel.create(name: 'Charlie', skill_list: 'ruby')
expect(TaggableModel.tagged_with('ruby').all_tag_counts(order: "#{ActsAsTaggableOn.tags_table}.id").first.count).to eq(3) # ruby
end
it 'should be able to get all scoped tags' do
TaggableModel.create(name: 'Bob', tag_list: 'ruby, rails, css')
TaggableModel.create(name: 'Frank', tag_list: 'ruby, rails')
TaggableModel.create(name: 'Charlie', skill_list: 'ruby')
expect(TaggableModel.tagged_with('ruby').all_tags(order: "#{ActsAsTaggableOn.tags_table}.id").first.name).to eq('ruby')
end
it 'should only return tag counts for the available scope' do
frank = TaggableModel.create(name: 'Frank', tag_list: 'ruby, rails')
TaggableModel.create(name: 'Bob', tag_list: 'ruby, rails, css')
TaggableModel.create(name: 'Charlie', skill_list: 'ruby, java')
expect(TaggableModel.tagged_with('rails').all_tag_counts.size).to eq(3)
expect(TaggableModel.tagged_with('rails').all_tag_counts.any? { |tag| tag.name == 'java' }).to be_falsy
# Test specific join syntaxes:
frank.untaggable_models.create!
expect(TaggableModel.tagged_with('rails').joins(:untaggable_models).all_tag_counts.size).to eq(2)
expect(TaggableModel.tagged_with('rails').joins([:untaggable_models]).all_tag_counts.size).to eq(2)
end
it 'should only return tags for the available scope' do
frank = TaggableModel.create(name: 'Frank', tag_list: 'ruby, rails')
TaggableModel.create(name: 'Bob', tag_list: 'ruby, rails, css')
TaggableModel.create(name: 'Charlie', skill_list: 'ruby, java')
expect(TaggableModel.tagged_with('rails').all_tags.count).to eq(3)
expect(TaggableModel.tagged_with('rails').all_tags.any? { |tag| tag.name == 'java' }).to be_falsy
# Test specific join syntaxes:
frank.untaggable_models.create!
expect(TaggableModel.tagged_with('rails').joins(:untaggable_models).all_tags.size).to eq(2)
expect(TaggableModel.tagged_with('rails').joins([:untaggable_models]).all_tags.size).to eq(2)
end
it 'should be able to set a custom tag context list' do
bob = TaggableModel.create(name: 'Bob')
bob.set_tag_list_on(:rotors, 'spinning, jumping')
expect(bob.tag_list_on(:rotors)).to eq(%w(spinning jumping))
bob.save
bob.reload
expect(bob.tags_on(:rotors)).to_not be_empty
end
it 'should be able to find tagged' do
bob = TaggableModel.create(name: 'Bob', tag_list: 'fitter, happier, more productive', skill_list: 'ruby, rails, css')
frank = TaggableModel.create(name: 'Frank', tag_list: 'weaker, depressed, inefficient', skill_list: 'ruby, rails, css')
steve = TaggableModel.create(name: 'Steve', tag_list: 'fitter, happier, more productive', skill_list: 'c++, java, ruby')
expect(TaggableModel.tagged_with('ruby', order: 'taggable_models.name').to_a).to eq([bob, frank, steve])
expect(TaggableModel.tagged_with('ruby, rails', order: 'taggable_models.name').to_a).to eq([bob, frank])
expect(TaggableModel.tagged_with(%w(ruby rails), order: 'taggable_models.name').to_a).to eq([bob, frank])
end
it 'should be able to find tagged with quotation marks' do
bob = TaggableModel.create(name: 'Bob', tag_list: "fitter, happier, more productive, 'I love the ,comma,'")
expect(TaggableModel.tagged_with("'I love the ,comma,'")).to include(bob)
end
it 'should be able to find tagged with invalid tags' do
bob = TaggableModel.create(name: 'Bob', tag_list: 'fitter, happier, more productive')
expect(TaggableModel.tagged_with('sad, happier')).to_not include(bob)
end
it 'should be able to find tagged with any tag' do
bob = TaggableModel.create(name: 'Bob', tag_list: 'fitter, happier, more productive', skill_list: 'ruby, rails, css')
frank = TaggableModel.create(name: 'Frank', tag_list: 'weaker, depressed, inefficient', skill_list: 'ruby, rails, css')
steve = TaggableModel.create(name: 'Steve', tag_list: 'fitter, happier, more productive', skill_list: 'c++, java, ruby')
expect(TaggableModel.tagged_with(%w(ruby java), order: 'taggable_models.name', any: true).to_a).to eq([bob, frank, steve])
expect(TaggableModel.tagged_with(%w(c++ fitter), order: 'taggable_models.name', any: true).to_a).to eq([bob, steve])
expect(TaggableModel.tagged_with(%w(depressed css), order: 'taggable_models.name', any: true).to_a).to eq([bob, frank])
end
it 'should be able to order by number of matching tags when matching any' do
bob = TaggableModel.create(name: 'Bob', tag_list: 'fitter, happier, more productive', skill_list: 'ruby, rails, css')
frank = TaggableModel.create(name: 'Frank', tag_list: 'weaker, depressed, inefficient', skill_list: 'ruby, rails, css')
steve = TaggableModel.create(name: 'Steve', tag_list: 'fitter, happier, more productive', skill_list: 'c++, java, ruby')
expect(TaggableModel.tagged_with(%w(ruby java), any: true, order_by_matching_tag_count: true, order: 'taggable_models.name').to_a).to eq([steve, bob, frank])
expect(TaggableModel.tagged_with(%w(c++ fitter), any: true, order_by_matching_tag_count: true, order: 'taggable_models.name').to_a).to eq([steve, bob])
expect(TaggableModel.tagged_with(%w(depressed css), any: true, order_by_matching_tag_count: true, order: 'taggable_models.name').to_a).to eq([frank, bob])
expect(TaggableModel.tagged_with(['fitter', 'happier', 'more productive', 'c++', 'java', 'ruby'], any: true, order_by_matching_tag_count: true, order: 'taggable_models.name').to_a).to eq([steve, bob, frank])
expect(TaggableModel.tagged_with(%w(c++ java ruby fitter), any: true, order_by_matching_tag_count: true, order: 'taggable_models.name').to_a).to eq([steve, bob, frank])
end
context 'wild: true' do
it 'should use params as wildcards' do
bob = TaggableModel.create(name: 'Bob', tag_list: 'bob, tricia')
frank = TaggableModel.create(name: 'Frank', tag_list: 'bobby, jim')
steve = TaggableModel.create(name: 'Steve', tag_list: 'john, patricia')
jim = TaggableModel.create(name: 'Jim', tag_list: 'jim, steve')
expect(TaggableModel.tagged_with(%w(bob tricia), wild: true, any: true).to_a.sort_by { |o| o.id }).to eq([bob, frank, steve])
expect(TaggableModel.tagged_with(%w(bob tricia), wild: :prefix, any: true).to_a.sort_by { |o| o.id }).to eq([bob, steve])
expect(TaggableModel.tagged_with(%w(bob tricia), wild: :suffix, any: true).to_a.sort_by { |o| o.id }).to eq([bob, frank])
expect(TaggableModel.tagged_with(%w(cia), wild: :prefix, any: true).to_a.sort_by { |o| o.id }).to eq([bob, steve])
expect(TaggableModel.tagged_with(%w(j), wild: :suffix, any: true).to_a.sort_by { |o| o.id }).to eq([frank, steve, jim])
expect(TaggableModel.tagged_with(%w(bob tricia), wild: true, exclude: true).to_a).to eq([jim])
expect(TaggableModel.tagged_with('ji', wild: true, any: true).to_a).to match_array([frank, jim])
end
end
it 'should be able to find tagged on a custom tag context' do
bob = TaggableModel.create(name: 'Bob')
bob.set_tag_list_on(:rotors, 'spinning, jumping')
expect(bob.tag_list_on(:rotors)).to eq(%w(spinning jumping))
bob.save
expect(TaggableModel.tagged_with('spinning', on: :rotors).to_a).to eq([bob])
end
it 'should be able to use named scopes to chain tag finds' do
bob = TaggableModel.create(name: 'Bob', tag_list: 'fitter, happier, more productive', skill_list: 'ruby, rails, css')
frank = TaggableModel.create(name: 'Frank', tag_list: 'weaker, depressed, inefficient', skill_list: 'ruby, rails, css')
steve = TaggableModel.create(name: 'Steve', tag_list: 'fitter, happier, more productive', skill_list: 'c++, java, python')
# Let's only find those productive Rails developers
expect(TaggableModel.tagged_with('rails', on: :skills, order: 'taggable_models.name').to_a).to eq([bob, frank])
expect(TaggableModel.tagged_with('happier', on: :tags, order: 'taggable_models.name').to_a).to eq([bob, steve])
expect(TaggableModel.tagged_with('rails', on: :skills).tagged_with('happier', on: :tags).to_a).to eq([bob])
expect(TaggableModel.tagged_with('rails').tagged_with('happier', on: :tags).to_a).to eq([bob])
end
it 'should be able to find tagged with only the matching tags' do
TaggableModel.create(name: 'Bob', tag_list: 'lazy, happier')
TaggableModel.create(name: 'Frank', tag_list: 'fitter, happier, inefficient')
steve = TaggableModel.create(name: 'Steve', tag_list: 'fitter, happier')
expect(TaggableModel.tagged_with('fitter, happier', match_all: true).to_a).to eq([steve])
end
it 'should be able to find tagged with only the matching tags for a context' do
TaggableModel.create(name: 'Bob', tag_list: 'lazy, happier', skill_list: 'ruby, rails, css')
frank = TaggableModel.create(name: 'Frank', tag_list: 'fitter, happier, inefficient', skill_list: 'css')
TaggableModel.create(name: 'Steve', tag_list: 'fitter, happier', skill_list: 'ruby, rails, css')
expect(TaggableModel.tagged_with('css', on: :skills, match_all: true).to_a).to eq([frank])
end
it 'should be able to find tagged with some excluded tags' do
TaggableModel.create(name: 'Bob', tag_list: 'happier, lazy')
frank = TaggableModel.create(name: 'Frank', tag_list: 'happier')
steve = TaggableModel.create(name: 'Steve', tag_list: 'happier')
expect(TaggableModel.tagged_with('lazy', exclude: true)).to include(frank, steve)
expect(TaggableModel.tagged_with('lazy', exclude: true).size).to eq(2)
end
it 'should return an empty scope for empty tags' do
['', ' ', nil, []].each do |tag|
expect(TaggableModel.tagged_with(tag)).to be_empty
end
end
it 'should options key not be deleted' do
options = {:exclude => true}
TaggableModel.tagged_with("foo", options)
expect(options).to eq({:exclude => true})
end
it 'should not delete tags if not updated' do
model = TaggableModel.create(name: 'foo', tag_list: 'ruby, rails, programming')
model.update(name: 'bar')
model.reload
expect(model.tag_list.sort).to eq(%w(ruby rails programming).sort)
end
context 'Duplicates' do
context 'should not create duplicate taggings' do
let(:bob) { TaggableModel.create(name: 'Bob') }
context 'case sensitive' do
it '#add' do
expect {
bob.tag_list.add 'happier'
bob.tag_list.add 'happier'
bob.tag_list.add 'happier', 'rich', 'funny'
bob.save
}.to change(ActsAsTaggableOn::Tagging, :count).by(3)
end
it '#<<' do
expect {
bob.tag_list << 'social'
bob.tag_list << 'social'
bob.tag_list << 'social' << 'wow'
bob.save
}.to change(ActsAsTaggableOn::Tagging, :count).by(2)
end
it 'unicode' do
expect {
bob.tag_list.add 'ПРИВЕТ'
bob.tag_list.add 'ПРИВЕТ'
bob.tag_list.add 'ПРИВЕТ', 'ПРИВЕТ'
bob.save
}.to change(ActsAsTaggableOn::Tagging, :count).by(1)
end
it '#=' do
expect {
bob.tag_list = ['Happy', 'Happy']
bob.save
}.to change(ActsAsTaggableOn::Tagging, :count).by(1)
end
end
context 'case insensitive' do
before(:all) { ActsAsTaggableOn.force_lowercase = true }
after(:all) { ActsAsTaggableOn.force_lowercase = false }
it '#<<' do
expect {
bob.tag_list << 'Alone'
bob.tag_list << 'AloNe'
bob.tag_list << 'ALONE' << 'In The dark'
bob.save
}.to change(ActsAsTaggableOn::Tagging, :count).by(2)
end
it '#add' do
expect {
bob.tag_list.add 'forever'
bob.tag_list.add 'ForEver'
bob.tag_list.add 'FOREVER', 'ALONE'
bob.save
}.to change(ActsAsTaggableOn::Tagging, :count).by(2)
end
it 'unicode' do
expect {
bob.tag_list.add 'ПРИВЕТ'
bob.tag_list.add 'привет', 'Привет'
bob.save
}.to change(ActsAsTaggableOn::Tagging, :count).by(1)
end
it '#=' do
expect {
bob.tag_list = ['Happy', 'HAPPY']
bob.save
}.to change(ActsAsTaggableOn::Tagging, :count).by(1)
end
end
end
it 'should not duplicate tags' do
connor = TaggableModel.new(name: 'Connor', tag_list: 'There, can, be, only, one')
allow(ActsAsTaggableOn::Tag).to receive(:create).and_call_original
expect(ActsAsTaggableOn::Tag).to receive(:create).with(name: 'can') do
# Simulate concurrent tag creation
ActsAsTaggableOn::Tag.new(name: 'can').save!
raise ActiveRecord::RecordNotUnique
end
expect(ActsAsTaggableOn::Tag).to receive(:create).with(name: 'be') do
# Simulate concurrent tag creation
ActsAsTaggableOn::Tag.new(name: 'be').save!
raise ActiveRecord::RecordNotUnique
end
expect { connor.save! }.to change(ActsAsTaggableOn::Tag, :count).by(5)
%w[There can only be one].each do |tag|
expect(TaggableModel.tagged_with(tag).count).to eq(1)
end
end
end
describe 'Associations' do
before(:each) do
@taggable = TaggableModel.create(tag_list: 'awesome, epic')
end
it 'should not remove tags when creating associated objects' do
@taggable.untaggable_models.create!
@taggable.reload
expect(@taggable.tag_list.size).to eq(2)
end
end
describe 'grouped_column_names_for method' do
it 'should return all column names joined for Tag GROUP clause' do
# NOTE: type column supports an STI Tag subclass in the test suite, though
# isn't included by default in the migration generator
expect(@taggable.grouped_column_names_for(ActsAsTaggableOn::Tag))
.to eq("#{ActsAsTaggableOn.tags_table}.id, #{ActsAsTaggableOn.tags_table}.name, #{ActsAsTaggableOn.tags_table}.taggings_count, #{ActsAsTaggableOn.tags_table}.type")
end
it 'should return all column names joined for TaggableModel GROUP clause' do
expect(@taggable.grouped_column_names_for(TaggableModel)).to eq('taggable_models.id, taggable_models.name, taggable_models.type, taggable_models.tenant_id')
end
it 'should return all column names joined for NonStandardIdTaggableModel GROUP clause' do
expect(@taggable.grouped_column_names_for(TaggableModel)).to eq("taggable_models.#{TaggableModel.primary_key}, taggable_models.name, taggable_models.type, taggable_models.tenant_id")
end
end
describe 'NonStandardIdTaggable' do
before(:each) do
@taggable = NonStandardIdTaggableModel.new(name: 'Bob Jones')
@taggables = [@taggable, NonStandardIdTaggableModel.new(name: 'John Doe')]
end
it 'should have tag types' do
[:tags, :languages, :skills, :needs, :offerings].each do |type|
expect(NonStandardIdTaggableModel.tag_types).to include type
end
expect(@taggable.tag_types).to eq(NonStandardIdTaggableModel.tag_types)
end
it 'should have tag_counts_on' do
expect(NonStandardIdTaggableModel.tag_counts_on(:tags)).to be_empty
@taggable.tag_list = %w(awesome epic)
@taggable.save
expect(NonStandardIdTaggableModel.tag_counts_on(:tags).length).to eq(2)
expect(@taggable.tag_counts_on(:tags).length).to eq(2)
end
it 'should have tags_on' do
expect(NonStandardIdTaggableModel.tags_on(:tags)).to be_empty
@taggable.tag_list = %w(awesome epic)
@taggable.save
expect(NonStandardIdTaggableModel.tags_on(:tags).length).to eq(2)
expect(@taggable.tags_on(:tags).length).to eq(2)
end
it 'should be able to create tags' do
@taggable.skill_list = 'ruby, rails, css'
expect(@taggable.instance_variable_get('@skill_list').instance_of?(ActsAsTaggableOn::TagList)).to be_truthy
expect {
@taggable.save
}.to change(ActsAsTaggableOn::Tag, :count).by(3)
@taggable.reload
expect(@taggable.skill_list.sort).to eq(%w(ruby rails css).sort)
end
it 'should be able to create tags through the tag list directly' do
@taggable.tag_list_on(:test).add('hello')
expect(@taggable.tag_list_cache_on(:test)).to_not be_empty
expect(@taggable.tag_list_on(:test)).to eq(['hello'])
@taggable.save
@taggable.save_tags
@taggable.reload
expect(@taggable.tag_list_on(:test)).to eq(['hello'])
end
end
describe 'Autogenerated methods' do
it 'should be overridable' do
expect(TaggableModel.create(tag_list: 'woo').tag_list_submethod_called).to be_truthy
end
end
# See https://github.com/mbleigh/acts-as-taggable-on/pull/457 for details
context 'tag_counts and aggreating scopes, compatibility with MySQL ' do
before(:each) do
TaggableModel.new(:name => 'Barb Jones').tap { |t| t.tag_list = %w(awesome fun) }.save
TaggableModel.new(:name => 'John Doe').tap { |t| t.tag_list = %w(cool fun hella) }.save
TaggableModel.new(:name => 'Jo Doe').tap { |t| t.tag_list = %w(curious young naive sharp) }.save
TaggableModel.all.each { |t| t.save }
end
context 'Model.limit(x).tag_counts.sum(:tags_count)' do
it 'should not break on Mysql' do
expect(TaggableModel.limit(2).tag_counts.sum('tags_count').to_i).to eq(5)
end
end
context 'regression prevention, just making sure these esoteric queries still work' do
context 'Model.tag_counts.limit(x)' do
it 'should limit the tag objects (not very useful, of course)' do
array_of_tag_counts = TaggableModel.tag_counts.limit(2)
expect(array_of_tag_counts.count).to eq(2)
end
end
context 'Model.tag_counts.sum(:tags_count)' do
it 'should limit the total tags used' do
expect(TaggableModel.tag_counts.sum(:tags_count).to_i).to eq(9)
end
end
context 'Model.tag_counts.limit(2).sum(:tags_count)' do
it 'limit should have no effect; this is just a sanity check' do
expect(TaggableModel.tag_counts.limit(2).sum(:tags_count).to_i).to eq(9)
end
end
end
end
end
RSpec.describe 'Taggable model with json columns', if: postgresql_support_json? do
before(:each) do
@taggable = TaggableModelWithJson.new(:name => 'Bob Jones')
@taggables = [@taggable, TaggableModelWithJson.new(:name => 'John Doe')]
end
it 'should be able to find by tag with context' do
@taggable.skill_list = 'ruby, rails, css'
@taggable.tag_list = 'bob, charlie'
@taggable.save
expect(TaggableModelWithJson.tagged_with('ruby').first).to eq(@taggable)
expect(TaggableModelWithJson.tagged_with('ruby, css').first).to eq(@taggable)
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | true |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/acts_as_taggable_on/caching_spec.rb | spec/acts_as_taggable_on/caching_spec.rb | require 'spec_helper'
RSpec.describe 'Acts As Taggable On' do
describe 'Caching' do
before(:each) do
@taggable = CachedModel.new(name: 'Bob Jones')
@another_taggable = OtherCachedModel.new(name: 'John Smith')
end
it 'should add saving of tag lists and cached tag lists to the instance' do
expect(@taggable).to respond_to(:save_cached_tag_list)
expect(@another_taggable).to respond_to(:save_cached_tag_list)
expect(@taggable).to respond_to(:save_tags)
end
it 'should generate a cached column checker for each tag type' do
expect(CachedModel).to respond_to(:caching_tag_list?)
expect(OtherCachedModel).to respond_to(:caching_language_list?)
end
it 'should not have cached tags' do
expect(@taggable.cached_tag_list).to be_blank
expect(@another_taggable.cached_language_list).to be_blank
end
it 'should cache tags' do
@taggable.update(tag_list: 'awesome, epic')
expect(@taggable.cached_tag_list).to eq('awesome, epic')
@another_taggable.update(language_list: 'ruby, .net')
expect(@another_taggable.cached_language_list).to eq('ruby, .net')
end
it 'should keep the cache' do
@taggable.update(tag_list: 'awesome, epic')
@taggable = CachedModel.find(@taggable.id)
@taggable.save!
expect(@taggable.cached_tag_list).to eq('awesome, epic')
end
it 'should update the cache' do
@taggable.update(tag_list: 'awesome, epic')
@taggable.update(tag_list: 'awesome')
expect(@taggable.cached_tag_list).to eq('awesome')
end
it 'should remove the cache' do
@taggable.update(tag_list: 'awesome, epic')
@taggable.update(tag_list: '')
expect(@taggable.cached_tag_list).to be_blank
end
it 'should have a tag list' do
@taggable.update(tag_list: 'awesome, epic')
@taggable = CachedModel.find(@taggable.id)
expect(@taggable.tag_list.sort).to eq(%w(awesome epic).sort)
end
it 'should keep the tag list' do
@taggable.update(tag_list: 'awesome, epic')
@taggable = CachedModel.find(@taggable.id)
@taggable.save!
expect(@taggable.tag_list.sort).to eq(%w(awesome epic).sort)
end
it 'should clear the cache on reset_column_information' do
CachedModel.column_names
CachedModel.reset_column_information
expect(CachedModel.instance_variable_get(:@acts_as_taggable_on_cache_columns)).to eql(nil)
end
it 'should not override a user-defined columns method' do
expect(ColumnsOverrideModel.columns.map(&:name)).not_to include('ignored_column')
ColumnsOverrideModel.acts_as_taggable
expect(ColumnsOverrideModel.columns.map(&:name)).not_to include('ignored_column')
end
end
describe 'with a custom delimiter' do
before(:each) do
@taggable = CachedModel.new(name: 'Bob Jones')
@another_taggable = OtherCachedModel.new(name: 'John Smith')
ActsAsTaggableOn.delimiter = ';'
end
after(:all) do
ActsAsTaggableOn.delimiter = ','
end
it 'should cache tags with custom delimiter' do
@taggable.update(tag_list: 'awesome; epic')
expect(@taggable.tag_list).to eq(['awesome', 'epic'])
expect(@taggable.cached_tag_list).to eq('awesome; epic')
@taggable = CachedModel.find_by_name('Bob Jones')
expect(@taggable.tag_list).to eq(['awesome', 'epic'])
expect(@taggable.cached_tag_list).to eq('awesome; epic')
end
end
describe 'Cache methods initialization on new models' do
before(:all) do
ActiveRecord::Base.connection.execute(
'INSERT INTO cache_methods_injected_models (cached_tag_list) VALUES (\'ciao\')'
)
class CacheMethodsInjectedModel < ActiveRecord::Base
acts_as_taggable
end
end
after(:all) { Object.send(:remove_const, :CacheMethodsInjectedModel) }
it 'cached_tag_list_on? get injected correctly' do
expect do
CacheMethodsInjectedModel.first.tag_list
end.not_to raise_error
end
end
describe 'CachingWithArray' do
pending '#TODO'
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/acts_as_taggable_on/tagger_spec.rb | spec/acts_as_taggable_on/tagger_spec.rb | require 'spec_helper'
RSpec.describe 'Tagger' do
before(:each) do
@user = User.create
@taggable = TaggableModel.create(name: 'Bob Jones')
end
it 'should have taggings' do
@user.tag(@taggable, with: 'ruby,scheme', on: :tags)
expect(@user.owned_taggings.size).to eq(2)
end
it 'should have tags' do
@user.tag(@taggable, with: 'ruby,scheme', on: :tags)
expect(@user.owned_tags.size).to eq(2)
end
it 'should scope objects returned by tagged_with by owners' do
@taggable2 = TaggableModel.create(name: 'Jim Jones')
@taggable3 = TaggableModel.create(name: 'Jane Doe')
@user2 = User.new
@user.tag(@taggable, with: 'ruby, scheme', on: :tags)
@user2.tag(@taggable2, with: 'ruby, scheme', on: :tags)
@user2.tag(@taggable3, with: 'ruby, scheme', on: :tags)
expect(TaggableModel.tagged_with(%w(ruby scheme), owned_by: @user).count).to eq(1)
expect(TaggableModel.tagged_with(%w(ruby scheme), owned_by: @user2).count).to eq(2)
end
it 'only returns objects tagged by owned_by when any is true' do
@user2 = User.new
@taggable2 = TaggableModel.create(name: 'Jim Jones')
@taggable3 = TaggableModel.create(name: 'Jane Doe')
@user.tag(@taggable, with: 'ruby', on: :tags)
@user.tag(@taggable2, with: 'java', on: :tags)
@user2.tag(@taggable3, with: 'ruby', on: :tags)
tags = TaggableModel.tagged_with(%w(ruby java), owned_by: @user, any: true)
expect(tags).to include(@taggable, @taggable2)
expect(tags.size).to eq(2)
end
it 'only returns objects tagged by owned_by when exclude is true' do
@user2 = User.new
@taggable2 = TaggableModel.create(name: 'Jim Jones')
@taggable3 = TaggableModel.create(name: 'Jane Doe')
@user.tag(@taggable, with: 'ruby', on: :tags)
@user.tag(@taggable2, with: 'java', on: :tags)
@user2.tag(@taggable3, with: 'java', on: :tags)
tags = TaggableModel.tagged_with(%w(ruby), owned_by: @user, exclude: true)
expect(tags).to eq([@taggable2])
end
it 'should not overlap tags from different taggers' do
@user2 = User.new
expect {
@user.tag(@taggable, with: 'ruby, scheme', on: :tags)
@user2.tag(@taggable, with: 'java, python, lisp, ruby', on: :tags)
}.to change(ActsAsTaggableOn::Tagging, :count).by(6)
[@user, @user2, @taggable].each(&:reload)
expect(@user.owned_tags.map(&:name).sort).to eq(%w(ruby scheme).sort)
expect(@user2.owned_tags.map(&:name).sort).to eq(%w(java python lisp ruby).sort)
expect(@taggable.tags_from(@user).sort).to eq(%w(ruby scheme).sort)
expect(@taggable.tags_from(@user2).sort).to eq(%w(java lisp python ruby).sort)
expect(@taggable.all_tags_list.sort).to eq(%w(ruby scheme java python lisp).sort)
expect(@taggable.all_tags_on(:tags).size).to eq(5)
end
it 'should not lose tags from different taggers' do
@user2 = User.create
@user2.tag(@taggable, with: 'java, python, lisp, ruby', on: :tags)
@user.tag(@taggable, with: 'ruby, scheme', on: :tags)
expect {
@user2.tag(@taggable, with: 'java, python, lisp', on: :tags)
}.to change(ActsAsTaggableOn::Tagging, :count).by(-1)
[@user, @user2, @taggable].each(&:reload)
expect(@taggable.tags_from(@user).sort).to eq(%w(ruby scheme).sort)
expect(@taggable.tags_from(@user2).sort).to eq(%w(java python lisp).sort)
expect(@taggable.all_tags_list.sort).to eq(%w(ruby scheme java python lisp).sort)
expect(@taggable.all_tags_on(:tags).length).to eq(5)
end
it 'should not lose tags' do
@user2 = User.create
@user.tag(@taggable, with: 'awesome', on: :tags)
@user2.tag(@taggable, with: 'awesome, epic', on: :tags)
expect {
@user2.tag(@taggable, with: 'epic', on: :tags)
}.to change(ActsAsTaggableOn::Tagging, :count).by(-1)
@taggable.reload
expect(@taggable.all_tags_list).to include('awesome')
expect(@taggable.all_tags_list).to include('epic')
end
it 'should not lose tags' do
@taggable.update(tag_list: 'ruby')
@user.tag(@taggable, with: 'ruby, scheme', on: :tags)
[@taggable, @user].each(&:reload)
expect(@taggable.tag_list).to eq(%w(ruby))
expect(@taggable.all_tags_list.sort).to eq(%w(ruby scheme).sort)
expect {
@taggable.update(tag_list: '')
}.to change(ActsAsTaggableOn::Tagging, :count).by(-1)
expect(@taggable.tag_list).to be_empty
expect(@taggable.all_tags_list.sort).to eq(%w(ruby scheme).sort)
end
it 'is tagger' do
expect(@user.is_tagger?).to be_truthy
end
it 'should skip save if skip_save is passed as option' do
expect(-> {
@user.tag(@taggable, with: 'epic', on: :tags, skip_save: true)
}).to_not change(ActsAsTaggableOn::Tagging, :count)
end
it 'should change tags order in ordered taggable' do
@ordered_taggable = OrderedTaggableModel.create name: 'hey!'
@user.tag @ordered_taggable, with: 'tag, tag1', on: :tags
expect(@ordered_taggable.reload.tags_from(@user)).to eq(['tag', 'tag1'])
@user.tag @ordered_taggable, with: 'tag2, tag1', on: :tags
expect(@ordered_taggable.reload.tags_from(@user)).to eq(['tag2', 'tag1'])
@user.tag @ordered_taggable, with: 'tag1, tag2', on: :tags
expect(@ordered_taggable.reload.tags_from(@user)).to eq(['tag1', 'tag2'])
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/acts_as_taggable_on/acts_as_taggable_on_spec.rb | spec/acts_as_taggable_on/acts_as_taggable_on_spec.rb | require 'spec_helper'
RSpec.describe 'Acts As Taggable On' do
it "should provide a class method 'taggable?' that is false for untaggable models" do
expect(UntaggableModel).to_not be_taggable
end
describe 'Taggable Method Generation To Preserve Order' do
before(:each) do
TaggableModel.tag_types = []
TaggableModel.preserve_tag_order = false
TaggableModel.acts_as_ordered_taggable_on(:ordered_tags)
@taggable = TaggableModel.new(name: 'Bob Jones')
end
it "should respond 'true' to preserve_tag_order?" do
expect(@taggable.class.preserve_tag_order?).to be_truthy
end
end
describe 'Taggable Method Generation' do
before(:each) do
TaggableModel.tag_types = []
TaggableModel.acts_as_taggable_on(:tags, :languages, :skills, :needs, :offerings)
@taggable = TaggableModel.new(name: 'Bob Jones')
end
it "should respond 'true' to taggable?" do
expect(@taggable.class).to be_taggable
end
it 'should create a class attribute for tag types' do
expect(@taggable.class).to respond_to(:tag_types)
end
it 'should create an instance attribute for tag types' do
expect(@taggable).to respond_to(:tag_types)
end
it 'should have all tag types' do
expect(@taggable.tag_types).to eq([:tags, :languages, :skills, :needs, :offerings])
end
it 'should create a class attribute for preserve tag order' do
expect(@taggable.class).to respond_to(:preserve_tag_order?)
end
it 'should create an instance attribute for preserve tag order' do
expect(@taggable).to respond_to(:preserve_tag_order?)
end
it "should respond 'false' to preserve_tag_order?" do
expect(@taggable.class.preserve_tag_order?).to be_falsy
end
it 'should generate an association for each tag type' do
expect(@taggable).to respond_to(:tags, :skills, :languages)
end
it 'should add tagged_with and tag_counts to singleton' do
expect(TaggableModel).to respond_to(:tagged_with, :tag_counts)
end
it 'should generate a tag_list accessor/setter for each tag type' do
expect(@taggable).to respond_to(:tag_list, :skill_list, :language_list)
expect(@taggable).to respond_to(:tag_list=, :skill_list=, :language_list=)
end
it 'should generate a tag_list accessor, that includes owned tags, for each tag type' do
expect(@taggable).to respond_to(:all_tags_list, :all_skills_list, :all_languages_list)
end
end
describe 'Matching Contexts' do
it 'should find objects with tags of matching contexts' do
taggable1 = TaggableModel.create!(name: 'Taggable 1')
taggable2 = TaggableModel.create!(name: 'Taggable 2')
taggable3 = TaggableModel.create!(name: 'Taggable 3')
taggable1.offering_list = 'one, two'
taggable1.save!
taggable2.need_list = 'one, two'
taggable2.save!
taggable3.offering_list = 'one, two'
taggable3.save!
expect(taggable1.find_matching_contexts(:offerings, :needs)).to include(taggable2)
expect(taggable1.find_matching_contexts(:offerings, :needs)).to_not include(taggable3)
end
it 'should find other related objects with tags of matching contexts' do
taggable1 = TaggableModel.create!(name: 'Taggable 1')
taggable2 = OtherTaggableModel.create!(name: 'Taggable 2')
taggable3 = OtherTaggableModel.create!(name: 'Taggable 3')
taggable1.offering_list = 'one, two'
taggable1.save
taggable2.need_list = 'one, two'
taggable2.save
taggable3.offering_list = 'one, two'
taggable3.save
expect(taggable1.find_matching_contexts_for(OtherTaggableModel, :offerings, :needs)).to include(taggable2)
expect(taggable1.find_matching_contexts_for(OtherTaggableModel, :offerings, :needs)).to_not include(taggable3)
end
it 'should not include the object itself in the list of related objects with tags of matching contexts' do
taggable1 = TaggableModel.create!(name: 'Taggable 1')
taggable2 = TaggableModel.create!(name: 'Taggable 2')
taggable1.offering_list = 'one, two'
taggable1.need_list = 'one, two'
taggable1.save
taggable2.need_list = 'one, two'
taggable2.save
expect(taggable1.find_matching_contexts_for(TaggableModel, :offerings, :needs)).to include(taggable2)
expect(taggable1.find_matching_contexts_for(TaggableModel, :offerings, :needs)).to_not include(taggable1)
end
it 'should ensure joins to multiple taggings maintain their contexts when aliasing' do
taggable1 = TaggableModel.create!(name: 'Taggable 1')
taggable1.offering_list = 'one'
taggable1.need_list = 'two'
taggable1.save
column = TaggableModel.connection.quote_column_name("context")
offer_alias = TaggableModel.connection.quote_table_name(ActsAsTaggableOn.taggings_table)
need_alias = TaggableModel.connection.quote_table_name("need_taggings_taggable_models_join")
expect(TaggableModel.joins(:offerings, :needs).to_sql).to include "#{offer_alias}.#{column}"
expect(TaggableModel.joins(:offerings, :needs).to_sql).to include "#{need_alias}.#{column}"
end
end
describe 'Tagging Contexts' do
it 'should eliminate duplicate tagging contexts ' do
TaggableModel.acts_as_taggable_on(:skills, :skills)
expect(TaggableModel.tag_types.freq[:skills]).to eq(1)
end
it 'should not contain embedded/nested arrays' do
TaggableModel.acts_as_taggable_on([:array], [:array])
expect(TaggableModel.tag_types.freq[[:array]]).to eq(0)
end
it 'should _flatten_ the content of arrays' do
TaggableModel.acts_as_taggable_on([:array], [:array])
expect(TaggableModel.tag_types.freq[:array]).to eq(1)
end
it 'should not raise an error when passed nil' do
expect(-> {
TaggableModel.acts_as_taggable_on
}).to_not raise_error
end
it 'should not raise an error when passed [nil]' do
expect(-> {
TaggableModel.acts_as_taggable_on([nil])
}).to_not raise_error
end
it 'should include dynamic contexts in tagging_contexts' do
taggable = TaggableModel.create!(name: 'Dynamic Taggable')
taggable.set_tag_list_on :colors, 'tag1, tag2, tag3'
expect(taggable.tagging_contexts).to eq(%w(tags languages skills needs offerings array colors))
taggable.save
taggable = TaggableModel.where(name: 'Dynamic Taggable').first
expect(taggable.tagging_contexts).to eq(%w(tags languages skills needs offerings array colors))
end
end
context 'when tagging context ends in an "s" when singular (ex. "status", "glass", etc.)' do
describe 'caching' do
before { @taggable = OtherCachedModel.new(name: 'John Smith') }
subject { @taggable }
it { should respond_to(:save_cached_tag_list) }
its(:cached_language_list) { should be_blank }
its(:cached_status_list) { should be_blank }
its(:cached_glass_list) { should be_blank }
context 'language taggings cache after update' do
before { @taggable.update(language_list: 'ruby, .net') }
subject { @taggable }
its(:language_list) { should == ['ruby', '.net']}
its(:cached_language_list) { should == 'ruby, .net' } # passes
its(:instance_variables) { should include(:@language_list) }
end
context 'status taggings cache after update' do
before { @taggable.update(status_list: 'happy, married') }
subject { @taggable }
its(:status_list) { should == ['happy', 'married'] }
its(:cached_status_list) { should == 'happy, married' } # fails
its(:cached_status_list) { should_not == '' } # fails, is blank
its(:instance_variables) { should include(:@status_list) }
its(:instance_variables) { should_not include(:@statu_list) } # fails, note: one "s"
end
context 'glass taggings cache after update' do
before do
@taggable.update(glass_list: 'rectangle, aviator')
end
subject { @taggable }
its(:glass_list) { should == ['rectangle', 'aviator'] }
its(:cached_glass_list) { should == 'rectangle, aviator' } # fails
its(:cached_glass_list) { should_not == '' } # fails, is blank
its(:instance_variables) { should include(:@glass_list) }
its(:instance_variables) { should_not include(:@glas_list) } # fails, note: one "s"
end
end
end
describe 'taggings' do
before(:each) do
@taggable = TaggableModel.new(name: 'Art Kram')
end
it 'should return no taggings' do
expect(@taggable.taggings).to be_empty
end
end
describe '@@remove_unused_tags' do
before do
@taggable = TaggableModel.create(name: 'Bob Jones')
@tag = ActsAsTaggableOn::Tag.create(name: 'awesome')
@tagging = ActsAsTaggableOn::Tagging.create(taggable: @taggable, tag: @tag, context: 'tags')
end
context 'if set to true' do
before do
ActsAsTaggableOn.remove_unused_tags = true
end
it 'should remove unused tags after removing taggings' do
@tagging.destroy
expect(ActsAsTaggableOn::Tag.find_by_name('awesome')).to be_nil
end
end
context 'if set to false' do
before do
ActsAsTaggableOn.remove_unused_tags = false
end
it 'should not remove unused tags after removing taggings' do
@tagging.destroy
expect(ActsAsTaggableOn::Tag.find_by_name('awesome')).to eq(@tag)
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/internal/app/models/student.rb | spec/internal/app/models/student.rb | require_relative 'user'
class Student < User
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/internal/app/models/taggable_model.rb | spec/internal/app/models/taggable_model.rb | class TaggableModel < ActiveRecord::Base
acts_as_taggable
acts_as_taggable_on :languages
acts_as_taggable_on :skills
acts_as_taggable_on :needs, :offerings
acts_as_taggable_tenant :tenant_id
has_many :untaggable_models
attr_reader :tag_list_submethod_called
def tag_list=(v)
@tag_list_submethod_called = true
super
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/internal/app/models/altered_inheriting_taggable_model.rb | spec/internal/app/models/altered_inheriting_taggable_model.rb | require_relative 'taggable_model'
class AlteredInheritingTaggableModel < TaggableModel
acts_as_taggable_on :parts
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/internal/app/models/other_cached_model.rb | spec/internal/app/models/other_cached_model.rb | class OtherCachedModel < ActiveRecord::Base
acts_as_taggable_on :languages, :statuses, :glasses
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/internal/app/models/untaggable_model.rb | spec/internal/app/models/untaggable_model.rb | class UntaggableModel < ActiveRecord::Base
belongs_to :taggable_model
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/internal/app/models/cached_model_with_array.rb | spec/internal/app/models/cached_model_with_array.rb | if using_postgresql?
class CachedModelWithArray < ActiveRecord::Base
acts_as_taggable
end
if postgresql_support_json?
class TaggableModelWithJson < ActiveRecord::Base
acts_as_taggable
acts_as_taggable_on :skills
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/internal/app/models/inheriting_taggable_model.rb | spec/internal/app/models/inheriting_taggable_model.rb | require_relative 'taggable_model'
class InheritingTaggableModel < TaggableModel
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/internal/app/models/cached_model.rb | spec/internal/app/models/cached_model.rb | class CachedModel < ActiveRecord::Base
acts_as_taggable
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/internal/app/models/market.rb | spec/internal/app/models/market.rb | class Market < ActsAsTaggableOn::Tag
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/internal/app/models/other_taggable_model.rb | spec/internal/app/models/other_taggable_model.rb | class OtherTaggableModel < ActiveRecord::Base
acts_as_taggable_on :tags, :languages
acts_as_taggable_on :needs, :offerings
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/internal/app/models/columns_override_model.rb | spec/internal/app/models/columns_override_model.rb | class ColumnsOverrideModel < ActiveRecord::Base
def self.columns
super.reject { |c| c.name == 'ignored_column' }
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/internal/app/models/non_standard_id_taggable_model.rb | spec/internal/app/models/non_standard_id_taggable_model.rb | class NonStandardIdTaggableModel < ActiveRecord::Base
self.primary_key = :an_id
acts_as_taggable
acts_as_taggable_on :languages
acts_as_taggable_on :skills
acts_as_taggable_on :needs, :offerings
has_many :untaggable_models
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/internal/app/models/ordered_taggable_model.rb | spec/internal/app/models/ordered_taggable_model.rb | class OrderedTaggableModel < ActiveRecord::Base
acts_as_ordered_taggable
acts_as_ordered_taggable_on :colours
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/internal/app/models/company.rb | spec/internal/app/models/company.rb | class Company < ActiveRecord::Base
acts_as_taggable_on :locations, :markets
has_many :markets, :through => :market_taggings, :source => :tag
private
def find_or_create_tags_from_list_with_context(tag_list, context)
if context.to_sym == :markets
Market.find_or_create_all_with_like_by_name(tag_list)
else
super
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/internal/app/models/user.rb | spec/internal/app/models/user.rb | class User < ActiveRecord::Base
acts_as_tagger
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/spec/internal/db/schema.rb | spec/internal/db/schema.rb | ActiveRecord::Schema.define version: 0 do
create_table ActsAsTaggableOn.tags_table, force: true do |t|
t.string :name
t.integer :taggings_count, default: 0
t.string :type
end
add_index ActsAsTaggableOn.tags_table, ['name'], name: 'index_tags_on_name', unique: true
create_table ActsAsTaggableOn.taggings_table, force: true do |t|
t.integer :tag_id
# You should make sure that the column created is
# long enough to store the required class names.
t.string :taggable_type
t.integer :taggable_id
t.string :tagger_type
t.integer :tagger_id
# Limit is created to prevent MySQL error on index
# length for MyISAM table type: http://bit.ly/vgW2Ql
t.string :context, limit: 128
t.string :tenant , limit: 128
t.datetime :created_at
end
add_index ActsAsTaggableOn.taggings_table,
['tag_id', 'taggable_id', 'taggable_type', 'context', 'tagger_id', 'tagger_type'],
unique: true, name: 'taggings_idx'
add_index ActsAsTaggableOn.taggings_table, :tag_id , name: 'index_taggings_on_tag_id'
# above copied from
# generators/acts_as_taggable_on/migration/migration_generator
create_table :taggable_models, force: true do |t|
t.column :name, :string
t.column :type, :string
t.column :tenant_id, :integer
end
create_table :columns_override_models, force: true do |t|
t.column :name, :string
t.column :type, :string
t.column :ignored_column, :string
end
create_table :non_standard_id_taggable_models, primary_key: 'an_id', force: true do |t|
t.column :name, :string
t.column :type, :string
end
create_table :untaggable_models, force: true do |t|
t.column :taggable_model_id, :integer
t.column :name, :string
end
create_table :cached_models, force: true do |t|
t.column :name, :string
t.column :type, :string
t.column :cached_tag_list, :string
end
create_table :other_cached_models, force: true do |t|
t.column :name, :string
t.column :type, :string
t.column :cached_language_list, :string
t.column :cached_status_list, :string
t.column :cached_glass_list, :string
end
create_table :companies, force: true do |t|
t.column :name, :string
end
create_table :users, force: true do |t|
t.column :name, :string
end
create_table :other_taggable_models, force: true do |t|
t.column :name, :string
t.column :type, :string
end
create_table :ordered_taggable_models, force: true do |t|
t.column :name, :string
t.column :type, :string
end
create_table :cache_methods_injected_models, force: true do |t|
t.column :cached_tag_list, :string
end
# Special cases for postgresql
if using_postgresql?
create_table :other_cached_with_array_models, force: true do |t|
t.column :name, :string
t.column :type, :string
t.column :cached_language_list, :string, array: true
t.column :cached_status_list, :string, array: true
t.column :cached_glass_list, :string, array: true
end
if postgresql_support_json?
create_table :taggable_model_with_jsons, :force => true do |t|
t.column :name, :string
t.column :type, :string
t.column :opts, :json
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on.rb | lib/acts-as-taggable-on.rb | require 'active_record'
require 'active_record/version'
require 'active_support/core_ext/module'
require 'zeitwerk'
loader = Zeitwerk::Loader.for_gem
loader.inflector.inflect "acts-as-taggable-on" => "ActsAsTaggableOn"
loader.setup
begin
require 'rails/engine'
require 'acts-as-taggable-on/engine'
rescue LoadError
end
require 'digest/sha1'
module ActsAsTaggableOn
class DuplicateTagError < StandardError
end
def self.setup
@configuration ||= Configuration.new
yield @configuration if block_given?
end
def self.method_missing(method_name, *args, &block)
@configuration.respond_to?(method_name) ?
@configuration.send(method_name, *args, &block) : super
end
def self.respond_to?(method_name, include_private=false)
@configuration.respond_to? method_name
end
def self.glue
setting = @configuration.delimiter
delimiter = setting.kind_of?(Array) ? setting[0] : setting
delimiter.end_with?(' ') ? delimiter : "#{delimiter} "
end
class Configuration
attr_accessor :force_lowercase, :force_parameterize,
:remove_unused_tags, :default_parser,
:tags_counter, :tags_table,
:taggings_table
attr_reader :delimiter, :strict_case_match, :base_class
def initialize
@delimiter = ','
@force_lowercase = false
@force_parameterize = false
@strict_case_match = false
@remove_unused_tags = false
@tags_counter = true
@default_parser = DefaultParser
@force_binary_collation = false
@tags_table = :tags
@taggings_table = :taggings
@base_class = '::ActiveRecord::Base'
end
def strict_case_match=(force_cs)
@strict_case_match = force_cs unless @force_binary_collation
end
def delimiter=(string)
ActiveRecord::Base.logger.warn <<WARNING
ActsAsTaggableOn.delimiter is deprecated \
and will be removed from v4.0+, use \
a ActsAsTaggableOn.default_parser instead
WARNING
@delimiter = string
end
def force_binary_collation=(force_bin)
if Utils.using_mysql?
if force_bin
Configuration.apply_binary_collation(true)
@force_binary_collation = true
@strict_case_match = true
else
Configuration.apply_binary_collation(false)
@force_binary_collation = false
end
end
end
def self.apply_binary_collation(bincoll)
if Utils.using_mysql?
coll = 'utf8_general_ci'
coll = 'utf8_bin' if bincoll
begin
ActiveRecord::Migration.execute("ALTER TABLE #{Tag.table_name} MODIFY name varchar(255) CHARACTER SET utf8 COLLATE #{coll};")
rescue Exception => e
puts "Trapping #{e.class}: collation parameter ignored while migrating for the first time."
end
end
end
def base_class=(base_class)
raise "base_class must be a String" unless base_class.is_a?(String)
@base_class = base_class
end
end
setup
end
ActiveSupport.on_load(:active_record) do
extend ActsAsTaggableOn::Taggable
include ActsAsTaggableOn::Tagger
end
ActiveSupport.on_load(:action_view) do
include ActsAsTaggableOn::TagsHelper
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/tag.rb | lib/acts-as-taggable-on/tag.rb | # frozen_string_literal: true
module ActsAsTaggableOn
class Tag < ActsAsTaggableOn.base_class.constantize
self.table_name = ActsAsTaggableOn.tags_table
### ASSOCIATIONS:
has_many :taggings, dependent: :destroy, class_name: '::ActsAsTaggableOn::Tagging'
### VALIDATIONS:
validates_presence_of :name
validates_uniqueness_of :name, if: :validates_name_uniqueness?, case_sensitive: true
validates_length_of :name, maximum: 255
# monkey patch this method if don't need name uniqueness validation
def validates_name_uniqueness?
true
end
### SCOPES:
scope :most_used, ->(limit = 20) { order('taggings_count desc').limit(limit) }
scope :least_used, ->(limit = 20) { order('taggings_count asc').limit(limit) }
def self.named(name)
if ActsAsTaggableOn.strict_case_match
where(["name = #{binary}?", name.to_s])
else
where(['LOWER(name) = LOWER(?)', name.to_s.downcase])
end
end
def self.named_any(list)
clause = list.map do |tag|
sanitize_sql_for_named_any(tag)
end.join(' OR ')
where(clause)
end
def self.named_like(name)
clause = ["name #{ActsAsTaggableOn::Utils.like_operator} ? ESCAPE '!'",
"%#{ActsAsTaggableOn::Utils.escape_like(name)}%"]
where(clause)
end
def self.named_like_any(list)
clause = list.map do |tag|
sanitize_sql(["name #{ActsAsTaggableOn::Utils.like_operator} ? ESCAPE '!'",
"%#{ActsAsTaggableOn::Utils.escape_like(tag.to_s)}%"])
end.join(' OR ')
where(clause)
end
def self.for_context(context)
joins(:taggings)
.where(["#{ActsAsTaggableOn.taggings_table}.context = ?", context])
.select("DISTINCT #{ActsAsTaggableOn.tags_table}.*")
end
def self.for_tenant(tenant)
joins(:taggings)
.where("#{ActsAsTaggableOn.taggings_table}.tenant = ?", tenant.to_s)
.select("DISTINCT #{ActsAsTaggableOn.tags_table}.*")
end
### CLASS METHODS:
def self.find_or_create_with_like_by_name(name)
if ActsAsTaggableOn.strict_case_match
find_or_create_all_with_like_by_name([name]).first
else
named_like(name).first || create(name: name)
end
end
def self.find_or_create_all_with_like_by_name(*list)
list = Array(list).flatten
return [] if list.empty?
existing_tags = named_any(list)
list.map do |tag_name|
tries ||= 3
comparable_tag_name = comparable_name(tag_name)
existing_tag = existing_tags.find { |tag| comparable_name(tag.name) == comparable_tag_name }
next existing_tag if existing_tag
transaction(requires_new: true) { create(name: tag_name) }
rescue ActiveRecord::RecordNotUnique
if (tries -= 1).positive?
existing_tags = named_any(list)
retry
end
raise DuplicateTagError, "'#{tag_name}' has already been taken"
end
end
### INSTANCE METHODS:
def ==(other)
super || (other.is_a?(Tag) && name == other.name)
end
def to_s
name
end
def count
read_attribute(:count).to_i
end
class << self
private
def comparable_name(str)
if ActsAsTaggableOn.strict_case_match
str
else
str.to_s.downcase
end
end
def binary
ActsAsTaggableOn::Utils.using_mysql? ? 'BINARY ' : nil
end
def sanitize_sql_for_named_any(tag)
if ActsAsTaggableOn.strict_case_match
sanitize_sql(["name = #{binary}?", tag.to_s])
else
sanitize_sql(['LOWER(name) = LOWER(?)', tag.to_s.downcase])
end
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/default_parser.rb | lib/acts-as-taggable-on/default_parser.rb | # frozen_string_literal: true
module ActsAsTaggableOn
##
# Returns a new TagList using the given tag string.
#
# Example:
# tag_list = ActsAsTaggableOn::DefaultParser.parse("One , Two, Three")
# tag_list # ["One", "Two", "Three"]
class DefaultParser < GenericParser
def parse
string = @tag_list
string = string.join(ActsAsTaggableOn.glue) if string.respond_to?(:join)
TagList.new.tap do |tag_list|
string = string.to_s.dup
string.gsub!(double_quote_pattern) do
# Append the matched tag to the tag list
tag_list << Regexp.last_match[2]
# Return the matched delimiter ($3) to replace the matched items
''
end
string.gsub!(single_quote_pattern) do
# Append the matched tag ($2) to the tag list
tag_list << Regexp.last_match[2]
# Return an empty string to replace the matched items
''
end
# split the string by the delimiter
# and add to the tag_list
tag_list.add(string.split(Regexp.new(delimiter)))
end
end
# private
def delimiter
# Parse the quoted tags
d = ActsAsTaggableOn.delimiter
# Separate multiple delimiters by bitwise operator
d = d.join('|') if d.is_a?(Array)
d
end
# ( # Tag start delimiter ($1)
# \A | # Either string start or
# #{delimiter} # a delimiter
# )
# \s*" # quote (") optionally preceded by whitespace
# (.*?) # Tag ($2)
# "\s* # quote (") optionally followed by whitespace
# (?= # Tag end delimiter (not consumed; is zero-length lookahead)
# #{delimiter}\s* | # Either a delimiter optionally followed by whitespace or
# \z # string end
# )
def double_quote_pattern
/(\A|#{delimiter})\s*"(.*?)"\s*(?=#{delimiter}\s*|\z)/
end
# ( # Tag start delimiter ($1)
# \A | # Either string start or
# #{delimiter} # a delimiter
# )
# \s*' # quote (') optionally preceded by whitespace
# (.*?) # Tag ($2)
# '\s* # quote (') optionally followed by whitespace
# (?= # Tag end delimiter (not consumed; is zero-length lookahead)
# #{delimiter}\s* | d # Either a delimiter optionally followed by whitespace or
# \z # string end
# )
def single_quote_pattern
/(\A|#{delimiter})\s*'(.*?)'\s*(?=#{delimiter}\s*|\z)/
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/version.rb | lib/acts-as-taggable-on/version.rb | # frozen_string_literal: true
module ActsAsTaggableOn
VERSION = '13.0.0'
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/tag_list.rb | lib/acts-as-taggable-on/tag_list.rb | # frozen_string_literal: true
require 'active_support/core_ext/module/delegation'
module ActsAsTaggableOn
class TagList < Array
attr_accessor :owner, :parser
def initialize(*args)
@parser = ActsAsTaggableOn.default_parser
add(*args)
end
##
# Add tags to the tag_list. Duplicate or blank tags will be ignored.
# Use the <tt>:parse</tt> option to add an unparsed tag string.
#
# Example:
# tag_list.add("Fun", "Happy")
# tag_list.add("Fun, Happy", :parse => true)
def add(*names)
extract_and_apply_options!(names)
concat(names)
clean!
self
end
# Append---Add the tag to the tag_list. This
# expression returns the tag_list itself, so several appends
# may be chained together.
def <<(obj)
add(obj)
end
# Concatenation --- Returns a new tag list built by concatenating the
# two tag lists together to produce a third tag list.
def +(other)
TagList.new.add(self).add(other)
end
# Appends the elements of +other_tag_list+ to +self+.
def concat(other_tag_list)
super(other_tag_list).send(:clean!)
self
end
##
# Remove specific tags from the tag_list.
# Use the <tt>:parse</tt> option to add an unparsed tag string.
#
# Example:
# tag_list.remove("Sad", "Lonely")
# tag_list.remove("Sad, Lonely", :parse => true)
def remove(*names)
extract_and_apply_options!(names)
delete_if { |name| names.include?(name) }
self
end
##
# Transform the tag_list into a tag string suitable for editing in a form.
# The tags are joined with <tt>TagList.delimiter</tt> and quoted if necessary.
#
# Example:
# tag_list = TagList.new("Round", "Square,Cube")
# tag_list.to_s # 'Round, "Square,Cube"'
def to_s
tags = frozen? ? dup : self
tags.send(:clean!)
tags.map do |name|
d = ActsAsTaggableOn.delimiter
d = Regexp.new d.join('|') if d.is_a? Array
name.index(d) ? "\"#{name}\"" : name
end.join(ActsAsTaggableOn.glue)
end
private
# Convert everything to string, remove whitespace, duplicates, and blanks.
def clean!
reject!(&:blank?)
map!(&:to_s)
map!(&:strip)
map! { |tag| tag.to_s.downcase } if ActsAsTaggableOn.force_lowercase
map!(&:parameterize) if ActsAsTaggableOn.force_parameterize
ActsAsTaggableOn.strict_case_match ? uniq! : uniq!(&:downcase)
self
end
def extract_and_apply_options!(args)
options = args.last.is_a?(Hash) ? args.pop : {}
options.assert_valid_keys :parse, :parser
parser = options[:parser] || @parser
args.map! { |a| parser.new(a).parse } if options[:parse] || options[:parser]
args.flatten!
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/tagger.rb | lib/acts-as-taggable-on/tagger.rb | # frozen_string_literal: true
module ActsAsTaggableOn
module Tagger
extend ActiveSupport::Concern
class_methods do
##
# Make a model a tagger. This allows an instance of a model to claim ownership
# of tags.
#
# Example:
# class User < ActiveRecord::Base
# acts_as_tagger
# end
def acts_as_tagger(opts = {})
class_eval do
owned_taggings_scope = opts.delete(:scope)
has_many :owned_taggings, owned_taggings_scope,
**opts.merge(
as: :tagger,
class_name: '::ActsAsTaggableOn::Tagging',
dependent: :destroy
)
has_many :owned_tags, -> { distinct },
class_name: '::ActsAsTaggableOn::Tag',
source: :tag,
through: :owned_taggings
end
include ActsAsTaggableOn::Tagger::InstanceMethods
extend ActsAsTaggableOn::Tagger::SingletonMethods
end
def tagger?
false
end
alias is_tagger? tagger?
end
module InstanceMethods
##
# Tag a taggable model with tags that are owned by the tagger.
#
# @param taggable The object that will be tagged
# @param [Hash] options An hash with options. Available options are:
# * <tt>:with</tt> - The tags that you want to
# * <tt>:on</tt> - The context on which you want to tag
#
# Example:
# @user.tag(@photo, :with => "paris, normandy", :on => :locations)
def tag(taggable, opts = {})
opts.reverse_merge!(force: true)
skip_save = opts.delete(:skip_save)
return false unless taggable.respond_to?(:is_taggable?) && taggable.is_taggable?
raise 'You need to specify a tag context using :on' unless opts.key?(:on)
raise 'You need to specify some tags using :with' unless opts.key?(:with)
unless opts[:force] || taggable.tag_types.include?(opts[:on])
raise "No context :#{opts[:on]} defined in #{taggable.class}"
end
taggable.set_owner_tag_list_on(self, opts[:on].to_s, opts[:with])
taggable.save unless skip_save
end
def tagger?
self.class.is_tagger?
end
alias is_tagger? tagger?
end
module SingletonMethods
def tagger?
true
end
alias is_tagger? tagger?
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/tags_helper.rb | lib/acts-as-taggable-on/tags_helper.rb | # frozen_string_literal: true
module ActsAsTaggableOn
module TagsHelper
# See the wiki for an example using tag_cloud.
def tag_cloud(tags, classes)
return [] if tags.empty?
max_count = tags.max_by(&:taggings_count).taggings_count.to_f
tags.each do |tag|
index = ((tag.taggings_count / max_count) * (classes.size - 1))
yield tag, classes[index.nan? ? 0 : index.round]
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/utils.rb | lib/acts-as-taggable-on/utils.rb | # frozen_string_literal: true
# This module is deprecated and will be removed in the incoming versions
module ActsAsTaggableOn
module Utils
class << self
# Use ActsAsTaggableOn::Tag connection
def connection
ActsAsTaggableOn::Tag.connection
end
def using_postgresql?
connection && %w[PostgreSQL PostGIS].include?(connection.adapter_name)
end
def using_mysql?
connection && connection.adapter_name == 'Mysql2'
end
def sha_prefix(string)
Digest::SHA1.hexdigest(string)[0..6]
end
def like_operator
using_postgresql? ? 'ILIKE' : 'LIKE'
end
# escape _ and % characters in strings, since these are wildcards in SQL.
def escape_like(str)
str.gsub(/[!%_]/) { |x| "!#{x}" }
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/taggable.rb | lib/acts-as-taggable-on/taggable.rb | # frozen_string_literal: true
module ActsAsTaggableOn
module Taggable
def taggable?
false
end
##
# This is an alias for calling <tt>acts_as_taggable_on :tags</tt>.
#
# Example:
# class Book < ActiveRecord::Base
# acts_as_taggable
# end
def acts_as_taggable
acts_as_taggable_on :tags
end
##
# This is an alias for calling <tt>acts_as_ordered_taggable_on :tags</tt>.
#
# Example:
# class Book < ActiveRecord::Base
# acts_as_ordered_taggable
# end
def acts_as_ordered_taggable
acts_as_ordered_taggable_on :tags
end
##
# Make a model taggable on specified contexts.
#
# @param [Array] tag_types An array of taggable contexts
#
# Example:
# class User < ActiveRecord::Base
# acts_as_taggable_on :languages, :skills
# end
def acts_as_taggable_on(*tag_types)
taggable_on(false, tag_types)
end
##
# Make a model taggable on specified contexts
# and preserves the order in which tags are created
#
# @param [Array] tag_types An array of taggable contexts
#
# Example:
# class User < ActiveRecord::Base
# acts_as_ordered_taggable_on :languages, :skills
# end
def acts_as_ordered_taggable_on(*tag_types)
taggable_on(true, tag_types)
end
def acts_as_taggable_tenant(tenant)
if taggable?
else
class_attribute :tenant_column
end
self.tenant_column = tenant
# each of these add context-specific methods and must be
# called on each call of taggable_on
include Core
include Collection
include Caching
include Ownership
include Related
end
private
# Make a model taggable on specified contexts
# and optionally preserves the order in which tags are created
#
# Separate methods used above for backwards compatibility
# so that the original acts_as_taggable_on method is unaffected
# as it's not possible to add another argument to the method
# without the tag_types being enclosed in square brackets
#
# NB: method overridden in core module in order to create tag type
# associations and methods after this logic has executed
#
def taggable_on(preserve_tag_order, *tag_types)
tag_types = tag_types.to_a.flatten.compact.map(&:to_sym)
if taggable?
self.tag_types = (self.tag_types + tag_types).uniq
self.preserve_tag_order = preserve_tag_order
else
class_eval do
class_attribute :tag_types
class_attribute :preserve_tag_order
class_attribute :tenant_column
self.tag_types = tag_types
self.preserve_tag_order = preserve_tag_order
has_many :taggings, as: :taggable, dependent: :destroy, class_name: '::ActsAsTaggableOn::Tagging'
has_many :base_tags, through: :taggings, source: :tag, class_name: '::ActsAsTaggableOn::Tag'
def self.taggable?
true
end
end
end
# each of these add context-specific methods and must be
# called on each call of taggable_on
include Core
include Collection
include Caching
include Ownership
include Related
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/tagging.rb | lib/acts-as-taggable-on/tagging.rb | # frozen_string_literal: true
module ActsAsTaggableOn
class Tagging < ActsAsTaggableOn.base_class.constantize # :nodoc:
self.table_name = ActsAsTaggableOn.taggings_table
DEFAULT_CONTEXT = 'tags'
belongs_to :tag, class_name: '::ActsAsTaggableOn::Tag', counter_cache: ActsAsTaggableOn.tags_counter
belongs_to :taggable, polymorphic: true
belongs_to :tagger, polymorphic: true, optional: true
scope :owned_by, ->(owner) { where(tagger: owner) }
scope :not_owned, -> { where(tagger_id: nil, tagger_type: nil) }
scope :by_contexts, ->(contexts) { where(context: (contexts || DEFAULT_CONTEXT)) }
scope :by_context, ->(context = DEFAULT_CONTEXT) { by_contexts(context.to_s) }
scope :by_tenant, ->(tenant) { where(tenant: tenant) }
validates_presence_of :context
validates_presence_of :tag_id
validates_uniqueness_of :tag_id, scope: %i[taggable_type taggable_id context tagger_id tagger_type]
after_destroy :remove_unused_tags
private
def remove_unused_tags
if ActsAsTaggableOn.remove_unused_tags
if ActsAsTaggableOn.tags_counter
tag.destroy if tag.reload.taggings_count.zero?
elsif tag.reload.taggings.none?
tag.destroy
end
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/engine.rb | lib/acts-as-taggable-on/engine.rb | # frozen_string_literal: true
module ActsAsTaggableOn
class Engine < Rails::Engine
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/generic_parser.rb | lib/acts-as-taggable-on/generic_parser.rb | # frozen_string_literal: true
module ActsAsTaggableOn
##
# Returns a new TagList using the given tag string.
#
# Example:
# tag_list = ActsAsTaggableOn::GenericParser.new.parse("One , Two, Three")
# tag_list # ["One", "Two", "Three"]
class GenericParser
def initialize(tag_list)
@tag_list = tag_list
end
def parse
TagList.new.tap do |tag_list|
tag_list.add @tag_list.split(',').map(&:strip).reject(&:empty?)
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/taggable/core.rb | lib/acts-as-taggable-on/taggable/core.rb | # frozen_string_literal: true
module ActsAsTaggableOn
module Taggable
module Core
extend ActiveSupport::Concern
included do
attr_writer :custom_contexts
after_save :save_tags
initialize_acts_as_taggable_on_core
end
class_methods do
def initialize_acts_as_taggable_on_core
include taggable_mixin
tag_types.map(&:to_s).each do |tags_type|
tag_type = tags_type.to_s.singularize
context_taggings = "#{tag_type}_taggings".to_sym
context_tags = tags_type.to_sym
taggings_order = (preserve_tag_order? ? "#{ActsAsTaggableOn::Tagging.table_name}.id" : [])
class_eval do
# when preserving tag order, include order option so that for a 'tags' context
# the associations tag_taggings & tags are always returned in created order
has_many context_taggings, -> { includes(:tag).order(taggings_order).where(context: tags_type) },
as: :taggable,
class_name: 'ActsAsTaggableOn::Tagging',
dependent: :destroy,
after_add: :dirtify_tag_list,
after_remove: :dirtify_tag_list
has_many context_tags, -> { order(taggings_order) },
class_name: 'ActsAsTaggableOn::Tag',
through: context_taggings,
source: :tag
attribute "#{tags_type.singularize}_list".to_sym, ActsAsTaggableOn::Taggable::TagListType.new
end
taggable_mixin.class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{tag_type}_list
tag_list_on('#{tags_type}')
end
def #{tag_type}_list=(new_tags)
parsed_new_list = ActsAsTaggableOn.default_parser.new(new_tags).parse
if self.class.preserve_tag_order? || (parsed_new_list.sort != #{tag_type}_list.sort)
unless #{tag_type}_list_changed?
@attributes["#{tag_type}_list"] = ActiveModel::Attribute.from_user("#{tag_type}_list", #{tag_type}_list, ActsAsTaggableOn::Taggable::TagListType.new)
end
write_attribute("#{tag_type}_list", parsed_new_list)
end
set_tag_list_on('#{tags_type}', new_tags)
end
def all_#{tags_type}_list
all_tags_list_on('#{tags_type}')
end
private
def dirtify_tag_list(tagging)
attribute_will_change! tagging.context.singularize+"_list"
end
RUBY
end
end
def taggable_on(preserve_tag_order, *tag_types)
super(preserve_tag_order, *tag_types)
initialize_acts_as_taggable_on_core
end
# all column names are necessary for PostgreSQL group clause
def grouped_column_names_for(object)
object.column_names.map { |column| "#{object.table_name}.#{column}" }.join(', ')
end
##
# Return a scope of objects that are tagged with the specified tags.
#
# @param tags The tags that we want to query for
# @param [Hash] options A hash of options to alter you query:
# * <tt>:exclude</tt> - if set to true, return objects that are *NOT* tagged with the specified tags
# * <tt>:any</tt> - if set to true, return objects that are tagged with *ANY* of the specified tags
# * <tt>:order_by_matching_tag_count</tt> - if set to true and used with :any, sort by objects matching the most tags, descending
# * <tt>:match_all</tt> - if set to true, return objects that are *ONLY* tagged with the specified tags
# * <tt>:owned_by</tt> - return objects that are *ONLY* owned by the owner
# * <tt>:start_at</tt> - Restrict the tags to those created after a certain time
# * <tt>:end_at</tt> - Restrict the tags to those created before a certain time
#
# Example:
# User.tagged_with(["awesome", "cool"]) # Users that are tagged with awesome and cool
# User.tagged_with(["awesome", "cool"], :exclude => true) # Users that are not tagged with awesome or cool
# User.tagged_with(["awesome", "cool"], :any => true) # Users that are tagged with awesome or cool
# User.tagged_with(["awesome", "cool"], :any => true, :order_by_matching_tag_count => true) # Sort by users who match the most tags, descending
# User.tagged_with(["awesome", "cool"], :match_all => true) # Users that are tagged with just awesome and cool
# User.tagged_with(["awesome", "cool"], :owned_by => foo ) # Users that are tagged with just awesome and cool by 'foo'
# User.tagged_with(["awesome", "cool"], :owned_by => foo, :start_at => Date.today ) # Users that are tagged with just awesome, cool by 'foo' and starting today
def tagged_with(tags, options = {})
tag_list = ActsAsTaggableOn.default_parser.new(tags).parse
options = options.dup
return none if tag_list.empty?
::ActsAsTaggableOn::Taggable::TaggedWithQuery.build(self, ActsAsTaggableOn::Tag, ActsAsTaggableOn::Tagging,
tag_list, options)
end
def is_taggable?
true
end
def taggable_mixin
@taggable_mixin ||= Module.new
end
end
# all column names are necessary for PostgreSQL group clause
def grouped_column_names_for(object)
self.class.grouped_column_names_for(object)
end
def custom_contexts
@custom_contexts ||= taggings.map(&:context).uniq
end
def is_taggable?
self.class.is_taggable?
end
def add_custom_context(value)
unless custom_contexts.include?(value.to_s) || self.class.tag_types.map(&:to_s).include?(value.to_s)
custom_contexts << value.to_s
end
end
def cached_tag_list_on(context)
self["cached_#{context.to_s.singularize}_list"]
end
def tag_list_cache_set_on(context)
variable_name = "@#{context.to_s.singularize}_list"
instance_variable_defined?(variable_name) && instance_variable_get(variable_name)
end
def tag_list_cache_on(context)
variable_name = "@#{context.to_s.singularize}_list"
if instance_variable_get(variable_name)
instance_variable_get(variable_name)
elsif cached_tag_list_on(context) && ensure_included_cache_methods! && self.class.caching_tag_list_on?(context)
instance_variable_set(variable_name, ActsAsTaggableOn.default_parser.new(cached_tag_list_on(context)).parse)
else
instance_variable_set(variable_name, ActsAsTaggableOn::TagList.new(tags_on(context).map(&:name)))
end
end
def tag_list_on(context)
add_custom_context(context)
tag_list_cache_on(context)
end
def all_tags_list_on(context)
variable_name = "@all_#{context.to_s.singularize}_list"
if instance_variable_defined?(variable_name) && instance_variable_get(variable_name)
return instance_variable_get(variable_name)
end
instance_variable_set(variable_name, ActsAsTaggableOn::TagList.new(all_tags_on(context).map(&:name)).freeze)
end
##
# Returns all tags of a given context
def all_tags_on(context)
tagging_table_name = ActsAsTaggableOn::Tagging.table_name
opts = ["#{tagging_table_name}.context = ?", context.to_s]
scope = base_tags.where(opts)
if ActsAsTaggableOn::Utils.using_postgresql?
group_columns = grouped_column_names_for(ActsAsTaggableOn::Tag)
scope.order(Arel.sql("max(#{tagging_table_name}.created_at)")).group(group_columns)
else
scope.group("#{ActsAsTaggableOn::Tag.table_name}.#{ActsAsTaggableOn::Tag.primary_key}")
end.to_a
end
##
# Returns all tags that are not owned of a given context
def tags_on(context)
scope = base_tags.where([
"#{ActsAsTaggableOn::Tagging.table_name}.context = ? AND #{ActsAsTaggableOn::Tagging.table_name}.tagger_id IS NULL", context.to_s
])
# when preserving tag order, return tags in created order
# if we added the order to the association this would always apply
scope = scope.order("#{ActsAsTaggableOn::Tagging.table_name}.id") if self.class.preserve_tag_order?
scope
end
def set_tag_list_on(context, new_list)
add_custom_context(context)
variable_name = "@#{context.to_s.singularize}_list"
parsed_new_list = ActsAsTaggableOn.default_parser.new(new_list).parse
instance_variable_set(variable_name, parsed_new_list)
end
def tagging_contexts
self.class.tag_types.map(&:to_s) + custom_contexts
end
def taggable_tenant
public_send(self.class.tenant_column) if self.class.tenant_column
end
def reload(*args)
self.class.tag_types.each do |context|
instance_variable_set("@#{context.to_s.singularize}_list", nil)
instance_variable_set("@all_#{context.to_s.singularize}_list", nil)
end
super(*args)
end
##
# Find existing tags or create non-existing tags
def load_tags(tag_list)
ActsAsTaggableOn::Tag.find_or_create_all_with_like_by_name(tag_list)
end
def save_tags
tagging_contexts.each do |context|
next unless tag_list_cache_set_on(context)
# List of currently assigned tag names
tag_list = tag_list_cache_on(context).uniq
# Find existing tags or create non-existing tags:
tags = find_or_create_tags_from_list_with_context(tag_list, context)
# Tag objects for currently assigned tags
current_tags = tags_on(context)
# Tag maintenance based on whether preserving the created order of tags
old_tags = current_tags - tags
new_tags = tags - current_tags
if self.class.preserve_tag_order?
shared_tags = current_tags & tags
if shared_tags.any? && tags[0...shared_tags.size] != shared_tags
index = shared_tags.each_with_index do |_, i|
break i unless shared_tags[i] == tags[i]
end
# Update arrays of tag objects
old_tags |= current_tags[index...current_tags.size]
new_tags |= current_tags[index...current_tags.size] & shared_tags
# Order the array of tag objects to match the tag list
new_tags = tags.map do |t|
new_tags.find { |n| n.name.downcase == t.name.downcase }
end.compact
end
else
# Delete discarded tags and create new tags
end
# Destroy old taggings:
taggings.not_owned.by_context(context).where(tag_id: old_tags).destroy_all if old_tags.present?
# Create new taggings:
new_tags.each do |tag|
if taggable_tenant
taggings.create!(tag_id: tag.id, context: context.to_s, taggable: self, tenant: taggable_tenant)
else
taggings.create!(tag_id: tag.id, context: context.to_s, taggable: self)
end
end
end
true
end
private
def ensure_included_cache_methods!
self.class.columns
end
# Filters the tag lists from the attribute names.
def attributes_for_update(attribute_names)
tag_lists = tag_types.map { |tags_type| "#{tags_type.to_s.singularize}_list" }
super.delete_if { |attr| tag_lists.include? attr }
end
# Filters the tag lists from the attribute names.
def attributes_for_create(attribute_names)
tag_lists = tag_types.map { |tags_type| "#{tags_type.to_s.singularize}_list" }
super.delete_if { |attr| tag_lists.include? attr }
end
##
# Override this hook if you wish to subclass {ActsAsTaggableOn::Tag} --
# context is provided so that you may conditionally use a Tag subclass
# only for some contexts.
#
# @example Custom Tag class for one context
# class Company < ActiveRecord::Base
# acts_as_taggable_on :markets, :locations
#
# def find_or_create_tags_from_list_with_context(tag_list, context)
# if context.to_sym == :markets
# MarketTag.find_or_create_all_with_like_by_name(tag_list)
# else
# super
# end
# end
#
# @param [Array<String>] tag_list Tags to find or create
# @param [Symbol] context The tag context for the tag_list
def find_or_create_tags_from_list_with_context(tag_list, _context)
load_tags(tag_list)
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/taggable/collection.rb | lib/acts-as-taggable-on/taggable/collection.rb | # frozen_string_literal: true
module ActsAsTaggableOn
module Taggable
module Collection
extend ActiveSupport::Concern
included do
initialize_acts_as_taggable_on_collection
end
class_methods do
def initialize_acts_as_taggable_on_collection
tag_types.map(&:to_s).each do |tag_type|
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def self.#{tag_type.singularize}_counts(options={})
tag_counts_on('#{tag_type}', options)
end
def #{tag_type.singularize}_counts(options = {})
tag_counts_on('#{tag_type}', options)
end
def top_#{tag_type}(limit = 10)
tag_counts_on('#{tag_type}', order: 'count desc', limit: limit.to_i)
end
def self.top_#{tag_type}(limit = 10)
tag_counts_on('#{tag_type}', order: 'count desc', limit: limit.to_i)
end
RUBY
end
end
def acts_as_taggable_on(*args)
super(*args)
initialize_acts_as_taggable_on_collection
end
def tag_counts_on(context, options = {})
all_tag_counts(options.merge({ on: context.to_s }))
end
def tags_on(context, options = {})
all_tags(options.merge({ on: context.to_s }))
end
##
# Calculate the tag names.
# To be used when you don't need tag counts and want to avoid the taggable joins.
#
# @param [Hash] options Options:
# * :start_at - Restrict the tags to those created after a certain time
# * :end_at - Restrict the tags to those created before a certain time
# * :conditions - A piece of SQL conditions to add to the query. Note we don't join the taggable objects for performance reasons.
# * :limit - The maximum number of tags to return
# * :order - A piece of SQL to order by. Eg 'tags.count desc' or 'taggings.created_at desc'
# * :on - Scope the find to only include a certain context
def all_tags(options = {})
options = options.dup
options.assert_valid_keys :start_at, :end_at, :conditions, :order, :limit, :on
## Generate conditions:
options[:conditions] = sanitize_sql(options[:conditions]) if options[:conditions]
## Generate scope:
tagging_scope = ActsAsTaggableOn::Tagging.select("#{ActsAsTaggableOn::Tagging.table_name}.tag_id")
tag_scope = ActsAsTaggableOn::Tag.select("#{ActsAsTaggableOn::Tag.table_name}.*").order(options[:order]).limit(options[:limit])
# Joins and conditions
tagging_conditions(options).each { |condition| tagging_scope = tagging_scope.where(condition) }
tag_scope = tag_scope.where(options[:conditions])
group_columns = "#{ActsAsTaggableOn::Tagging.table_name}.tag_id"
# Append the current scope to the scope, because we can't use scope(:find) in RoR 3.0 anymore:
tagging_scope = generate_tagging_scope_in_clause(tagging_scope, table_name, primary_key).group(group_columns)
tag_scope_joins(tag_scope, tagging_scope)
end
##
# Calculate the tag counts for all tags.
#
# @param [Hash] options Options:
# * :start_at - Restrict the tags to those created after a certain time
# * :end_at - Restrict the tags to those created before a certain time
# * :conditions - A piece of SQL conditions to add to the query
# * :limit - The maximum number of tags to return
# * :order - A piece of SQL to order by. Eg 'tags.count desc' or 'taggings.created_at desc'
# * :at_least - Exclude tags with a frequency less than the given value
# * :at_most - Exclude tags with a frequency greater than the given value
# * :on - Scope the find to only include a certain context
def all_tag_counts(options = {})
options = options.dup
options.assert_valid_keys :start_at, :end_at, :conditions, :at_least, :at_most, :order, :limit, :on, :id
## Generate conditions:
options[:conditions] = sanitize_sql(options[:conditions]) if options[:conditions]
## Generate scope:
tagging_scope = ActsAsTaggableOn::Tagging.select("#{ActsAsTaggableOn::Tagging.table_name}.tag_id, COUNT(#{ActsAsTaggableOn::Tagging.table_name}.tag_id) AS tags_count")
tag_scope = ActsAsTaggableOn::Tag.select("#{ActsAsTaggableOn::Tag.table_name}.*, #{ActsAsTaggableOn::Tagging.table_name}.tags_count AS count").order(options[:order]).limit(options[:limit])
# Current model is STI descendant, so add type checking to the join condition
unless descends_from_active_record?
taggable_join = "INNER JOIN #{table_name} ON #{table_name}.#{primary_key} = #{ActsAsTaggableOn::Tagging.table_name}.taggable_id"
taggable_join = taggable_join + " AND #{table_name}.#{inheritance_column} = '#{name}'"
tagging_scope = tagging_scope.joins(taggable_join)
end
# Conditions
tagging_conditions(options).each { |condition| tagging_scope = tagging_scope.where(condition) }
tag_scope = tag_scope.where(options[:conditions])
# GROUP BY and HAVING clauses:
having = ["COUNT(#{ActsAsTaggableOn::Tagging.table_name}.tag_id) > 0"]
if options[:at_least]
having.push sanitize_sql(["COUNT(#{ActsAsTaggableOn::Tagging.table_name}.tag_id) >= ?",
options.delete(:at_least)])
end
if options[:at_most]
having.push sanitize_sql(["COUNT(#{ActsAsTaggableOn::Tagging.table_name}.tag_id) <= ?",
options.delete(:at_most)])
end
having = having.compact.join(' AND ')
group_columns = "#{ActsAsTaggableOn::Tagging.table_name}.tag_id"
unless options[:id]
# Append the current scope to the scope, because we can't use scope(:find) in RoR 3.0 anymore:
tagging_scope = generate_tagging_scope_in_clause(tagging_scope, table_name, primary_key)
end
tagging_scope = tagging_scope.group(group_columns).having(having)
tag_scope_joins(tag_scope, tagging_scope)
end
def safe_to_sql(relation)
if connection.respond_to?(:unprepared_statement)
connection.unprepared_statement do
relation.to_sql
end
else
relation.to_sql
end
end
private
def generate_tagging_scope_in_clause(tagging_scope, table_name, primary_key)
table_name_pkey = "#{table_name}.#{primary_key}"
if ActsAsTaggableOn::Utils.using_mysql?
# See https://github.com/mbleigh/acts-as-taggable-on/pull/457 for details
scoped_ids = pluck(table_name_pkey)
tagging_scope = tagging_scope.where("#{ActsAsTaggableOn::Tagging.table_name}.taggable_id IN (?)",
scoped_ids)
else
tagging_scope = tagging_scope.where("#{ActsAsTaggableOn::Tagging.table_name}.taggable_id IN(#{safe_to_sql(except(:select).select(table_name_pkey))})")
end
tagging_scope
end
def tagging_conditions(options)
tagging_conditions = []
if options[:end_at]
tagging_conditions.push sanitize_sql(["#{ActsAsTaggableOn::Tagging.table_name}.created_at <= ?",
options.delete(:end_at)])
end
if options[:start_at]
tagging_conditions.push sanitize_sql(["#{ActsAsTaggableOn::Tagging.table_name}.created_at >= ?",
options.delete(:start_at)])
end
taggable_conditions = sanitize_sql(["#{ActsAsTaggableOn::Tagging.table_name}.taggable_type = ?",
base_class.name])
if options[:on]
taggable_conditions << sanitize_sql([" AND #{ActsAsTaggableOn::Tagging.table_name}.context = ?",
options.delete(:on).to_s])
end
if options[:id]
taggable_conditions << if options[:id].is_a? Array
sanitize_sql([" AND #{ActsAsTaggableOn::Tagging.table_name}.taggable_id IN (?)",
options[:id]])
else
sanitize_sql([" AND #{ActsAsTaggableOn::Tagging.table_name}.taggable_id = ?",
options[:id]])
end
end
tagging_conditions.push taggable_conditions
tagging_conditions
end
def tag_scope_joins(tag_scope, tagging_scope)
tag_scope = tag_scope.joins("JOIN (#{safe_to_sql(tagging_scope)}) AS #{ActsAsTaggableOn::Tagging.table_name} ON #{ActsAsTaggableOn::Tagging.table_name}.tag_id = #{ActsAsTaggableOn::Tag.table_name}.id")
tag_scope.extending(CalculationMethods)
end
end
def tag_counts_on(context, options = {})
self.class.tag_counts_on(context, options.merge(id: id))
end
module CalculationMethods
# Rails 5 TODO: Remove options argument as soon we remove support to
# activerecord-deprecated_finders.
# See https://github.com/rails/rails/blob/master/activerecord/lib/active_record/relation/calculations.rb#L38
def count(column_name = :all, _options = {})
# https://github.com/rails/rails/commit/da9b5d4a8435b744fcf278fffd6d7f1e36d4a4f2
super(column_name)
end
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/taggable/related.rb | lib/acts-as-taggable-on/taggable/related.rb | # frozen_string_literal: true
module ActsAsTaggableOn
module Taggable
module Related
def self.included(base)
base.extend ActsAsTaggableOn::Taggable::Related::ClassMethods
base.initialize_acts_as_taggable_on_related
end
module ClassMethods
def initialize_acts_as_taggable_on_related
tag_types.map(&:to_s).each do |tag_type|
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def find_related_#{tag_type}(options = {})
related_tags_for('#{tag_type}', self.class, options)
end
alias_method :find_related_on_#{tag_type}, :find_related_#{tag_type}
def find_related_#{tag_type}_for(klass, options = {})
related_tags_for('#{tag_type}', klass, options)
end
RUBY
end
end
def acts_as_taggable_on(*args)
super(*args)
initialize_acts_as_taggable_on_related
end
end
def find_matching_contexts(search_context, result_context, options = {})
matching_contexts_for(search_context.to_s, result_context.to_s, self.class, options)
end
def find_matching_contexts_for(klass, search_context, result_context, options = {})
matching_contexts_for(search_context.to_s, result_context.to_s, klass, options)
end
def matching_contexts_for(search_context, result_context, klass, _options = {})
tags_to_find = tags_on(search_context).map(&:name)
related_where(klass,
[
"#{exclude_self(klass,
id)} #{klass.table_name}.#{klass.primary_key} = #{ActsAsTaggableOn::Tagging.table_name}.taggable_id AND #{ActsAsTaggableOn::Tagging.table_name}.taggable_type = '#{klass.base_class}' AND #{ActsAsTaggableOn::Tagging.table_name}.tag_id = #{ActsAsTaggableOn::Tag.table_name}.#{ActsAsTaggableOn::Tag.primary_key} AND #{ActsAsTaggableOn::Tag.table_name}.name IN (?) AND #{ActsAsTaggableOn::Tagging.table_name}.context = ?", tags_to_find, result_context
])
end
def related_tags_for(context, klass, options = {})
tags_to_ignore = Array.wrap(options[:ignore]).map(&:to_s) || []
tags_to_find = tags_on(context).map(&:name).reject { |t| tags_to_ignore.include? t }
related_where(klass,
[
"#{exclude_self(klass,
id)} #{klass.table_name}.#{klass.primary_key} = #{ActsAsTaggableOn::Tagging.table_name}.taggable_id AND #{ActsAsTaggableOn::Tagging.table_name}.taggable_type = '#{klass.base_class}' AND #{ActsAsTaggableOn::Tagging.table_name}.tag_id = #{ActsAsTaggableOn::Tag.table_name}.#{ActsAsTaggableOn::Tag.primary_key} AND #{ActsAsTaggableOn::Tag.table_name}.name IN (?) AND #{ActsAsTaggableOn::Tagging.table_name}.context = ?", tags_to_find, context
])
end
private
def exclude_self(klass, id)
"#{klass.arel_table[klass.primary_key].not_eq(id).to_sql} AND" if [self.class.base_class,
self.class].include? klass
end
def group_columns(klass)
if ActsAsTaggableOn::Utils.using_postgresql?
grouped_column_names_for(klass)
else
"#{klass.table_name}.#{klass.primary_key}"
end
end
def related_where(klass, conditions)
klass.select("#{klass.table_name}.*, COUNT(#{ActsAsTaggableOn::Tag.table_name}.#{ActsAsTaggableOn::Tag.primary_key}) AS count")
.from("#{klass.table_name}, #{ActsAsTaggableOn::Tag.table_name}, #{ActsAsTaggableOn::Tagging.table_name}")
.group(group_columns(klass))
.order('count DESC')
.where(conditions)
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/taggable/tagged_with_query.rb | lib/acts-as-taggable-on/taggable/tagged_with_query.rb | # frozen_string_literal: true
module ActsAsTaggableOn
module Taggable
module TaggedWithQuery
def self.build(taggable_model, tag_model, tagging_model, tag_list, options)
if options[:exclude].present?
ExcludeTagsQuery.new(taggable_model, tag_model, tagging_model, tag_list, options).build
elsif options[:any].present?
AnyTagsQuery.new(taggable_model, tag_model, tagging_model, tag_list, options).build
else
AllTagsQuery.new(taggable_model, tag_model, tagging_model, tag_list, options).build
end
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/taggable/tag_list_type.rb | lib/acts-as-taggable-on/taggable/tag_list_type.rb | # frozen_string_literal: true
module ActsAsTaggableOn
module Taggable
class TagListType < ActiveModel::Type::Value
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/taggable/ownership.rb | lib/acts-as-taggable-on/taggable/ownership.rb | # frozen_string_literal: true
module ActsAsTaggableOn
module Taggable
module Ownership
extend ActiveSupport::Concern
included do
after_save :save_owned_tags
initialize_acts_as_taggable_on_ownership
end
class_methods do
def acts_as_taggable_on(*args)
initialize_acts_as_taggable_on_ownership
super(*args)
end
def initialize_acts_as_taggable_on_ownership
tag_types.map(&:to_s).each do |tag_type|
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{tag_type}_from(owner)
owner_tag_list_on(owner, '#{tag_type}')
end
RUBY
end
end
end
def owner_tags(owner)
scope = if owner.nil?
base_tags
else
base_tags.where(
ActsAsTaggableOn::Tagging.table_name.to_s => {
tagger_id: owner.id,
tagger_type: owner.class.base_class.to_s
}
)
end
# when preserving tag order, return tags in created order
# if we added the order to the association this would always apply
if self.class.preserve_tag_order?
scope.order("#{ActsAsTaggableOn::Tagging.table_name}.id")
else
scope
end
end
def owner_tags_on(owner, context)
owner_tags(owner).where(
ActsAsTaggableOn::Tagging.table_name.to_s => {
context: context
}
)
end
def cached_owned_tag_list_on(context)
variable_name = "@owned_#{context}_list"
(instance_variable_defined?(variable_name) && instance_variable_get(variable_name)) || instance_variable_set(
variable_name, {}
)
end
def owner_tag_list_on(owner, context)
add_custom_context(context)
cache = cached_owned_tag_list_on(context)
cache[owner] ||= ActsAsTaggableOn::TagList.new(*owner_tags_on(owner, context).map(&:name))
end
def set_owner_tag_list_on(owner, context, new_list)
add_custom_context(context)
cache = cached_owned_tag_list_on(context)
cache[owner] = ActsAsTaggableOn.default_parser.new(new_list).parse
end
def reload(*args)
self.class.tag_types.each do |context|
instance_variable_set("@owned_#{context}_list", nil)
end
super(*args)
end
def save_owned_tags
tagging_contexts.each do |context|
cached_owned_tag_list_on(context).each do |owner, tag_list|
# Find existing tags or create non-existing tags:
tags = find_or_create_tags_from_list_with_context(tag_list.uniq, context)
# Tag objects for owned tags
owned_tags = owner_tags_on(owner, context).to_a
# Tag maintenance based on whether preserving the created order of tags
old_tags = owned_tags - tags
new_tags = tags - owned_tags
if self.class.preserve_tag_order?
shared_tags = owned_tags & tags
if shared_tags.any? && tags[0...shared_tags.size] != shared_tags
index = shared_tags.each_with_index do |_, i|
break i unless shared_tags[i] == tags[i]
end
# Update arrays of tag objects
old_tags |= owned_tags.from(index)
new_tags |= owned_tags.from(index) & shared_tags
# Order the array of tag objects to match the tag list
new_tags = tags.map do |t|
new_tags.find do |n|
n.name.downcase == t.name.downcase
end
end.compact
end
else
# Delete discarded tags and create new tags
end
# Find all taggings that belong to the taggable (self), are owned by the owner,
# have the correct context, and are removed from the list.
if old_tags.present?
ActsAsTaggableOn::Tagging.where(taggable_id: id, taggable_type: self.class.base_class.to_s,
tagger_type: owner.class.base_class.to_s, tagger_id: owner.id,
tag_id: old_tags, context: context).destroy_all
end
# Create new taggings:
new_tags.each do |tag|
taggings.create!(tag_id: tag.id, context: context.to_s, tagger: owner, taggable: self)
end
end
end
true
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/taggable/caching.rb | lib/acts-as-taggable-on/taggable/caching.rb | # frozen_string_literal: true
module ActsAsTaggableOn
module Taggable
module Caching
extend ActiveSupport::Concern
included do
initialize_tags_cache
before_save :save_cached_tag_list
end
class_methods do
def initialize_tags_cache
tag_types.map(&:to_s).each do |tag_type|
define_singleton_method("caching_#{tag_type.singularize}_list?") do
caching_tag_list_on?(tag_type)
end
end
end
def acts_as_taggable_on(*args)
super(*args)
initialize_tags_cache
end
def caching_tag_list_on?(context)
column_names.include?("cached_#{context.to_s.singularize}_list")
end
end
def save_cached_tag_list
tag_types.map(&:to_s).each do |tag_type|
next unless self.class.respond_to?("caching_#{tag_type.singularize}_list?")
if self.class.send("caching_#{tag_type.singularize}_list?") && tag_list_cache_set_on(tag_type)
list = tag_list_cache_on(tag_type).to_a.flatten.compact.join("#{ActsAsTaggableOn.delimiter} ")
self["cached_#{tag_type.singularize}_list"] = list
end
end
true
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/taggable/tagged_with_query/exclude_tags_query.rb | lib/acts-as-taggable-on/taggable/tagged_with_query/exclude_tags_query.rb | # frozen_string_literal: true
module ActsAsTaggableOn
module Taggable
module TaggedWithQuery
class ExcludeTagsQuery < QueryBase
def build
taggable_model.joins(owning_to_tagger)
.where(tags_not_in_list)
.having(tags_that_matches_count)
.readonly(false)
end
private
def tags_not_in_list
taggable_arel_table[:id].not_in(
tagging_arel_table
.project(tagging_arel_table[:taggable_id])
.join(tag_arel_table)
.on(
tagging_arel_table[:tag_id].eq(tag_arel_table[:id])
.and(tagging_arel_table[:taggable_type].eq(taggable_model.base_class.name))
.and(tags_match_type)
)
)
# FIXME: missing time scope, this is also missing in the original implementation
end
def owning_to_tagger
return [] if options[:owned_by].blank?
owner = options[:owned_by]
arel_join = taggable_arel_table
.join(tagging_arel_table)
.on(
tagging_arel_table[:tagger_id].eq(owner.id)
.and(tagging_arel_table[:tagger_type].eq(owner.class.base_class.to_s))
.and(tagging_arel_table[:taggable_id].eq(taggable_arel_table[taggable_model.primary_key]))
.and(tagging_arel_table[:taggable_type].eq(taggable_model.base_class.name))
)
if options[:match_all].present?
arel_join = arel_join
.join(tagging_arel_table, Arel::Nodes::OuterJoin)
.on(
match_all_on_conditions
)
end
arel_join.join_sources
end
def match_all_on_conditions
on_condition = tagging_arel_table[:taggable_id].eq(taggable_arel_table[taggable_model.primary_key])
.and(tagging_arel_table[:taggable_type].eq(taggable_model.base_class.name))
if options[:start_at].present?
on_condition = on_condition.and(tagging_arel_table[:created_at].gteq(options[:start_at]))
end
if options[:end_at].present?
on_condition = on_condition.and(tagging_arel_table[:created_at].lteq(options[:end_at]))
end
on_condition = on_condition.and(tagging_arel_table[:context].eq(options[:on])) if options[:on].present?
on_condition
end
def tags_that_matches_count
return [] if options[:match_all].blank?
taggable_model.find_by_sql(tag_arel_table.project(Arel.star.count).where(tags_match_type).to_sql)
tagging_arel_table[:taggable_id].count.eq(
tag_arel_table.project(Arel.star.count).where(tags_match_type)
)
end
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/taggable/tagged_with_query/query_base.rb | lib/acts-as-taggable-on/taggable/tagged_with_query/query_base.rb | # frozen_string_literal: true
module ActsAsTaggableOn
module Taggable
module TaggedWithQuery
class QueryBase
def initialize(taggable_model, tag_model, tagging_model, tag_list, options)
@taggable_model = taggable_model
@tag_model = tag_model
@tagging_model = tagging_model
@tag_list = tag_list
@options = options
end
private
attr_reader :taggable_model, :tag_model, :tagging_model, :tag_list, :options
def taggable_arel_table
@taggable_arel_table ||= taggable_model.arel_table
end
def tag_arel_table
@tag_arel_table ||= tag_model.arel_table
end
def tagging_arel_table
@tagging_arel_table ||= tagging_model.arel_table
end
def tag_match_type(tag)
matches_attribute = tag_arel_table[:name]
matches_attribute = matches_attribute.lower unless ActsAsTaggableOn.strict_case_match
if options[:wild].present?
matches_attribute.matches(wildcard_escaped_tag(tag), '!', ActsAsTaggableOn.strict_case_match)
else
matches_attribute.matches(escaped_tag(tag), '!', ActsAsTaggableOn.strict_case_match)
end
end
def tags_match_type
matches_attribute = tag_arel_table[:name]
matches_attribute = matches_attribute.lower unless ActsAsTaggableOn.strict_case_match
if options[:wild].present?
matches_attribute.matches_any(tag_list.map do |tag|
wildcard_escaped_tag(tag)
end, '!', ActsAsTaggableOn.strict_case_match)
else
matches_attribute.matches_any(tag_list.map do |tag|
escaped_tag(tag).to_s
end, '!', ActsAsTaggableOn.strict_case_match)
end
end
def escaped_tag(tag)
tag = tag.downcase unless ActsAsTaggableOn.strict_case_match
ActsAsTaggableOn::Utils.escape_like(tag)
end
def wildcard_escaped_tag(tag)
case options[:wild]
when :suffix then "#{escaped_tag(tag)}%"
when :prefix then "%#{escaped_tag(tag)}"
when true then "%#{escaped_tag(tag)}%"
else escaped_tag(tag)
end
end
def adjust_taggings_alias(taggings_alias)
taggings_alias = "taggings_alias_#{Digest::SHA1.hexdigest(taggings_alias)}" if taggings_alias.size > 75
taggings_alias
end
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/taggable/tagged_with_query/all_tags_query.rb | lib/acts-as-taggable-on/taggable/tagged_with_query/all_tags_query.rb | # frozen_string_literal: true
module ActsAsTaggableOn
module Taggable
module TaggedWithQuery
class AllTagsQuery < QueryBase
def build
taggable_model.joins(each_tag_in_list)
.group(by_taggable)
.having(tags_that_matches_count)
.order(order_conditions)
.readonly(false)
end
private
def each_tag_in_list
arel_join = taggable_arel_table
tag_list.each do |tag|
tagging_alias = tagging_arel_table.alias(tagging_alias(tag))
arel_join = arel_join
.join(tagging_alias)
.on(on_conditions(tag, tagging_alias))
end
if options[:match_all].present?
arel_join = arel_join
.join(tagging_arel_table, Arel::Nodes::OuterJoin)
.on(
match_all_on_conditions
)
end
arel_join.join_sources
end
def on_conditions(tag, tagging_alias)
on_condition = tagging_alias[:taggable_id].eq(taggable_arel_table[taggable_model.primary_key])
.and(tagging_alias[:taggable_type].eq(taggable_model.base_class.name))
.and(
tagging_alias[:tag_id].in(
tag_arel_table.project(tag_arel_table[:id]).where(tag_match_type(tag))
)
)
if options[:start_at].present?
on_condition = on_condition.and(tagging_alias[:created_at].gteq(options[:start_at]))
end
if options[:end_at].present?
on_condition = on_condition.and(tagging_alias[:created_at].lteq(options[:end_at]))
end
on_condition = on_condition.and(tagging_alias[:context].eq(options[:on])) if options[:on].present?
if (owner = options[:owned_by]).present?
on_condition = on_condition.and(tagging_alias[:tagger_id].eq(owner.id))
.and(tagging_alias[:tagger_type].eq(owner.class.base_class.to_s))
end
on_condition
end
def match_all_on_conditions
on_condition = tagging_arel_table[:taggable_id].eq(taggable_arel_table[taggable_model.primary_key])
.and(tagging_arel_table[:taggable_type].eq(taggable_model.base_class.name))
if options[:start_at].present?
on_condition = on_condition.and(tagging_arel_table[:created_at].gteq(options[:start_at]))
end
if options[:end_at].present?
on_condition = on_condition.and(tagging_arel_table[:created_at].lteq(options[:end_at]))
end
on_condition = on_condition.and(tagging_arel_table[:context].eq(options[:on])) if options[:on].present?
on_condition
end
def by_taggable
return [] if options[:match_all].blank?
taggable_arel_table[taggable_model.primary_key]
end
def tags_that_matches_count
return [] if options[:match_all].blank?
taggable_model.find_by_sql(tag_arel_table.project(Arel.star.count).where(tags_match_type).to_sql)
tagging_arel_table[:taggable_id].count.eq(
tag_arel_table.project(Arel.star.count).where(tags_match_type)
)
end
def order_conditions
order_by = []
if options[:order_by_matching_tag_count].present? && options[:match_all].blank?
order_by << tagging_arel_table.project(tagging_arel_table[Arel.star].count.as('taggings_count')).order('taggings_count DESC').to_sql
end
order_by << options[:order] if options[:order].present?
order_by.join(', ')
end
def tagging_alias(tag)
alias_base_name = taggable_model.base_class.name.downcase
adjust_taggings_alias("#{alias_base_name[0..11]}_taggings_#{ActsAsTaggableOn::Utils.sha_prefix(tag)}")
end
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
mbleigh/acts-as-taggable-on | https://github.com/mbleigh/acts-as-taggable-on/blob/380c0bc4fd7e2c043593d8411250aba268101672/lib/acts-as-taggable-on/taggable/tagged_with_query/any_tags_query.rb | lib/acts-as-taggable-on/taggable/tagged_with_query/any_tags_query.rb | # frozen_string_literal: true
module ActsAsTaggableOn
module Taggable
module TaggedWithQuery
class AnyTagsQuery < QueryBase
def build
taggable_model.select(all_fields)
.where(model_has_at_least_one_tag)
.order(Arel.sql(order_conditions))
.readonly(false)
end
private
def all_fields
taggable_arel_table[Arel.star]
end
def model_has_at_least_one_tag
tagging_arel_table.project(Arel.star).where(at_least_one_tag).exists
end
def at_least_one_tag
exists_contition = tagging_arel_table[:taggable_id].eq(taggable_arel_table[taggable_model.primary_key])
.and(tagging_arel_table[:taggable_type].eq(taggable_model.base_class.name))
.and(
tagging_arel_table[:tag_id].in(
tag_arel_table.project(tag_arel_table[:id]).where(tags_match_type)
)
)
if options[:start_at].present?
exists_contition = exists_contition.and(tagging_arel_table[:created_at].gteq(options[:start_at]))
end
if options[:end_at].present?
exists_contition = exists_contition.and(tagging_arel_table[:created_at].lteq(options[:end_at]))
end
if options[:on].present?
exists_contition = exists_contition.and(tagging_arel_table[:context].eq(options[:on]))
end
if (owner = options[:owned_by]).present?
exists_contition = exists_contition.and(tagging_arel_table[:tagger_id].eq(owner.id))
.and(tagging_arel_table[:tagger_type].eq(owner.class.base_class.to_s))
end
exists_contition
end
def order_conditions
order_by = []
if options[:order_by_matching_tag_count].present?
order_by << "(SELECT count(*) FROM #{tagging_model.table_name} WHERE #{at_least_one_tag.to_sql}) desc"
end
order_by << options[:order] if options[:order].present?
order_by.join(', ')
end
def alias_name(tag_list)
alias_base_name = taggable_model.base_class.name.downcase
taggings_context = options[:on] ? "_#{options[:on]}" : ''
adjust_taggings_alias(
"#{alias_base_name[0..4]}#{taggings_context[0..6]}_taggings_#{ActsAsTaggableOn::Utils.sha_prefix(tag_list.join('_'))}"
)
end
end
end
end
end
| ruby | MIT | 380c0bc4fd7e2c043593d8411250aba268101672 | 2026-01-04T15:44:35.730653Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/integration/spec_helper.rb | integration/spec_helper.rb | # encoding: utf-8
require "backup"
Dir[File.expand_path("../support/**/*.rb", __FILE__)].each { |f| require f }
RSpec.configure do |c|
c.include BackupSpec::ExampleHelpers
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/integration/tasks/fileset_builder.rb | integration/tasks/fileset_builder.rb | # encoding: utf-8
class FilesetBuilder
def create(root_dir, dir_name, total, file_size)
create_dir(root_dir, dir_name)
create_fileset(File.join(root_dir, dir_name), total, file_size)
end
def create_dir(parent_dir, dir_name)
dir = File.join(parent_dir, dir_name)
Dir.mkdir(dir) unless Dir.exist?(dir)
end
def create_file(file_path, file_size)
File.open(file_path, "w") do |file|
contents = "x" * (1024 * 1024)
file_size.to_i.times { file.write(contents) }
end
end
def create_fileset(dir, total, file_size)
count = 0
total.times do
count += 1
file_name = "#{count}.txt"
file_path = File.join(dir, file_name)
create_file(file_path, file_size)
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/integration/support/logger.rb | integration/support/logger.rb | # encoding: utf-8
module Backup
class Logger
class << self
alias _clear! clear!
def clear!
saved << logger
_clear!
end
def saved
@saved ||= []
end
private
alias _reset! reset!
def reset!
@saved = nil
_reset!
end
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/integration/support/package.rb | integration/support/package.rb | # encoding: utf-8
module BackupSpec
class Package
include Backup::Utilities::Helpers
extend Forwardable
def_delegators :tarfile, :manifest, :contents, :[]
attr_reader :model
def initialize(model)
@model = model
end
def exist?
!files.empty? && files.all? { |f| File.exist?(f) }
end
def path
@path ||= unsplit
end
# Note that once the package is inspected with the match_manifest matcher,
# a Tarfile will be created. If the Splitter was used, this will create an
# additional file (the re-joined tar) in the remote_path. If #[] is used,
# the package will be extracted into the remote_path. Some cycling
# operations remove each package file, then the timestamp directory which
# should be empty at that point. So you can"t inspect a split package"s
# manifest or inspect tar files within the package when testing cycling.
def removed?
files.all? { |f| !File.exist?(f) }
end
# If a trigger is run multiple times within a test (like when testing cycling),
# multiple packages will exist under different timestamp folders.
# This allows us to find the package files for the specific model given.
#
# For most tests the Local storage is used, which will have a remote_path
# that"s already expanded. Others like SCP, RSync (:ssh mode), etc... will
# have a remote_path that"s relative to the vagrant user"s home.
# The exception is the RSync daemon modes, where remote_path will begin
# with daemon module names, which are mapped to the vagrant user"s home.
def files
@files ||= begin
storage = model.storages.first
return [] unless storage # model didn"t store anything
path = storage.send(:remote_path)
unless path == File.expand_path(path)
path.sub!(/(ssh|rsync)-daemon-module/, "")
path = File.expand_path(File.join("tmp", path))
end
Dir[File.join(path, "#{model.trigger}.tar*")].sort
end
end
private
def tarfile
@tarfile ||= TarFile.new(path)
end
def unsplit
return files.first unless files.count > 1
base_dir = File.dirname(files.first)
orig_ext = File.extname(files.first)
base_ext = orig_ext.split("-").first
outfile = File.basename(files.first).sub(/#{ orig_ext }$/, base_ext)
Dir.chdir(base_dir) do
`#{ utility(:cat) } #{ outfile }-* > #{ outfile }`
end
File.join(base_dir, outfile)
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/integration/support/match_manifest.rb | integration/support/match_manifest.rb | # encoding: utf-8
# Matches the contents of a TarFile (or PerformedJob.package)
# against the given manifest.
#
# Usage:
#
# performed_job = backup_perform :trigger
#
# expect(performed_job.package).to match_manifest(<<-EOS)
# 51200 my_backup/archives/my_archive.tar
# 8099 my_backup/databases/MySQL/backup_test_01.sql
# EOS
#
# File sizes may also be tested against a range, using `min..max`.
#
# expect(performed_job.package).to match_manifest(%q[
# 51200..51250 my_backup/archives/my_archive.tar
# 8099 my_backup/databases/MySQL/backup_test_01.sql
# ])
#
# Or simply checked for existance, using `-`:
#
# expect(performed_job.package).to match_manifest(%q[
# - my_backup/archives/my_archive.tar
# 8099 my_backup/databases/MySQL/backup_test_01.sql
# ])
#
# Extra spaces and blank lines are ok.
#
# If the given files with the given sizes do not match all the files
# in the archive"s manifest, the error message will include the entire
# manifest as output by `tar -tvf`.
RSpec::Matchers.define :match_manifest do |expected|
match do |actual|
expected_contents = expected.split("\n").map(&:strip).reject(&:empty?)
expected_contents.map! { |line| line.split(" ") }
expected_contents = Hash[
expected_contents.map { |fields| [fields[1], fields[0]] }
]
files_match = expected_contents.keys.sort == actual.contents.keys.sort
if files_match
sizes_ok = true
expected_contents.each do |path, size|
actual_size = actual.contents[path]
sizes_ok =
case size
when "-" then true
when /\d+(\.\.)\d+/
a, b = size.split("..").map(&:to_i)
(a..b).cover? actual_size
else
size.to_i == actual_size
end
break unless sizes_ok
end
end
files_match && sizes_ok
end
failure_message do |actual|
"expected that:\n\n#{actual.manifest}\n" \
"would match:\n#{expected}"
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/integration/support/example_helpers.rb | integration/support/example_helpers.rb | # encoding: utf-8
module BackupSpec
CONFIG_TEMPLATE = Backup::Template.new.result("cli/config")
PROJECT_ROOT = "/usr/src/backup".freeze
LOCAL_STORAGE_PATH = File.join(PROJECT_ROOT, "tmp", "Storage")
module ExampleHelpers
# Creates the config.rb file.
#
# By default, this will be created as ~/Backup/config.rb,
# since Backup::Config is reset before each example.
#
# If paths will be changed when calling backup_perform(),
# like --config-file or --root-path, then the full path to
# the config file must be given here in +config_file+.
#
# The config file created here will disable console log output
# and file logging, but this may be overridden in +text+.
#
# Note that the first line in +text+ will set the indent for the text being
# given and that indent will be removed from all lines in +text+
#
# If you don"t intend to change the default config.rb contents or path,
# you can omit this method from your example. Calling create_model()
# will call this method if the +config_file+ does not exist.
def create_config(text = nil, config_file = nil)
config_file ||= Backup::Config.config_file
config_path = File.dirname(config_file)
unless text.to_s.empty?
indent = text.lines.first.match(/^ */)[0].length
text = text.lines.map { |l| l[indent..-1] }.join
end
config = <<-EOS.gsub(/^ /, "")
# encoding: utf-8
Backup::Utilities.configure do
# silence the log output produced by the auto-detection
tar_dist :gnu
end
Backup::Logger.configure do
console.quiet = true
logfile.enabled = false
end
Backup::Storage::Local.defaults do |local|
local.path = "#{LOCAL_STORAGE_PATH}"
end
#{text}
#{CONFIG_TEMPLATE}
EOS
# Create models path, since models are always relative to the config file.
FileUtils.mkdir_p File.join(config_path, "models")
File.open(config_file, "w") { |f| f.write config }
end
# Creates a model file.
#
# Pass +config_file+ if it won"t be at the default path +~/Backup/+.
#
# Creates the model as +/models/<trigger>.rb+, relative to the path
# of +config_file+.
#
# Note that the first line in +text+ will set the indent for the text being
# given and that indent will be removed from all lines in +text+
def create_model(trigger, text, config_file = nil)
config_file ||= Backup::Config.config_file
model_path = File.join(File.dirname(config_file), "models")
model_file = File.join(model_path, trigger.to_s + ".rb")
create_config(nil, config_file) unless File.exist?(config_file)
indent = text.lines.first.match(/^ */)[0].length
text = text.lines.map { |l| l[indent..-1] }.join
config = <<-EOS.gsub(/^ /, "")
# encoding: utf-8
#{text}
EOS
File.open(model_file, "w") { |f| f.write config }
end
# Runs the given trigger(s).
#
# Any +options+ given are passed as command line options to the
# `backup perform` command. These should be given as String arguments.
# e.g. job = backup_perform :my_backup, "--tmp-path=/tmp"
#
# The last argument given for +options+ may be a Hash, which is used
# as options for this method. If { :exit_status => Integer } is set,
# this method will rescue SystemExit and assert that the exit status
# is correct. This allows jobs that log warnings to continue and return
# the performed job(s).
#
# When :focus is added to an example, "--no-quiet" will be appended to
# +options+ so you can see the log output as the backup is performed.
def backup_perform(triggers, *options)
triggers = Array(triggers).map(&:to_s)
opts = options.last.is_a?(Hash) ? options.pop : {}
exit_status = opts.delete(:exit_status)
argv = ["perform", "-t", triggers.join(",")] + options
# Reset config paths, utility paths and the logger.
Backup::Config.send(:reset!)
Backup::Utilities.send(:reset!)
Backup::Logger.send(:reset!)
# Ensure multiple runs have different timestamps
sleep 1 unless Backup::Model.all.empty?
# Clear previously loaded models and other class instance variables
Backup::Model.send(:reset!)
ARGV.replace(argv)
if exit_status
expect do
Backup::CLI.start
end.to raise_error(SystemExit) { |exit|
expect(exit.status).to be(exit_status)
}
else
Backup::CLI.start
end
models = triggers.map { |t| Backup::Model.find_by_trigger(t).first }
jobs = models.map { |m| BackupSpec::PerformedJob.new(m) }
jobs.count > 1 ? jobs : jobs.first
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/integration/support/performed_job.rb | integration/support/performed_job.rb | # encoding: utf-8
module BackupSpec
class PerformedJob
attr_reader :model, :logger, :package
def initialize(model)
@model = model
@logger = Backup::Logger.saved.shift
@package = Package.new(model)
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/integration/support/tarfile.rb | integration/support/tarfile.rb | # encoding: utf-8
module BackupSpec
class TarFile
include Backup::Utilities::Helpers
attr_reader :path
def initialize(path)
@path = path
end
def manifest
@manifest ||= begin
if File.exist?(path.to_s)
`#{ utility(:tar) } -tvf #{ path } 2>/dev/null`
else
""
end
end
end
# GNU/BSD have different formats for `tar -tvf`.
#
# Returns a Hash of { "path" => size } for only the files in the manifest.
def contents
@contents ||= begin
data = manifest.split("\n").reject { |line| line =~ %r{\/$} }
data.map! { |line| line.split(" ") }
if gnu_tar?
Hash[data.map { |fields| [fields[5], fields[2].to_i] }]
else
Hash[data.map { |fields| [fields[8], fields[4].to_i] }]
end
end
end
def [](val)
extracted_files[val]
end
private
# Return a Hash with the paths from #contents mapped to either another
# TarFile object (for tar files) or the full path to the extracted file.
def extracted_files
@extracted_files ||= begin
base_path = File.dirname(path)
filename = File.basename(path)
Dir.chdir(base_path) do
`#{ utility(:tar) } -xf #{ filename } 2>/dev/null`
end
Hash[
contents.keys.map do |manifest_path|
path = File.join(base_path, manifest_path.sub(%r{^\/}, ""))
if path =~ /\.tar.*$/
[manifest_path, self.class.new(path)]
else
[manifest_path, path]
end
end
]
end
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/integration/acceptance/archive_spec.rb | integration/acceptance/archive_spec.rb | # encoding: utf-8
require File.expand_path("../../spec_helper", __FILE__)
module Backup
describe Archive do
specify "All directories, no compression, without :root" do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
archive :archive_a do |archive|
archive.add "./tmp/test_data"
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect(job.package.exist?).to be true
expect(job.package).to match_manifest(<<-EOS)
10_496_000 my_backup/archives/archive_a.tar
EOS
package_a = job.package["my_backup/archives/archive_a.tar"]
expect(package_a).to match_manifest(<<-EOS)
1_048_576 /usr/src/backup/tmp/test_data/dir_a/1.txt
1_048_576 /usr/src/backup/tmp/test_data/dir_a/2.txt
1_048_576 /usr/src/backup/tmp/test_data/dir_a/3.txt
1_048_576 /usr/src/backup/tmp/test_data/dir_b/1.txt
1_048_576 /usr/src/backup/tmp/test_data/dir_b/2.txt
1_048_576 /usr/src/backup/tmp/test_data/dir_b/3.txt
1_048_576 /usr/src/backup/tmp/test_data/dir_c/1.txt
1_048_576 /usr/src/backup/tmp/test_data/dir_c/2.txt
1_048_576 /usr/src/backup/tmp/test_data/dir_c/3.txt
1_048_576 /usr/src/backup/tmp/test_data/dir_d/1.txt
EOS
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/integration/acceptance/splitter_spec.rb | integration/acceptance/splitter_spec.rb | require File.expand_path("../../spec_helper", __FILE__)
describe Backup::Splitter do
specify "suffix length may be configured" do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, "a description") do
split_into_chunks_of 1, 5
archive :my_archive do |archive|
archive.add "./tmp/test_data"
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect(job.package.exist?).to be true
expect(job.package.files.count).to be(11)
expect(job.package.files.first).to end_with("-aaaaa")
expect(job.package).to match_manifest(
"- my_backup/archives/my_archive.tar"
)
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/spec_helper.rb | vagrant/spec/spec_helper.rb | abort "These specs should only be run on the backup-testbox VM" unless
%x[hostname].chomp == 'backup-testbox'
version = '9'
found = File.read('/home/vagrant/backup-testbox-version').strip rescue '?'
warn(<<EOS) unless version == found
\n -- Warning: backup-testbox should be v.#{ version } - Found v.#{ found } --
EOS
require 'bundler/setup'
require 'backup'
Dir[File.expand_path('../support/**/*.rb', __FILE__)].each {|f| require f }
require 'rspec/autorun'
RSpec.configure do |config|
config.treat_symbols_as_metadata_keys_with_true_values = true
config.run_all_when_everything_filtered = true
config.filter_run_excluding :live
config.filter_run :focus
config.include BackupSpec::ExampleHelpers
config.before(:each) do
# Reset to default paths
Backup::Config.send(:reset!)
# Remove default and alt config paths if they exist.
FileUtils.rm_rf File.dirname(Backup::Config.config_file)
FileUtils.rm_rf BackupSpec::ALT_CONFIG_PATH
# Remove the local storage path if it exists.
FileUtils.rm_rf BackupSpec::LOCAL_STORAGE_PATH
@argv_save = ARGV
end
# The last spec example to run will leave behind it's files in the
# LOCAL_STORAGE_PATH (if used) and it's config.rb and model files
# in either the default path (~/Backup) or the alt path (~/Backup_alt)
# so these files may be inspected if needed.
#
# Adding `:focus` to spec examples will automatically enable the
# Console Logger so you can see the log output as the job runs.
config.after(:each) do
ARGV.replace(@argv_save)
end
end
puts "\nRuby version: #{ RUBY_DESCRIPTION }\n\n"
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/support/logger.rb | vagrant/spec/support/logger.rb | module Backup
class Logger
class << self
alias _clear! clear!
def clear!
saved << logger
_clear!
end
def saved
@saved ||= []
end
private
alias _reset! reset!
def reset!
@saved = nil
_reset!
end
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/support/package.rb | vagrant/spec/support/package.rb | module BackupSpec
class Package
include Backup::Utilities::Helpers
extend Forwardable
def_delegators :tarfile, :manifest, :contents, :[]
attr_reader :model
def initialize(model)
@model = model
end
def exist?
!files.empty? && files.all? {|f| File.exist?(f) }
end
def path
@path ||= unsplit
end
# Note that once the package is inspected with the match_manifest matcher,
# a Tarfile will be created. If the Splitter was used, this will create an
# additional file (the re-joined tar) in the remote_path. If #[] is used,
# the package will be extracted into the remote_path. Some cycling
# operations remove each package file, then the timestamp directory which
# should be empty at that point. So you can't inspect a split package's
# manifest or inspect tar files within the package when testing cycling.
def removed?
files.all? {|f| !File.exist?(f) }
end
# If a trigger is run multiple times within a test (like when testing cycling),
# multiple packages will exist under different timestamp folders.
# This allows us to find the package files for the specific model given.
#
# For most tests the Local storage is used, which will have a remote_path
# that's already expanded. Others like SCP, RSync (:ssh mode), etc... will
# have a remote_path that's relative to the vagrant user's home.
# The exception is the RSync daemon modes, where remote_path will begin
# with daemon module names, which are mapped to the vagrant user's home.
def files
@files ||= begin
storage = model.storages.first
return [] unless storage # model didn't store anything
path = storage.send(:remote_path)
unless path == File.expand_path(path)
path.sub!(/(ssh|rsync)-daemon-module/, '')
path = File.expand_path(File.join('~/', path))
end
Dir[File.join(path, "#{ model.trigger }.tar*")].sort
end
end
private
def tarfile
@tarfile ||= TarFile.new(path)
end
def unsplit
return files.first unless files.count > 1
base_dir = File.dirname(files.first)
orig_ext = File.extname(files.first)
base_ext = orig_ext.split('-').first
outfile = File.basename(files.first).sub(/#{ orig_ext }$/, base_ext)
Dir.chdir(base_dir) do
%x[#{ utility(:cat) } #{ outfile }-* > #{ outfile }]
end
File.join(base_dir, outfile)
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/support/example_helpers.rb | vagrant/spec/support/example_helpers.rb | module BackupSpec
PROJECT_ROOT = '/backup.git'
CONFIG_TEMPLATE = Backup::Template.new.result('cli/config')
LOCAL_STORAGE_PATH = '/home/vagrant/Storage'
ALT_CONFIG_PATH = '/home/vagrant/Backup_alt'
LOCAL_SYNC_PATH = '/home/vagrant/sync_root'
GPG_HOME_DIR = '/home/vagrant/gpg_home' # default would be ~/.gnupg
module ExampleHelpers
# Creates the config.rb file.
#
# By default, this will be created as ~/Backup/config.rb,
# since Backup::Config is reset before each example.
#
# If paths will be changed when calling backup_perform(),
# like --config-file or --root-path, then the full path to
# the config file must be given here in +config_file+.
#
# The config file created here will disable console log output
# and file logging, but this may be overridden in +text+.
#
# Note that the first line in +text+ will set the indent for the text being
# given and that indent will be removed from all lines in +text+
#
# If you don't intend to change the default config.rb contents or path,
# you can omit this method from your example. Calling create_model()
# will call this method if the +config_file+ does not exist.
def create_config(text = nil, config_file = nil)
config_file ||= Backup::Config.config_file
config_path = File.dirname(config_file)
unless text.to_s.empty?
indent = text.lines.first.match(/^ */)[0].length
text = text.lines.map {|l| l[indent..-1] }.join
end
config = <<-EOS.gsub(/^ /, '')
# encoding: utf-8
Backup::Utilities.configure do
# silence the log output produced by the auto-detection
tar_dist :gnu
end
Backup::Logger.configure do
console.quiet = true
logfile.enabled = false
end
Backup::Storage::Local.defaults do |local|
local.path = '#{ LOCAL_STORAGE_PATH }'
end
#{ text }
#{ CONFIG_TEMPLATE }
EOS
# Create models path, since models are always relative to the config file.
FileUtils.mkdir_p File.join(config_path, 'models')
File.open(config_file, 'w') {|f| f.write config }
end
# Creates a model file.
#
# Pass +config_file+ if it won't be at the default path +~/Backup/+.
#
# Creates the model as +/models/<trigger>.rb+, relative to the path
# of +config_file+.
#
# Note that the first line in +text+ will set the indent for the text being
# given and that indent will be removed from all lines in +text+
def create_model(trigger, text, config_file = nil)
config_file ||= Backup::Config.config_file
model_path = File.join(File.dirname(config_file), 'models')
model_file = File.join(model_path, trigger.to_s + '.rb')
create_config(nil, config_file) unless File.exist?(config_file)
indent = text.lines.first.match(/^ */)[0].length
text = text.lines.map {|l| l[indent..-1] }.join
config = <<-EOS.gsub(/^ /, '')
# encoding: utf-8
#{ text }
EOS
File.open(model_file, 'w') {|f| f.write config }
end
# Runs the given trigger(s).
#
# Any +options+ given are passed as command line options to the
# `backup perform` command. These should be given as String arguments.
# e.g. job = backup_perform :my_backup, '--tmp-path=/tmp'
#
# The last argument given for +options+ may be a Hash, which is used
# as options for this method. If { :exit_status => Integer } is set,
# this method will rescue SystemExit and assert that the exit status
# is correct. This allows jobs that log warnings to continue and return
# the performed job(s).
#
# When :focus is added to an example, '--no-quiet' will be appended to
# +options+ so you can see the log output as the backup is performed.
def backup_perform(triggers, *options)
triggers = Array(triggers).map(&:to_s)
opts = options.last.is_a?(Hash) ? options.pop : {}
exit_status = opts.delete(:exit_status)
options << '--no-quiet' if example.metadata[:focus] || ENV['VERBOSE']
argv = ['perform', '-t', triggers.join(',')] + options
# Reset config paths, utility paths and the logger.
Backup::Config.send(:reset!)
Backup::Utilities.send(:reset!)
Backup::Logger.send(:reset!)
# Ensure multiple runs have different timestamps
sleep 1 unless Backup::Model.all.empty?
# Clear previously loaded models and other class instance variables
Backup::Model.send(:reset!)
ARGV.replace(argv)
if exit_status
expect do
Backup::CLI.start
end.to raise_error(SystemExit) {|exit|
expect( exit.status ).to be(exit_status)
}
else
Backup::CLI.start
end
models = triggers.map {|t| Backup::Model.find_by_trigger(t).first }
jobs = models.map {|m| BackupSpec::PerformedJob.new(m) }
jobs.count > 1 ? jobs : jobs.first
end
# Return the sorted contents of the given +path+,
# relative to the path so the contents may be matched against
# the contents of another path.
def dir_contents(path)
path = File.expand_path(path)
Dir["#{ path }/**/*"].map {|e| e.sub(/^#{ path }/, '') }.sort
end
# Initial Files are MD5: d3b07384d113edec49eaa6238ad5ff00
#
# ├── dir_a
# │ └── one.file
# └── dir_b
# ├── dir_c
# │ └── three.file
# ├── bad\xFFfile
# └── two.file
#
def prepare_local_sync_files
FileUtils.rm_rf LOCAL_SYNC_PATH
%w{ dir_a
dir_b/dir_c }.each do |path|
FileUtils.mkdir_p File.join(LOCAL_SYNC_PATH, path)
end
%W{ dir_a/one.file
dir_b/two.file
dir_b/bad\xFFfile
dir_b/dir_c/three.file }.each do |path|
File.open(File.join(LOCAL_SYNC_PATH, path), 'w') do |file|
file.puts 'foo'
end
end
end
# Added/Updated Files are MD5: 14758f1afd44c09b7992073ccf00b43d
#
# ├── dir_a
# │ ├── dir_d (add)
# │ │ └── two.new (add)
# │ └── one.file (update)
# └── dir_b
# ├── dir_c
# │ └── three.file
# ├── bad\377file
# ├── one.new (add)
# └── two.file (remove)
#
def update_local_sync_files
FileUtils.mkdir_p File.join(LOCAL_SYNC_PATH, 'dir_a/dir_d')
%w{ dir_a/one.file
dir_b/one.new
dir_a/dir_d/two.new }.each do |path|
File.open(File.join(LOCAL_SYNC_PATH, path), 'w') do |file|
file.puts 'foobar'
end
end
FileUtils.rm File.join(LOCAL_SYNC_PATH, 'dir_b/two.file')
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/support/live.rb | vagrant/spec/support/live.rb | module BackupSpec
file = File.expand_path('../../live.yml', __FILE__)
LIVE = File.exist?(file) ? YAML.load_file(file) : Hash.new {|h,k| h.dup }
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/support/tar_file.rb | vagrant/spec/support/tar_file.rb | module BackupSpec
class TarFile
include Backup::Utilities::Helpers
attr_reader :path
def initialize(path)
@path = path
end
def manifest
@manifest ||= begin
if File.exist?(path.to_s)
%x[#{ utility(:tar) } -tvf #{ path } 2>/dev/null]
else
''
end
end
end
# GNU/BSD have different formats for `tar -tvf`.
#
# Returns a Hash of { 'path' => size } for only the files in the manifest.
def contents
@contents ||= begin
data = manifest.split("\n").reject {|line| line =~ /\/$/ }
data.map! {|line| line.split(' ') }
if gnu_tar?
Hash[data.map {|fields| [fields[5], fields[2].to_i] }]
else
Hash[data.map {|fields| [fields[8], fields[4].to_i] }]
end
end
end
def [](val)
extracted_files[val]
end
private
# Return a Hash with the paths from #contents mapped to either another
# TarFile object (for tar files) or the full path to the extracted file.
def extracted_files
@extracted_files ||= begin
base_path = File.dirname(path)
filename = File.basename(path)
Dir.chdir(base_path) do
%x[#{ utility(:tar) } -xf #{ filename } 2>/dev/null]
end
Hash[
contents.keys.map {|manifest_path|
path = File.join(base_path, manifest_path.sub(/^\//, ''))
if path =~ /\.tar.*$/
[manifest_path, self.class.new(path)]
else
[manifest_path, path]
end
}
]
end
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/support/performed_job.rb | vagrant/spec/support/performed_job.rb | module BackupSpec
class PerformedJob
attr_reader :model, :logger, :package
def initialize(model)
@model = model
@logger = Backup::Logger.saved.shift
@package = Package.new(model)
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/support/gpg_keys.rb | vagrant/spec/support/gpg_keys.rb | module BackupSpec
GPGKeys = Hash.new {|h,k| h[k] = {} }
GPGKeys[:backup01][:long_id] = '8F5D150616325C61'
GPGKeys[:backup01][:public] = <<-EOS
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.4.12 (GNU/Linux)
mI0EUBR6CwEEAMVSlFtAXO4jXYnVFAWy6chyaMw+gXOFKlWojNXOOKmE3SujdLKh
kWqnafx7VNrb8cjqxz6VZbumN9UgerFpusM3uLCYHnwyv/rGMf4cdiuX7gGltwGb
dwP18gzdDanXYvO4G7qtk8DH1lRI/TnLH8wAoY/DthSR//wcP33GxRnrABEBAAG0
HkJhY2t1cCBUZXN0IDxiYWNrdXAwMUBmb28uY29tPoi4BBMBAgAiBQJQFHoLAhsD
BgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRCPXRUGFjJcYZc5A/91HQ4+BXUw
KUHmpGyD+6b42xl3eBdmBVimCYTgfRUyRQEDWzHV4a3cYWwe30J/LzfFn1E6uVwz
6SHtzwZddWwONRgC/Q7V0TrnLeuv46MKoB24EFqfbr0kosuZgHPuK4h+rLmaPVCM
kv9DcKCupGnFzoaZ7tdgQAXzGepZQZU0sbiNBFAUegsBBACXX6cGjaENoOMyibXh
HLlEOKWwlxDgo3bSu6U8kISUmwxH/MO4I/u7BAQBczitNYSWovlbvCcxCy4h12qj
gruN5INIDGsEfDSWcN3lxBZ+9J+FhngBjETeADFaPxoele9wVGdIYdLIP6RntK/D
6F2ER8sb57YYtK50iyyuYQqSeQARAQABiJ8EGAECAAkFAlAUegsCGwwACgkQj10V
BhYyXGEq7AP/Y/k1A6nrCC6bfkHFMJmEJDe0Wb6q8P3gcBqNuf8iOwk53UdoXU0Q
JcPAQd/sJy6914huN2dzbVCSchSkLRXgejI0Xf5go1sDzspVKEflu0CWZ3A976QH
mLekS3xntUhhgHKc4lhf4IVBqG4cFmwSZ0tZEJJUSESb3TqkkdnNLjE=
=KEW+
-----END PGP PUBLIC KEY BLOCK-----
EOS
GPGKeys[:backup01][:private] = <<-EOS
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG v1.4.12 (GNU/Linux)
lQHYBFAUegsBBADFUpRbQFzuI12J1RQFsunIcmjMPoFzhSpVqIzVzjiphN0ro3Sy
oZFqp2n8e1Ta2/HI6sc+lWW7pjfVIHqxabrDN7iwmB58Mr/6xjH+HHYrl+4BpbcB
m3cD9fIM3Q2p12LzuBu6rZPAx9ZUSP05yx/MAKGPw7YUkf/8HD99xsUZ6wARAQAB
AAP/VJDiogUAjtK7SNH4BcU6qjxWK4pyQkcE8LcOvKbn48bcXtJrtg7GWpYrNxjI
Mg/nHHt6Lpkqg3RmI0ILMzOj5TukhmJnB/ieogFyuiVzymcMdkcx8PRNXIoF90Au
8yp5ZgXdStmIrlxh4ofJsas8YWsVynb+r6FT2UrAjYT3vAECANoCF26P14ZtGQJ4
eT4a19wzlcIDMuKFaXlB5WYCnQi43ngKn/mjdQrNfpfSPNF+oCHlWGisz0fg/51+
NXg46+sCAOe1pm8K6qO20SzkAW0b9Hzk0b0JWJiHk1QiB1gR9KZffC/8Y7rqYaiG
Sbtyc3ujjayFdc90bwZeSkzrCvO/CgEB/3jiuZiAOov2JFMMPzp7S9SS3CN8nopp
xupeE6uH3Kxp24XYgLxfRO9iqZK/BRlkb5fUKw8u08J5439X9o9mBUOf4bQeQmFj
a3VwIFRlc3QgPGJhY2t1cDAxQGZvby5jb20+iLgEEwECACIFAlAUegsCGwMGCwkI
BwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEI9dFQYWMlxhlzkD/3UdDj4FdTApQeak
bIP7pvjbGXd4F2YFWKYJhOB9FTJFAQNbMdXhrdxhbB7fQn8vN8WfUTq5XDPpIe3P
Bl11bA41GAL9DtXROuct66/jowqgHbgQWp9uvSSiy5mAc+4riH6suZo9UIyS/0Nw
oK6kacXOhpnu12BABfMZ6llBlTSxnQHYBFAUegsBBACXX6cGjaENoOMyibXhHLlE
OKWwlxDgo3bSu6U8kISUmwxH/MO4I/u7BAQBczitNYSWovlbvCcxCy4h12qjgruN
5INIDGsEfDSWcN3lxBZ+9J+FhngBjETeADFaPxoele9wVGdIYdLIP6RntK/D6F2E
R8sb57YYtK50iyyuYQqSeQARAQABAAP6Akx2AvtBheKqnJIl3cn5FWxWS3Q/Jygi
+2rVJNJYKbu2hVJ/xDMLWoZNC3AXsof95X3f/e4sJVpN/FPS/IdqqBmZpREOzash
fWAjs6j7Z7lQEuxKvdSdcy4olzcYGOegYaZpL0B9eeOtX3Hb4JXHwp0i9NwFlXgg
MR10rIy48qECAMBEW64UAaZ31/Q1P0NXfMYTm+vogrAi8lsVdSAjDBAKtAD3+mGD
JGymg0R6uzw9xDijN9HgBi55TfCAiVoVhiECAMmNHHuypUMVsPstBtUEELwDHH7K
acWFNhi6x4Ccl1C7xncKK6BedjjwP8K06hBjWAkBzNUwX79N0Lm+ob9O0VkB+wdE
ykurS0qEob/PiLBA5ksWRA1EKLQ/PjEmSxYJAldVLyKtUPtfyXVKTpZ2xCwuLi/m
sspaiPeTJp7Gtr1l/smYf4ifBBgBAgAJBQJQFHoLAhsMAAoJEI9dFQYWMlxhKuwD
/2P5NQOp6wgum35BxTCZhCQ3tFm+qvD94HAajbn/IjsJOd1HaF1NECXDwEHf7Ccu
vdeIbjdnc21QknIUpC0V4HoyNF3+YKNbA87KVShH5btAlmdwPe+kB5i3pEt8Z7VI
YYBynOJYX+CFQahuHBZsEmdLWRCSVEhEm906pJHZzS4x
=ls9W
-----END PGP PRIVATE KEY BLOCK-----
EOS
GPGKeys[:backup02][:long_id] = '711899386A6A175A'
GPGKeys[:backup02][:public] = <<-EOS
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.4.12 (GNU/Linux)
mI0EUBR6JQEEAMPuY4qoKR7MpZA7D+KRrhiJRCT8t5F4IZ+gq7FBCfwoopcStlin
nTGRL1F/UEngu5xHgLsERzPdKNoTpoy1aCcgB7i9vyi2bA3iNGs1YzWqf1vGJxEp
+CXXtlBU+QYod6wRMK4cHKVjPaD+Ga+saU1Pz9tBGYAbADYVmhJd7R21ABEBAAG0
HkJhY2t1cCBUZXN0IDxiYWNrdXAwMkBmb28uY29tPoi4BBMBAgAiBQJQFHolAhsD
BgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRBxGJk4amoXWjJxA/sG60qZMn40
IP0pjuY+3kc5199xcavxgHZdQTBq2vrJHzr3K8Zk8xxSCADRJf4++t4+8yG7g9rk
bmEAeGoFBIbdx7zGcxYIe5g9UG/+eDCJ44HCb0v8vHUT7iqt5Jk6cryYtcYvqO6I
84HXdXz4rCMCUeRP4ceMCZB6GZKDXR8zoriNBFAUeiUBBADEEOUdfCmwJ5BEPWzm
QTGcp2dSY8SgpbZtk23LvWIlEziYflIqOGeL623AOBb9S2FChR+zPyOA9D3LEZrA
PF8TS3YY+qjBdiXLKchRr5y2Kwylh/vVdcCcgTjfPkga4pGq+cHBOevPiqAvoCtO
ntN7+Cqk3B7nWTPQRFDQJVThwwARAQABiJ8EGAECAAkFAlAUeiUCGwwACgkQcRiZ
OGpqF1oNNgP/adkSZZVaYy/JEHjjrtC9UwirSluAdHQZGPGv/FHaFou+4mlLi0+R
gQLieU+3AHFSWVYMNjIsSjA4hhMLchteFlJnbkGAFUaA2QUoyf7cSSmdpNKQdDdZ
oe3OXEQM2pUTEwE9AqKXthrSMQuJ5bozm8zHm/CohZPHGTeQH75Kq/4=
=AgbQ
-----END PGP PUBLIC KEY BLOCK-----
EOS
GPGKeys[:backup02][:private] = <<-EOS
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG v1.4.12 (GNU/Linux)
lQHYBFAUeiUBBADD7mOKqCkezKWQOw/ika4YiUQk/LeReCGfoKuxQQn8KKKXErZY
p50xkS9Rf1BJ4LucR4C7BEcz3SjaE6aMtWgnIAe4vb8otmwN4jRrNWM1qn9bxicR
Kfgl17ZQVPkGKHesETCuHBylYz2g/hmvrGlNT8/bQRmAGwA2FZoSXe0dtQARAQAB
AAP9Ek+8U+Alf7BmpNUwRd+Ros9pY/+OdHUCx3VvtnA6q6tsjqv8CMsZgOFtx7Mb
YNw1DIUOPexHb0xzHfaKMUpfAmc4PRYnEiggloT+UmB/Hs2tHfeE3hONiDDD9PMU
PiFmm2d+P0pRVTZUrioBaACWpu5YS03I6SC0zDdJeJapk10CANvaaRUZwBqpccfR
MFuV78NYPDkgwKuIJzMRFvp2PnEYPKmS7Ivz5ZimwltDukEOdmTCUAjW6iibKav5
EFmENSMCAOQlGzr3kQRNbcTWh4MYqQ0mDS0Gv9IWZR1DJBPziWnaMqvMyRrFK031
WXzHFDkhbph/HjZ0M33e7bsaLfBsq0cB/Ag+/9rJyTAOyCgbx4VNeipuseiLW3rn
gE5UdJa2FHpZcJqHk81IssCTVLnU3NADH0Eg6rVB4/31L1CtlkxgxZiXWbQeQmFj
a3VwIFRlc3QgPGJhY2t1cDAyQGZvby5jb20+iLgEEwECACIFAlAUeiUCGwMGCwkI
BwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEHEYmThqahdaMnED+wbrSpkyfjQg/SmO
5j7eRznX33Fxq/GAdl1BMGra+skfOvcrxmTzHFIIANEl/j763j7zIbuD2uRuYQB4
agUEht3HvMZzFgh7mD1Qb/54MInjgcJvS/y8dRPuKq3kmTpyvJi1xi+o7ojzgdd1
fPisIwJR5E/hx4wJkHoZkoNdHzOinQHXBFAUeiUBBADEEOUdfCmwJ5BEPWzmQTGc
p2dSY8SgpbZtk23LvWIlEziYflIqOGeL623AOBb9S2FChR+zPyOA9D3LEZrAPF8T
S3YY+qjBdiXLKchRr5y2Kwylh/vVdcCcgTjfPkga4pGq+cHBOevPiqAvoCtOntN7
+Cqk3B7nWTPQRFDQJVThwwARAQABAAP0CszwvLeNuTt80e53OXmOmYJZ6zhzRz2k
kiX+LwzoRKjYycFdFz3gCqiDj9w1Pq6Pcx030Wmh+tI07znhkXGG6WgEdg3WMBa0
ephoNZKsmU2Xhbpf/au8uNwXLtaCEgZoC04JGlGzbX4gJXyUooW+/paxZMQFWFlM
ztf04oIHFQIA2+wOHvJc3HxP0I1Gtfx9bf27UKp1O/4te3m8yOZuIb8gAhlvqkJr
q+HcJ6604c8vKBHA08F+E6EJ8Sdt/eMlTwIA5Dr4AmGEKqkk92FuXm6R0ruo9Bm3
Ep7eFCjRul5lKV/lTF88+KLrzMzho1E/9BgiOKvm7Z1yQTZQUAHEwcqHTQIAusG5
gr2CASWpXbCxX6DWl8n7hdWAhGR0wHWk3ValNl0hLzxMx2Icf2ZWZ3rZw2/JsLiQ
oujz1T1DWgxsNyZaraPsiJ8EGAECAAkFAlAUeiUCGwwACgkQcRiZOGpqF1oNNgP/
adkSZZVaYy/JEHjjrtC9UwirSluAdHQZGPGv/FHaFou+4mlLi0+RgQLieU+3AHFS
WVYMNjIsSjA4hhMLchteFlJnbkGAFUaA2QUoyf7cSSmdpNKQdDdZoe3OXEQM2pUT
EwE9AqKXthrSMQuJ5bozm8zHm/CohZPHGTeQH75Kq/4=
=+a/7
-----END PGP PRIVATE KEY BLOCK-----
EOS
GPGKeys[:backup03][:long_id] = '5847D49DD791E4FA'
GPGKeys[:backup03][:public] = <<-EOS
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.4.12 (GNU/Linux)
mI0EUBR4LgEEAL6TxhYYNEirawnp/fmc0TwKYVSiTk60qGJyspEj0QKJ3MmunC/o
YX+5k8HN68BKP7xkJyHYFdXCJn2HqSbj0T7oV4scQGLJSO5adNa/6uMDZIA6Ptt4
UFOwdc8bnV9sDQTdrp2Gqsxi3f34WX0DV7/KrMD/jQJ9hiWphXSmvaV9ABEBAAG0
HkJhY2t1cCBUZXN0IDxiYWNrdXAwM0Bmb28uY29tPoi4BBMBAgAiBQJQFHguAhsD
BgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRBYR9Sd15Hk+shkA/4yev3zyK+/
jPZQgFLq10biRDYMdWk4ysHCkSbBi4GMnjIanBFk6ggbH/jQIb79oZRv2MB/N8Ag
4s1oZdC5W1gSCg4m4pUB06NkKD4NvKAHHzsfr93farAct1zBQJ19e2ErFeo2Bb5G
uAvf2VWziMQD9aB0lF6tf/CToeWp+2xK77iNBFAUeC4BBADGwKc66SFldjN9dIxk
NYWLwCSvEgsOUdQpYckWLeUFnvKMpOW9+0Q5fc7QZuTs4TnT6cHjKk7F4ZQpMlqy
vc5H99vfp+/fus4LyAYIZKXmuc44SWwxU0y2MsGguFZbWKctQLquKD3uk3S8LPvY
wYn5weLVOhoUgbYGi6HeK8hkuQARAQABiJ8EGAECAAkFAlAUeC4CGwwACgkQWEfU
ndeR5PqQIQP8DMrzFSpyOEsxWRC8x4dhBtpptjO2MIS9FsX9pmycC52V9mCQX5pb
5ZN6YPHOArYNUQfrXGRrOQFAPuNaucet/w39KIOmMZGPRGzOkTmp4AEhO7fKtuw8
/oWOO6hlX/rG4JNZUu3DQEt8WKCV9dHGxNWkxEptRA/CRYW4aj0MkaE=
=dxCg
-----END PGP PUBLIC KEY BLOCK-----
EOS
GPGKeys[:backup03][:private] = <<-EOS
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG v1.4.12 (GNU/Linux)
lQHYBFAUeC4BBAC+k8YWGDRIq2sJ6f35nNE8CmFUok5OtKhicrKRI9ECidzJrpwv
6GF/uZPBzevASj+8ZCch2BXVwiZ9h6km49E+6FeLHEBiyUjuWnTWv+rjA2SAOj7b
eFBTsHXPG51fbA0E3a6dhqrMYt39+Fl9A1e/yqzA/40CfYYlqYV0pr2lfQARAQAB
AAP9HVrYQHd+eDIVRPvqr7vwu7mSl+1/N97ab/2gVTxp2aUAIf24F6YI/JpKcOgF
2ALn0d4wa+VjqZ8j/CJ9Et01EeIkEl9rDBVHLFKLpEABSRCCPpYPBhNqKgRQnLBl
M9kb6OxlBF0Y2L7oonq19Txer8FNB724m7yvBlWQko5id6ECAND9Cgn/YVuj83Es
DEBMjyAysgs3L69CoKQRL02PULbfVgabKqKqFJKDZr4DVyVo6v0L/c9pvnrz5GZG
McGH390CAOlyfn9fWtNjMci+DZ2ZXjut8FXnU+ChyGoc62brcQ0YE1767pyIpmxe
sG06jTMPpmBSA1xbMpScfLQehnLJUiEB/3f3U/8UiUTmB8bWe2JpHefJAn3Y8VLr
tLXujEmYqrn6kUNo1UgIodLtlKY/HfYm6gvcBl5W4+z7FnDBWwDIlX6e/7QeQmFj
a3VwIFRlc3QgPGJhY2t1cDAzQGZvby5jb20+iLgEEwECACIFAlAUeC4CGwMGCwkI
BwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEFhH1J3XkeT6yGQD/jJ6/fPIr7+M9lCA
UurXRuJENgx1aTjKwcKRJsGLgYyeMhqcEWTqCBsf+NAhvv2hlG/YwH83wCDizWhl
0LlbWBIKDibilQHTo2QoPg28oAcfOx+v3d9qsBy3XMFAnX17YSsV6jYFvka4C9/Z
VbOIxAP1oHSUXq1/8JOh5an7bErvnQHYBFAUeC4BBADGwKc66SFldjN9dIxkNYWL
wCSvEgsOUdQpYckWLeUFnvKMpOW9+0Q5fc7QZuTs4TnT6cHjKk7F4ZQpMlqyvc5H
99vfp+/fus4LyAYIZKXmuc44SWwxU0y2MsGguFZbWKctQLquKD3uk3S8LPvYwYn5
weLVOhoUgbYGi6HeK8hkuQARAQABAAP9G+yT4lFAXbC8fb8a/XZOl8qsbMN4da/W
AuVn+vuCPqatFckSNT3BAWHVZY7bUZO4S/d/A/NdA2zU4+/c8dl8inzv5tAmVFQY
w9XYZoA8d4GS+IflmVAzu8aWJlQLfMI8HKtwrf4gpSjZFsLIe9E/xQSgGWt1WXJ5
fbgbBKBLRB0CANF5C0VHOg/zIc7AODCi9GYqYWxQE0MiMhh1SzuG/NVHke+ldhqb
ogV+TMBAR8PCRNf64cKtXyJ2u5ZnXlSBWdUCAPLmCZBCFW3hm/26fdAovNHA53HZ
ucxhwrLP0Ks1+vr779JMypl6QVYbbHXaI7oyRFKg5KOdz4S2ij213gVOzVUCAKy1
MftwhFXCrQwfuA8d2rnro4WqreNyzRj/7QL11N8oQ1XasHCuuOVpDVyuBxtwGLG3
KUeriIODL6Bo/RevX0an8YifBBgBAgAJBQJQFHguAhsMAAoJEFhH1J3XkeT6kCED
/AzK8xUqcjhLMVkQvMeHYQbaabYztjCEvRbF/aZsnAudlfZgkF+aW+WTemDxzgK2
DVEH61xkazkBQD7jWrnHrf8N/SiDpjGRj0RszpE5qeABITu3yrbsPP6FjjuoZV/6
xuCTWVLtw0BLfFiglfXRxsTVpMRKbUQPwkWFuGo9DJGh
=6CYb
-----END PGP PRIVATE KEY BLOCK-----
EOS
GPGKeys[:backup04][:long_id] = '0F45932D3F24426D'
GPGKeys[:backup04][:public] = <<-EOS
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.4.12 (GNU/Linux)
mI0EUBR40wEEAMLAMVwpXCeEz1QZPJc8RFwAUBZRc/FYZ+CY4RKfQKZPuBMyzz3y
mk3gFB8raw2nycH00zwrP/qm/gIBzpCza+87uqGrB8bezgHoU1CaFnO0ZNUzyB8j
FsaQ/7BScjFNQp4RvbryZJUMXJ0V8fV9mQMe+O83CskabLCS4UY6EhWXABEBAAG0
HkJhY2t1cCBUZXN0IDxiYWNrdXAwNEBmb28uY29tPoi4BBMBAgAiBQJQFHjTAhsD
BgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRAPRZMtPyRCbU30A/0YU8U7EOKd
5jSKhkAN50n4Cvwr0uOfC3UoJHInglRc+hDLB5ZF5GMqSfLYIb6/saY99Xb76l7i
k/0Q+rpk0AJ/dbY2ARrPqetleTPBsjrQbj9pzU4yvpYohpippjUbGAo74ssRGJoX
28O98TXn8+q3bcz7bbLBmYj1Fy4QrSpBj7iNBFAUeNMBBADNBWFF0UFiPOCh9g3P
qOAYOXRsmEpLwGBGUB5ZdWzkIGrvs3KjTxIgy+uvx5Q8nX7+OLePaR9BM0qyryzz
LLjEKuaeDk1KelZ6/aV4ErgBUfVDs8pniLrSUqD65o18PL+T6nQ4aUYpgcqdb7t/
/by/yzt0+eEaAoArm0B8IdzB/QARAQABiJ8EGAECAAkFAlAUeNMCGwwACgkQD0WT
LT8kQm2LDgP/cUpWPR/GVdwLlbUIWBh37lLHEEuppZFg2P15Pv0UK9pNxCFhGouS
eBXW8xC/mvOrf7mj/tEV3CxGvIFdebtraEwLUQW0109vWHNclK6/SvmSNcaPo1t0
FtsIP4HI4ymvvTKUObfQliRdk1u1wY7sCWGarQgN9NtHuuyYP5+wmYg=
=LfdH
-----END PGP PUBLIC KEY BLOCK-----
EOS
GPGKeys[:backup04][:private] = <<-EOS
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG v1.4.12 (GNU/Linux)
lQHYBFAUeNMBBADCwDFcKVwnhM9UGTyXPERcAFAWUXPxWGfgmOESn0CmT7gTMs89
8ppN4BQfK2sNp8nB9NM8Kz/6pv4CAc6Qs2vvO7qhqwfG3s4B6FNQmhZztGTVM8gf
IxbGkP+wUnIxTUKeEb268mSVDFydFfH1fZkDHvjvNwrJGmywkuFGOhIVlwARAQAB
AAP8C0NOjNFu3Rw5r1fsS092y/P6rb0VMv0quMWup+3iMRwa0wVqZd9CHESGyrdZ
8BwRjNrfXTNKdnEHmfnHxqeRvit+WRPCuhGcRTNJ8UTBPw4XMY/UYXHIXQGXwqk6
lzd+UQvqyZPv3ukuChDrXuCTG+443WFfHxl4S7PAn3aTwjUCANQjjqSweQZAHvn0
XXcnTNRDV8Bf+Sl7rxhMcBUJhFu3ALBWosZDI/zYTDQ/FZqbM8A9Poh6cnB2TS/S
47kNwDMCAOsESXIs/RBg2RDactjqxj5TVn/T0PMZ1AhV2BPl2RmP/bnwyBWy0O9N
V3hKY0ArEEpcNf8HuRz7/nOduCtEYQ0CAN2AODbYyG/sL+wH0k392fpnsWmdYs4N
21AgfPY8U3Oyrodgjz1hU3C3dxyE3co4sU42d3sLI2tpxa0xy6mHetKdbLQeQmFj
a3VwIFRlc3QgPGJhY2t1cDA0QGZvby5jb20+iLgEEwECACIFAlAUeNMCGwMGCwkI
BwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEA9Fky0/JEJtTfQD/RhTxTsQ4p3mNIqG
QA3nSfgK/CvS458LdSgkcieCVFz6EMsHlkXkYypJ8tghvr+xpj31dvvqXuKT/RD6
umTQAn91tjYBGs+p62V5M8GyOtBuP2nNTjK+liiGmKmmNRsYCjviyxEYmhfbw73x
Nefz6rdtzPttssGZiPUXLhCtKkGPnQHYBFAUeNMBBADNBWFF0UFiPOCh9g3PqOAY
OXRsmEpLwGBGUB5ZdWzkIGrvs3KjTxIgy+uvx5Q8nX7+OLePaR9BM0qyryzzLLjE
KuaeDk1KelZ6/aV4ErgBUfVDs8pniLrSUqD65o18PL+T6nQ4aUYpgcqdb7t//by/
yzt0+eEaAoArm0B8IdzB/QARAQABAAP9H1IfFidtsbBTMOsCGSNXeNvuKVjqoL/2
9UbwHAKQbBl3vL7RWJmPz2rXyrbWspvs9rF7eXE50SAg3UNdvpiqcSdBwC4VSDNe
VSbKaZ5MmqapC7ioLH/FEcvZgaZfTsTsLC10CIZgisW+z+zKq2fafwSI5o2XMuoE
/iuai9z6ZoECANEKpjytZB93+O2fUWPG7BjIzVUZGIeSxGKPze9jgQloHAou5sH8
WygPVlQzy9Xxt7Z9/QrZlGdalyeDQaoC6dkCAPsThN0K0s2pabEfMtYOneJzR5Xs
ze6aqs6+FpHikAISMswd5EHnfPtKA51bGxWKAxgeCqNMpf8tJMAFCmj2fsUB/3Z5
IZJE+OmdiMDm81yDNpK801RZAiySpbZ5CEaWB/BuuTIyG7k/dtSnWtodEOEcEjFs
yBaY+gUfFbKHBatQN7qf2oifBBgBAgAJBQJQFHjTAhsMAAoJEA9Fky0/JEJtiw4D
/3FKVj0fxlXcC5W1CFgYd+5SxxBLqaWRYNj9eT79FCvaTcQhYRqLkngV1vMQv5rz
q3+5o/7RFdwsRryBXXm7a2hMC1EFtNdPb1hzXJSuv0r5kjXGj6NbdBbbCD+ByOMp
r70ylDm30JYkXZNbtcGO7Alhmq0IDfTbR7rsmD+fsJmI
=I+GJ
-----END PGP PRIVATE KEY BLOCK-----
EOS
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/support/custom_matchers.rb | vagrant/spec/support/custom_matchers.rb | # Matches the contents of a TarFile (or PerformedJob.package)
# against the given manifest.
#
# Usage:
#
# performed_job = backup_perform :trigger
#
# expect( performed_job.package ).to match_manifest(<<-EOS)
# 51200 my_backup/archives/my_archive.tar
# 8099 my_backup/databases/MySQL/backup_test_01.sql
# EOS
#
# File sizes may also be tested against a range, using `min..max`.
#
# expect( performed_job.package ).to match_manifest(%q[
# 51200..51250 my_backup/archives/my_archive.tar
# 8099 my_backup/databases/MySQL/backup_test_01.sql
# ])
#
# Or simply checked for existance, using `-`:
#
# expect( performed_job.package ).to match_manifest(%q[
# - my_backup/archives/my_archive.tar
# 8099 my_backup/databases/MySQL/backup_test_01.sql
# ])
#
# Extra spaces and blank lines are ok.
#
# If the given files with the given sizes do not match all the files
# in the archive's manifest, the error message will include the entire
# manifest as output by `tar -tvf`.
RSpec::Matchers.define :match_manifest do |expected|
match do |actual|
expected_contents = expected.split("\n").map(&:strip).reject(&:empty?)
expected_contents.map! {|line| line.split(' ') }
expected_contents = Hash[
expected_contents.map {|fields| [fields[1], fields[0]] }
]
if files_match = expected_contents.keys.sort == actual.contents.keys.sort
sizes_ok = true
expected_contents.each do |path, size|
actual_size = actual.contents[path]
sizes_ok =
case size
when '-' then true
when /\d+(\.\.)\d+/
a, b = size.split('..').map(&:to_i)
(a..b).include? actual_size
else
size.to_i == actual_size
end
break unless sizes_ok
end
end
files_match && sizes_ok
end
failure_message_for_should do |actual|
"expected that:\n\n#{ actual.manifest }\n" +
"would match:\n#{ expected }"
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/acceptance/archive_spec.rb | vagrant/spec/acceptance/archive_spec.rb | require File.expand_path('../../spec_helper', __FILE__)
module Backup
describe Archive do
shared_examples 'GNU or BSD tar' do
specify 'All directories, no compression, with/without :root' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
archive :archive_a do |archive|
archive.add '~/test_data'
end
archive :archive_b do |archive|
archive.root '~/'
archive.add 'test_data'
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
1_105_920 my_backup/archives/archive_a.tar
1_105_920 my_backup/archives/archive_b.tar
])
# without :root option
package_a = job.package['my_backup/archives/archive_a.tar']
expect( package_a ).to match_manifest(%q[
5_000 /home/vagrant/test_data/dir_a/file_a
5_000 /home/vagrant/test_data/dir_a/file_b
5_000 /home/vagrant/test_data/dir_a/file_c
10_000 /home/vagrant/test_data/dir_b/file_a
10_000 /home/vagrant/test_data/dir_b/file_b
10_000 /home/vagrant/test_data/dir_b/file_c
15_000 /home/vagrant/test_data/dir_c/file_a
15_000 /home/vagrant/test_data/dir_c/file_b
15_000 /home/vagrant/test_data/dir_c/file_c
1_000_000 /home/vagrant/test_data/dir_d/file_a
])
# with :root option
package_b = job.package['my_backup/archives/archive_b.tar']
expect( package_b ).to match_manifest(%q[
5_000 test_data/dir_a/file_a
5_000 test_data/dir_a/file_b
5_000 test_data/dir_a/file_c
10_000 test_data/dir_b/file_a
10_000 test_data/dir_b/file_b
10_000 test_data/dir_b/file_c
15_000 test_data/dir_c/file_a
15_000 test_data/dir_c/file_b
15_000 test_data/dir_c/file_c
1_000_000 test_data/dir_d/file_a
])
end
specify 'Specific directories, with compression, with/without :root' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
archive :archive_a do |archive|
archive.add '~/test_data/dir_a/'
archive.add '~/test_data/dir_b'
end
archive :archive_b do |archive|
archive.root '~/test_data'
archive.add 'dir_a/'
archive.add 'dir_b'
end
compress_with Gzip
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
- my_backup/archives/archive_a.tar.gz
- my_backup/archives/archive_b.tar.gz
])
# without :root option
package_a = job.package['my_backup/archives/archive_a.tar.gz']
expect( package_a ).to match_manifest(%q[
5_000 /home/vagrant/test_data/dir_a/file_a
5_000 /home/vagrant/test_data/dir_a/file_b
5_000 /home/vagrant/test_data/dir_a/file_c
10_000 /home/vagrant/test_data/dir_b/file_a
10_000 /home/vagrant/test_data/dir_b/file_b
10_000 /home/vagrant/test_data/dir_b/file_c
])
# with :root option
package_b = job.package['my_backup/archives/archive_b.tar.gz']
expect( package_b ).to match_manifest(%q[
5_000 dir_a/file_a
5_000 dir_a/file_b
5_000 dir_a/file_c
10_000 dir_b/file_a
10_000 dir_b/file_b
10_000 dir_b/file_c
])
end
specify 'Excluded directories, with compression, with/without :root' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
archive :archive_a do |archive|
archive.add '~/test_data'
archive.exclude '~/test_data/dir_a/'
archive.exclude '~/test_data/dir_d'
end
archive :archive_b do |archive|
archive.root '~/'
archive.add 'test_data'
archive.exclude 'test_data/dir_a/*'
archive.exclude 'test_data/dir_d'
end
compress_with Gzip
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
- my_backup/archives/archive_a.tar.gz
- my_backup/archives/archive_b.tar.gz
])
# without :root option
package_a = job.package['my_backup/archives/archive_a.tar.gz']
expect( package_a ).to match_manifest(%q[
10_000 /home/vagrant/test_data/dir_b/file_a
10_000 /home/vagrant/test_data/dir_b/file_b
10_000 /home/vagrant/test_data/dir_b/file_c
15_000 /home/vagrant/test_data/dir_c/file_a
15_000 /home/vagrant/test_data/dir_c/file_b
15_000 /home/vagrant/test_data/dir_c/file_c
])
# with :root option
package_b = job.package['my_backup/archives/archive_b.tar.gz']
expect( package_b ).to match_manifest(%q[
10_000 test_data/dir_b/file_a
10_000 test_data/dir_b/file_b
10_000 test_data/dir_b/file_c
15_000 test_data/dir_c/file_a
15_000 test_data/dir_c/file_b
15_000 test_data/dir_c/file_c
])
end
specify 'Using Splitter' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
split_into_chunks_of 1 # 1MB
archive :my_archive do |archive|
archive.add '~/test_data'
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.files.count ).to be(2)
expect( job.package ).to match_manifest(%q[
1_105_920 my_backup/archives/my_archive.tar
])
expect(
job.package['my_backup/archives/my_archive.tar']
).to match_manifest(<<-EOS)
5_000 /home/vagrant/test_data/dir_a/file_a
5_000 /home/vagrant/test_data/dir_a/file_b
5_000 /home/vagrant/test_data/dir_a/file_c
10_000 /home/vagrant/test_data/dir_b/file_a
10_000 /home/vagrant/test_data/dir_b/file_b
10_000 /home/vagrant/test_data/dir_b/file_c
15_000 /home/vagrant/test_data/dir_c/file_a
15_000 /home/vagrant/test_data/dir_c/file_b
15_000 /home/vagrant/test_data/dir_c/file_c
1_000_000 /home/vagrant/test_data/dir_d/file_a
EOS
end
specify 'Using sudo' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
archive :my_archive do |archive|
archive.use_sudo
archive.add '~/test_root_data'
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
- my_backup/archives/my_archive.tar
])
expect(
job.package['my_backup/archives/my_archive.tar']
).to match_manifest(<<-EOS)
5_000 /home/vagrant/test_root_data/dir_a/file_a
5_000 /home/vagrant/test_root_data/dir_a/file_b
5_000 /home/vagrant/test_root_data/dir_a/file_c
EOS
end
end # shared_examples 'GNU or BSD tar'
describe 'Using GNU tar' do
# GNU tar is set as the default
it_behaves_like 'GNU or BSD tar'
it 'detects GNU tar' do
create_config <<-EOS
Backup::Utilities.configure do
tar '/usr/bin/tar'
tar_dist nil
end
EOS
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
archive :my_archive do |archive|
archive.add '~/test_data/dir_a'
end
end
EOS
job = backup_perform :my_backup
log_messages = job.logger.messages.map(&:lines).flatten.join
expect( log_messages ).to match(/STDOUT: tar \(GNU tar\)/)
expect( Utilities.send(:utility, :tar) ).to eq('/usr/bin/tar')
expect( Utilities.send(:gnu_tar?) ).to be(true)
end
end
describe 'Using BSD tar' do
before do
# tar_dist must be set, since the default config.rb
# will set this to :gnu to suppress the detection messages.
create_config <<-EOS
Backup::Utilities.configure do
tar '/usr/bin/bsdtar'
tar_dist :bsd
end
EOS
end
it_behaves_like 'GNU or BSD tar'
it 'detects BSD tar' do
create_config <<-EOS
Backup::Utilities.configure do
tar '/usr/bin/bsdtar'
tar_dist nil
end
EOS
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
archive :my_archive do |archive|
archive.add '~/test_data/dir_a'
end
end
EOS
job = backup_perform :my_backup
log_messages = job.logger.messages.map(&:lines).flatten.join
expect( log_messages ).to match(/STDOUT: bsdtar/)
expect( Utilities.send(:utility, :tar) ).to eq('/usr/bin/bsdtar')
expect( Utilities.send(:gnu_tar?) ).to be(false)
end
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/acceptance/splitter_spec.rb | vagrant/spec/acceptance/splitter_spec.rb | require File.expand_path('../../spec_helper', __FILE__)
module Backup
describe Splitter do
specify 'suffix length may be configured' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
split_into_chunks_of 1, 5
archive :my_archive do |archive|
archive.add '~/test_data'
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package.files.count ).to be(2)
expect( job.package.files.first ).to end_with('-aaaaa')
expect( job.package ).to match_manifest(%q[
- my_backup/archives/my_archive.tar
])
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/acceptance/config_spec.rb | vagrant/spec/acceptance/config_spec.rb | require File.expand_path('../../spec_helper', __FILE__)
describe 'Backup Configuration' do
specify 'Models may be preconfigured' do
create_config <<-EOS
preconfigure 'MyModel' do
archive :archive_a do |archive|
archive.add '~/test_data/dir_a'
end
compress_with Gzip
end
EOS
create_model :my_backup, <<-EOS
MyModel.new(:my_backup, 'a description') do
archive :archive_b do |archive|
archive.add '~/test_data/dir_a'
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
- my_backup/archives/archive_a.tar.gz
- my_backup/archives/archive_b.tar.gz
])
end
specify 'Command line path options may be set in config.rb' do
alt_config_path = BackupSpec::ALT_CONFIG_PATH
config_file = File.join(alt_config_path, 'my_config.rb')
create_config <<-EOS, config_file
root_path BackupSpec::ALT_CONFIG_PATH
tmp_path 'my_tmp'
EOS
create_model :my_backup, <<-EOS, config_file
Model.new(:my_backup, 'a description') do
archive :my_archive do |archive|
archive.add '~/test_data/dir_a'
end
store_with Local
end
EOS
# path to config.rb and models is set on the command line
job = backup_perform :my_backup, '--config-file', config_file
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
- my_backup/archives/my_archive.tar
])
# without setting root_path in config.rb,
# these would still be based on the default root_path (~/Backup)
expect( Backup::Config.tmp_path ).to eq(
File.join(alt_config_path, 'my_tmp')
)
expect( Backup::Config.data_path ).to eq(
File.join(alt_config_path, Backup::Config::DEFAULTS[:data_path])
)
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/acceptance/storage/ftp_spec.rb | vagrant/spec/acceptance/storage/ftp_spec.rb | require File.expand_path('../../../spec_helper', __FILE__)
# Note: vsftpd is setup to chroot to the user's home directory
module Backup
describe Storage::FTP do
it 'cycles stored packages' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
split_into_chunks_of 1 # 1MB
archive :my_archive do |archive|
archive.add '~/test_data'
end
store_with FTP do |ftp|
ftp.ip = 'localhost'
ftp.username = 'vagrant'
ftp.password = 'vagrant'
ftp.path = '~/Storage'
ftp.keep = 2
end
end
EOS
job_a = backup_perform :my_backup
expect( job_a.package.files.count ).to be(2)
job_b = backup_perform :my_backup
expect( job_b.package.files.count ).to be(2)
expect( job_a.package.exist? ).to be_true
job_c = backup_perform :my_backup
expect( job_c.package.files.count ).to be(2)
expect( job_b.package.exist? ).to be_true
expect( job_a.package.removed? ).to be_true
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/acceptance/storage/scp_spec.rb | vagrant/spec/acceptance/storage/scp_spec.rb | require File.expand_path('../../../spec_helper', __FILE__)
# Note: the password may be omitted, since the 'vagrant' user
# is setup with passphrase-less SSH keys.
module Backup
describe Storage::SCP do
it 'cycles stored packages' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
split_into_chunks_of 1 # 1MB
archive :my_archive do |archive|
archive.add '~/test_data'
end
store_with SCP do |scp|
scp.ip = 'localhost'
scp.username = 'vagrant'
scp.password = 'vagrant'
scp.path = '~/Storage'
scp.keep = 2
end
end
EOS
job_a = backup_perform :my_backup
expect( job_a.package.files.count ).to be(2)
job_b = backup_perform :my_backup
expect( job_b.package.files.count ).to be(2)
expect( job_a.package.exist? ).to be_true
job_c = backup_perform :my_backup
expect( job_c.package.files.count ).to be(2)
expect( job_b.package.exist? ).to be_true
expect( job_a.package.removed? ).to be_true
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/acceptance/storage/sftp_spec.rb | vagrant/spec/acceptance/storage/sftp_spec.rb | require File.expand_path('../../../spec_helper', __FILE__)
# Note: the password may be omitted, since the 'vagrant' user
# is setup with passphrase-less SSH keys.
module Backup
describe Storage::SFTP do
it 'cycles stored packages' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
split_into_chunks_of 1 # 1MB
archive :my_archive do |archive|
archive.add '~/test_data'
end
store_with SFTP do |sftp|
sftp.ip = 'localhost'
sftp.username = 'vagrant'
sftp.password = 'vagrant'
sftp.path = '~/Storage'
sftp.keep = 2
end
end
EOS
job_a = backup_perform :my_backup
expect( job_a.package.files.count ).to be(2)
job_b = backup_perform :my_backup
expect( job_b.package.files.count ).to be(2)
expect( job_a.package.exist? ).to be_true
job_c = backup_perform :my_backup
expect( job_c.package.files.count ).to be(2)
expect( job_b.package.exist? ).to be_true
expect( job_a.package.removed? ).to be_true
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/acceptance/storage/rsync_spec.rb | vagrant/spec/acceptance/storage/rsync_spec.rb | require File.expand_path('../../../spec_helper', __FILE__)
module Backup
describe Storage::RSync do
context 'using local operation' do
specify 'single package file' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
archive :my_archive do |archive|
archive.add '~/test_data'
end
store_with RSync do |rsync|
rsync.path = '~/Storage'
rsync.additional_rsync_options = '-vv'
end
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
1_105_920 my_backup/archives/my_archive.tar
])
end
specify 'multiple package files' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
split_into_chunks_of 1 # 1MB
archive :my_archive do |archive|
archive.add '~/test_data'
end
store_with RSync do |rsync|
rsync.path = '~/Storage'
rsync.additional_rsync_options = '-vv'
end
end
EOS
job = backup_perform :my_backup
expect( job.package.files.count ).to be(2)
expect( job.package ).to match_manifest(%q[
1_105_920 my_backup/archives/my_archive.tar
])
end
end # context 'using local operation'
context 'using :ssh mode' do
specify 'single package file' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
archive :my_archive do |archive|
archive.add '~/test_data'
end
store_with RSync do |rsync|
rsync.host = 'localhost'
rsync.path = '~/Storage'
rsync.additional_rsync_options = '-vv'
end
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
1_105_920 my_backup/archives/my_archive.tar
])
end
specify 'multiple package files' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
split_into_chunks_of 1 # 1MB
archive :my_archive do |archive|
archive.add '~/test_data'
end
store_with RSync do |rsync|
rsync.host = 'localhost'
rsync.path = '~/Storage'
rsync.additional_rsync_options = '-vv'
end
end
EOS
job = backup_perform :my_backup
expect( job.package.files.count ).to be(2)
expect( job.package ).to match_manifest(%q[
1_105_920 my_backup/archives/my_archive.tar
])
end
end # context 'using :ssh mode'
context 'daemon modes' do
before do
# Note: rsync will not automatically create this directory,
# since the target is a file. Normally when using a daemon mode,
# only a module name would be used which would specify a directory
# that already exists in which to store the backup package file(s).
# But we need to use ~/Storage, which we remove before each spec example.
FileUtils.mkdir BackupSpec::LOCAL_STORAGE_PATH
end
context 'using :ssh_daemon mode' do
specify 'single package file' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
archive :my_archive do |archive|
archive.add '~/test_data'
end
store_with RSync do |rsync|
rsync.mode = :ssh_daemon
rsync.host = 'localhost'
rsync.path = 'ssh-daemon-module/Storage'
rsync.additional_rsync_options = '-vv'
end
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
1_105_920 my_backup/archives/my_archive.tar
])
end
specify 'multiple package files' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
split_into_chunks_of 1 # 1MB
archive :my_archive do |archive|
archive.add '~/test_data'
end
store_with RSync do |rsync|
rsync.mode = :ssh_daemon
rsync.host = 'localhost'
rsync.path = 'ssh-daemon-module/Storage'
rsync.additional_rsync_options = '-vv'
end
end
EOS
job = backup_perform :my_backup
expect( job.package.files.count ).to be(2)
expect( job.package ).to match_manifest(%q[
1_105_920 my_backup/archives/my_archive.tar
])
end
end # context 'using :ssh_daemon mode'
context 'using :rsync_daemon mode' do
specify 'single package file' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
archive :my_archive do |archive|
archive.add '~/test_data'
end
store_with RSync do |rsync|
rsync.mode = :rsync_daemon
rsync.host = 'localhost'
rsync.rsync_password = 'daemon-password'
rsync.path = 'rsync-daemon-module/Storage'
rsync.additional_rsync_options = '-vv'
end
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
1_105_920 my_backup/archives/my_archive.tar
])
end
specify 'multiple package files' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
split_into_chunks_of 1 # 1MB
archive :my_archive do |archive|
archive.add '~/test_data'
end
store_with RSync do |rsync|
rsync.mode = :rsync_daemon
rsync.host = 'localhost'
rsync.rsync_password = 'daemon-password'
rsync.path = 'rsync-daemon-module/Storage'
rsync.additional_rsync_options = '-vv'
end
end
EOS
job = backup_perform :my_backup
expect( job.package.files.count ).to be(2)
expect( job.package ).to match_manifest(%q[
1_105_920 my_backup/archives/my_archive.tar
])
end
end # context 'using :rsync_daemon mode'
end # context 'daemon modes'
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/acceptance/storage/local_spec.rb | vagrant/spec/acceptance/storage/local_spec.rb | require File.expand_path('../../../spec_helper', __FILE__)
module Backup
describe Storage::Local do
it 'cycles stored packages' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
split_into_chunks_of 1 # 1MB
archive :my_archive do |archive|
archive.add '~/test_data'
end
store_with Local do |local|
local.keep = 2
local.path = '~/Storage'
end
end
EOS
job_a = backup_perform :my_backup
expect( job_a.package.files.count ).to be(2)
job_b = backup_perform :my_backup
expect( job_b.package.files.count ).to be(2)
expect( job_a.package.exist? ).to be_true
job_c = backup_perform :my_backup
expect( job_c.package.files.count ).to be(2)
expect( job_b.package.exist? ).to be_true
expect( job_a.package.removed? ).to be_true
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/acceptance/database/mysql_spec.rb | vagrant/spec/acceptance/database/mysql_spec.rb | require File.expand_path('../../../spec_helper', __FILE__)
module Backup
describe 'Database::MySQL' do
describe 'All Databases' do
specify 'All tables' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database MySQL do |db|
db.name = :all
db.username = 'root'
db.host = 'localhost'
db.port = 3306
db.additional_options = '--events'
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
532976 my_backup/databases/MySQL.sql
])
end
specify 'Tables Excluded' do
# This warning will occur if --events is not used.
create_config <<-EOS
Backup::Logger.configure do
ignore_warning 'Warning: Skipping the data of table mysql.event'
end
EOS
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database MySQL do |db|
db.name = :all
db.username = 'root'
db.host = 'localhost'
db.port = 3306
db.skip_tables = ['backup_test_01.twos', 'backup_test_02.threes']
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
525504 my_backup/databases/MySQL.sql
])
end
end # describe 'All Databases'
describe 'Single Database' do
specify 'All tables' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database MySQL do |db|
db.name = 'backup_test_01'
db.username = 'root'
db.host = 'localhost'
db.port = 3306
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
9532 my_backup/databases/MySQL.sql
])
end
specify 'Only one table' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database MySQL do |db|
db.name = 'backup_test_01'
db.username = 'root'
db.host = 'localhost'
db.port = 3306
db.only_tables = ['ones']
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
2686 my_backup/databases/MySQL.sql
])
end
specify 'Exclude a table' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database MySQL do |db|
db.name = 'backup_test_01'
db.username = 'root'
db.host = 'localhost'
db.port = 3306
db.skip_tables = ['ones']
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
8117 my_backup/databases/MySQL.sql
])
end
end # describe 'Single Database'
describe 'Multiple Dumps' do
specify 'All tables' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database MySQL, :dump_01 do |db|
db.name = 'backup_test_01'
db.username = 'root'
db.host = 'localhost'
db.port = 3306
end
database MySQL, 'Dump #2' do |db|
db.name = 'backup_test_02'
db.username = 'root'
db.host = 'localhost'
db.port = 3306
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
9532 my_backup/databases/MySQL-dump_01.sql
10282 my_backup/databases/MySQL-Dump__2.sql
])
end
end # describe 'Multiple Dumps'
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/acceptance/database/riak_spec.rb | vagrant/spec/acceptance/database/riak_spec.rb | require File.expand_path('../../../spec_helper', __FILE__)
module Backup
describe 'Database::Riak' do
specify 'No Compression' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database Riak
store_with Local
end
EOS
# --tmp-path must be changed from the default ~/Backup/.tmp
# due to permissions needed by riak-admin to perform the dump.
job = backup_perform :my_backup, '--tmp-path=/tmp'
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
156000..157000 my_backup/databases/Riak-riak@127.0.0.1
])
end
specify 'With Compression' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database Riak
store_with Local
compress_with Gzip
end
EOS
# --tmp-path must be changed from the default ~/Backup/.tmp
# due to permissions needed by riak-admin to perform the dump.
job = backup_perform :my_backup, '--tmp-path=/tmp'
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
6500..6800 my_backup/databases/Riak-riak@127.0.0.1.gz
])
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/acceptance/database/redis_spec.rb | vagrant/spec/acceptance/database/redis_spec.rb | require File.expand_path('../../../spec_helper', __FILE__)
module Backup
describe 'Database::Redis' do
shared_examples 'redis specs' do
specify 'No Compression' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database Redis do |db|
db.mode = #{ mode }
db.rdb_path = '/var/lib/redis/dump.rdb'
db.invoke_save = #{ invoke_save }
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
5782 my_backup/databases/Redis.rdb
])
end
specify 'With Compression' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database Redis do |db|
db.mode = #{ mode }
db.rdb_path = '/var/lib/redis/dump.rdb'
db.invoke_save = #{ invoke_save }
end
compress_with Gzip
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
2200..2300 my_backup/databases/Redis.rdb.gz
])
end
specify 'Multiple Dumps' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database Redis, :dump_01 do |db|
db.mode = #{ mode }
db.rdb_path = '/var/lib/redis/dump.rdb'
db.invoke_save = #{ invoke_save }
end
database Redis, 'Dump #2' do |db|
db.mode = #{ mode }
db.rdb_path = '/var/lib/redis/dump.rdb'
db.invoke_save = #{ invoke_save }
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
5782 my_backup/databases/Redis-dump_01.rdb
5782 my_backup/databases/Redis-Dump__2.rdb
])
end
end # shared_examples 'redis specs'
context 'using :copy mode' do
let(:mode) { ':copy' }
context 'with :invoke_save' do
let(:invoke_save) { 'true' }
include_examples 'redis specs'
end
context 'without :invoke_save' do
let(:invoke_save) { 'false' }
include_examples 'redis specs'
end
end
context 'using :sync mode' do
let(:mode) { ':sync' }
let(:invoke_save) { 'false' }
include_examples 'redis specs'
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/acceptance/database/mongodb_spec.rb | vagrant/spec/acceptance/database/mongodb_spec.rb | require File.expand_path('../../../spec_helper', __FILE__)
module Backup
describe 'Database::MongoDB' do
describe 'Single Database' do
specify 'All collections' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database MongoDB do |db|
db.name = 'backup_test_01'
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
- my_backup/databases/MongoDB.tar
])
expect(
job.package['my_backup/databases/MongoDB.tar']
).to match_manifest(%q[
3400 MongoDB/backup_test_01/ones.bson
101 MongoDB/backup_test_01/ones.metadata.json
6800 MongoDB/backup_test_01/twos.bson
101 MongoDB/backup_test_01/twos.metadata.json
13600 MongoDB/backup_test_01/threes.bson
103 MongoDB/backup_test_01/threes.metadata.json
224 MongoDB/backup_test_01/system.indexes.bson
])
end
specify 'All collections with compression' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database MongoDB do |db|
db.name = 'backup_test_01'
end
compress_with Gzip
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
- my_backup/databases/MongoDB.tar.gz
])
expect(
job.package['my_backup/databases/MongoDB.tar.gz']
).to match_manifest(%q[
3400 MongoDB/backup_test_01/ones.bson
101 MongoDB/backup_test_01/ones.metadata.json
6800 MongoDB/backup_test_01/twos.bson
101 MongoDB/backup_test_01/twos.metadata.json
13600 MongoDB/backup_test_01/threes.bson
103 MongoDB/backup_test_01/threes.metadata.json
224 MongoDB/backup_test_01/system.indexes.bson
])
end
specify 'All collections, locking the database' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database MongoDB do |db|
db.name = 'backup_test_01'
db.lock = true
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
- my_backup/databases/MongoDB.tar
])
expect(
job.package['my_backup/databases/MongoDB.tar']
).to match_manifest(%q[
3400 MongoDB/backup_test_01/ones.bson
101 MongoDB/backup_test_01/ones.metadata.json
6800 MongoDB/backup_test_01/twos.bson
101 MongoDB/backup_test_01/twos.metadata.json
13600 MongoDB/backup_test_01/threes.bson
103 MongoDB/backup_test_01/threes.metadata.json
224 MongoDB/backup_test_01/system.indexes.bson
])
end
end # describe 'Single Database'
describe 'All Databases' do
specify 'All collections' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database MongoDB
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
- my_backup/databases/MongoDB.tar
])
expect(
job.package['my_backup/databases/MongoDB.tar']
).to match_manifest(%q[
3400 MongoDB/backup_test_01/ones.bson
101 MongoDB/backup_test_01/ones.metadata.json
6800 MongoDB/backup_test_01/twos.bson
101 MongoDB/backup_test_01/twos.metadata.json
13600 MongoDB/backup_test_01/threes.bson
103 MongoDB/backup_test_01/threes.metadata.json
224 MongoDB/backup_test_01/system.indexes.bson
4250 MongoDB/backup_test_02/ones.bson
101 MongoDB/backup_test_02/ones.metadata.json
7650 MongoDB/backup_test_02/twos.bson
101 MongoDB/backup_test_02/twos.metadata.json
14450 MongoDB/backup_test_02/threes.bson
103 MongoDB/backup_test_02/threes.metadata.json
224 MongoDB/backup_test_02/system.indexes.bson
])
end
specify 'All collections, locking the database' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database MongoDB do |db|
db.lock = true
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
- my_backup/databases/MongoDB.tar
])
expect(
job.package['my_backup/databases/MongoDB.tar']
).to match_manifest(%q[
3400 MongoDB/backup_test_01/ones.bson
101 MongoDB/backup_test_01/ones.metadata.json
6800 MongoDB/backup_test_01/twos.bson
101 MongoDB/backup_test_01/twos.metadata.json
13600 MongoDB/backup_test_01/threes.bson
103 MongoDB/backup_test_01/threes.metadata.json
224 MongoDB/backup_test_01/system.indexes.bson
4250 MongoDB/backup_test_02/ones.bson
101 MongoDB/backup_test_02/ones.metadata.json
7650 MongoDB/backup_test_02/twos.bson
101 MongoDB/backup_test_02/twos.metadata.json
14450 MongoDB/backup_test_02/threes.bson
103 MongoDB/backup_test_02/threes.metadata.json
224 MongoDB/backup_test_02/system.indexes.bson
])
end
end # describe 'All Databases'
describe 'Multiple Dumps' do
specify 'All collections' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database MongoDB, :dump_01 do |db|
db.name = 'backup_test_01'
end
database MongoDB, 'Dump #2' do |db|
db.name = 'backup_test_02'
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
- my_backup/databases/MongoDB-dump_01.tar
- my_backup/databases/MongoDB-Dump__2.tar
])
expect(
job.package['my_backup/databases/MongoDB-dump_01.tar']
).to match_manifest(%q[
3400 MongoDB-dump_01/backup_test_01/ones.bson
101 MongoDB-dump_01/backup_test_01/ones.metadata.json
6800 MongoDB-dump_01/backup_test_01/twos.bson
101 MongoDB-dump_01/backup_test_01/twos.metadata.json
13600 MongoDB-dump_01/backup_test_01/threes.bson
103 MongoDB-dump_01/backup_test_01/threes.metadata.json
224 MongoDB-dump_01/backup_test_01/system.indexes.bson
])
expect(
job.package['my_backup/databases/MongoDB-Dump__2.tar']
).to match_manifest(%q[
4250 MongoDB-Dump__2/backup_test_02/ones.bson
101 MongoDB-Dump__2/backup_test_02/ones.metadata.json
7650 MongoDB-Dump__2/backup_test_02/twos.bson
101 MongoDB-Dump__2/backup_test_02/twos.metadata.json
14450 MongoDB-Dump__2/backup_test_02/threes.bson
103 MongoDB-Dump__2/backup_test_02/threes.metadata.json
224 MongoDB-Dump__2/backup_test_02/system.indexes.bson
])
end
end # describe 'Multiple Dumps'
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/acceptance/database/postgresql_spec.rb | vagrant/spec/acceptance/database/postgresql_spec.rb | require File.expand_path('../../../spec_helper', __FILE__)
module Backup
describe 'Database::PostgreSQL' do
describe 'All Databases' do
specify 'With compression' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database PostgreSQL
compress_with Gzip
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
3118 my_backup/databases/PostgreSQL.sql.gz
])
end
specify 'Without compression' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database PostgreSQL
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
21809 my_backup/databases/PostgreSQL.sql
])
end
end # describe 'All Databases'
describe 'Single Database' do
specify 'All tables' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database PostgreSQL do |db|
db.name = 'backup_test_01'
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
9199 my_backup/databases/PostgreSQL.sql
])
end
specify 'Only one table' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database PostgreSQL do |db|
db.name = 'backup_test_01'
db.only_tables = ['ones']
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
2056 my_backup/databases/PostgreSQL.sql
])
end
specify 'Exclude a table' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database PostgreSQL do |db|
db.name = 'backup_test_01'
db.skip_tables = ['ones']
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
7860 my_backup/databases/PostgreSQL.sql
])
end
end # describe 'Single Database'
describe 'Multiple Dumps' do
specify 'All tables' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
database PostgreSQL, :dump_01 do |db|
db.name = 'backup_test_01'
end
database PostgreSQL, 'Dump #2' do |db|
db.name = 'backup_test_02'
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package ).to match_manifest(%q[
9199 my_backup/databases/PostgreSQL-dump_01.sql
9799 my_backup/databases/PostgreSQL-Dump__2.sql
])
end
end # describe 'Multiple Dumps'
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/acceptance/syncer/rsync/pull_spec.rb | vagrant/spec/acceptance/syncer/rsync/pull_spec.rb | require File.expand_path('../../../../spec_helper', __FILE__)
module Backup
describe Syncer::RSync::Pull do
context 'using :ssh mode' do
specify 'single directory' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Pull do |rsync|
rsync.host = 'localhost'
rsync.path = '~/Storage'
rsync.directories do |dirs|
dirs.add '~/test_data'
end
rsync.additional_rsync_options = '-vv'
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/test_data') ).
to eq( dir_contents('~/test_data') )
end
specify 'multiple directories' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Pull do |rsync|
rsync.host = 'localhost'
rsync.path = '~/Storage'
rsync.directories do |dirs|
dirs.add '~/test_data/dir_a'
dirs.add '~/test_data/dir_b'
dirs.add '~/test_data/dir_c'
end
rsync.additional_rsync_options = '-vv'
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/dir_a') ).
to eq( dir_contents('~/test_data/dir_a') )
expect( dir_contents('~/Storage/dir_b') ).
to eq( dir_contents('~/test_data/dir_b') )
expect( dir_contents('~/Storage/dir_c') ).
to eq( dir_contents('~/test_data/dir_c') )
end
specify 'multiple directories with excludes' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Pull do |rsync|
rsync.host = 'localhost'
rsync.path = '~/Storage'
rsync.directories do |dirs|
dirs.add '~/test_data/dir_a'
dirs.add '~/test_data/dir_b'
dirs.add '~/test_data/dir_c'
dirs.exclude 'file_b'
end
rsync.additional_rsync_options = '-vv'
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/dir_a') ).to eq(
dir_contents('~/test_data/dir_a') - ['/file_b']
)
expect( dir_contents('~/Storage/dir_b') ).to eq(
dir_contents('~/test_data/dir_b') - ['/file_b']
)
expect( dir_contents('~/Storage/dir_c') ).to eq(
dir_contents('~/test_data/dir_c') - ['/file_b']
)
end
end # context 'using :ssh mode'
context 'using :ssh_daemon mode' do
specify 'single directory' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Pull do |rsync|
rsync.mode = :ssh_daemon
rsync.host = 'localhost'
rsync.path = '~/Storage'
rsync.directories do |dirs|
dirs.add 'ssh-daemon-module/test_data'
end
rsync.additional_rsync_options = '-vv'
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/test_data') ).
to eq( dir_contents('~/test_data') )
end
specify 'multiple directories' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Pull do |rsync|
rsync.mode = :ssh_daemon
rsync.host = 'localhost'
rsync.path = '~/Storage'
rsync.directories do |dirs|
dirs.add 'ssh-daemon-module/test_data/dir_a'
dirs.add 'ssh-daemon-module/test_data/dir_b'
dirs.add 'ssh-daemon-module/test_data/dir_c'
end
rsync.additional_rsync_options = '-vv'
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/dir_a') ).
to eq( dir_contents('~/test_data/dir_a') )
expect( dir_contents('~/Storage/dir_b') ).
to eq( dir_contents('~/test_data/dir_b') )
expect( dir_contents('~/Storage/dir_c') ).
to eq( dir_contents('~/test_data/dir_c') )
end
specify 'multiple directories with excludes' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Pull do |rsync|
rsync.mode = :ssh_daemon
rsync.host = 'localhost'
rsync.path = '~/Storage'
rsync.directories do |dirs|
dirs.add 'ssh-daemon-module/test_data/dir_a'
dirs.add 'ssh-daemon-module/test_data/dir_b'
dirs.add 'ssh-daemon-module/test_data/dir_c'
dirs.exclude 'file_b'
end
rsync.additional_rsync_options = '-vv'
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/dir_a') ).to eq(
dir_contents('~/test_data/dir_a') - ['/file_b']
)
expect( dir_contents('~/Storage/dir_b') ).to eq(
dir_contents('~/test_data/dir_b') - ['/file_b']
)
expect( dir_contents('~/Storage/dir_c') ).to eq(
dir_contents('~/test_data/dir_c') - ['/file_b']
)
end
end # context 'using :ssh_daemon mode'
context 'using :rsync_daemon mode' do
specify 'single directory' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Pull do |rsync|
rsync.mode = :rsync_daemon
rsync.host = 'localhost'
rsync.rsync_password = 'daemon-password'
rsync.path = '~/Storage'
rsync.directories do |dirs|
dirs.add 'rsync-daemon-module/test_data'
end
rsync.additional_rsync_options = '-vv'
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/test_data') ).
to eq( dir_contents('~/test_data') )
end
specify 'multiple directories' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Pull do |rsync|
rsync.mode = :rsync_daemon
rsync.host = 'localhost'
rsync.rsync_password = 'daemon-password'
rsync.path = '~/Storage'
rsync.directories do |dirs|
dirs.add 'rsync-daemon-module/test_data/dir_a'
dirs.add 'rsync-daemon-module/test_data/dir_b'
dirs.add 'rsync-daemon-module/test_data/dir_c'
end
rsync.additional_rsync_options = '-vv'
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/dir_a') ).
to eq( dir_contents('~/test_data/dir_a') )
expect( dir_contents('~/Storage/dir_b') ).
to eq( dir_contents('~/test_data/dir_b') )
expect( dir_contents('~/Storage/dir_c') ).
to eq( dir_contents('~/test_data/dir_c') )
end
specify 'multiple directories with excludes' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Pull do |rsync|
rsync.mode = :rsync_daemon
rsync.host = 'localhost'
rsync.rsync_password = 'daemon-password'
rsync.path = '~/Storage'
rsync.directories do |dirs|
dirs.add 'rsync-daemon-module/test_data/dir_a'
dirs.add 'rsync-daemon-module/test_data/dir_b'
dirs.add 'rsync-daemon-module/test_data/dir_c'
dirs.exclude 'file_b'
end
rsync.additional_rsync_options = '-vv'
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/dir_a') ).to eq(
dir_contents('~/test_data/dir_a') - ['/file_b']
)
expect( dir_contents('~/Storage/dir_b') ).to eq(
dir_contents('~/test_data/dir_b') - ['/file_b']
)
expect( dir_contents('~/Storage/dir_c') ).to eq(
dir_contents('~/test_data/dir_c') - ['/file_b']
)
end
end # context 'using :rsync_daemon mode'
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/acceptance/syncer/rsync/push_spec.rb | vagrant/spec/acceptance/syncer/rsync/push_spec.rb | require File.expand_path('../../../../spec_helper', __FILE__)
module Backup
describe Syncer::RSync::Push do
context 'using :ssh mode' do
specify 'single directory' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Push do |rsync|
rsync.host = 'localhost'
rsync.path = '~/Storage'
rsync.directories do |dirs|
dirs.add '~/test_data'
end
rsync.additional_rsync_options = '-vv'
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/test_data') ).
to eq( dir_contents('~/test_data') )
end
specify 'multiple directories' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Push do |rsync|
rsync.host = 'localhost'
rsync.path = '~/Storage'
rsync.directories do |dirs|
dirs.add '~/test_data/dir_a'
dirs.add '~/test_data/dir_b'
dirs.add '~/test_data/dir_c'
end
rsync.additional_rsync_options = '-vv'
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/dir_a') ).
to eq( dir_contents('~/test_data/dir_a') )
expect( dir_contents('~/Storage/dir_b') ).
to eq( dir_contents('~/test_data/dir_b') )
expect( dir_contents('~/Storage/dir_c') ).
to eq( dir_contents('~/test_data/dir_c') )
end
specify 'multiple directories with excludes' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Push do |rsync|
rsync.host = 'localhost'
rsync.path = '~/Storage'
rsync.directories do |dirs|
dirs.add '~/test_data/dir_a'
dirs.add '~/test_data/dir_b'
dirs.add '~/test_data/dir_c'
dirs.exclude 'file_b'
end
rsync.additional_rsync_options = '-vv'
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/dir_a') ).to eq(
dir_contents('~/test_data/dir_a') - ['/file_b']
)
expect( dir_contents('~/Storage/dir_b') ).to eq(
dir_contents('~/test_data/dir_b') - ['/file_b']
)
expect( dir_contents('~/Storage/dir_c') ).to eq(
dir_contents('~/test_data/dir_c') - ['/file_b']
)
end
end # context 'using :ssh mode'
context 'using :ssh_daemon mode' do
specify 'single directory' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Push do |rsync|
rsync.mode = :ssh_daemon
rsync.host = 'localhost'
rsync.path = 'ssh-daemon-module/Storage'
rsync.directories do |dirs|
dirs.add '~/test_data'
end
rsync.additional_rsync_options = '-vv'
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/test_data') ).
to eq( dir_contents('~/test_data') )
end
specify 'multiple directories' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Push do |rsync|
rsync.mode = :ssh_daemon
rsync.host = 'localhost'
rsync.path = 'ssh-daemon-module/Storage'
rsync.directories do |dirs|
dirs.add '~/test_data/dir_a'
dirs.add '~/test_data/dir_b'
dirs.add '~/test_data/dir_c'
end
rsync.additional_rsync_options = '-vv'
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/dir_a') ).
to eq( dir_contents('~/test_data/dir_a') )
expect( dir_contents('~/Storage/dir_b') ).
to eq( dir_contents('~/test_data/dir_b') )
expect( dir_contents('~/Storage/dir_c') ).
to eq( dir_contents('~/test_data/dir_c') )
end
specify 'multiple directories with excludes' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Push do |rsync|
rsync.mode = :ssh_daemon
rsync.host = 'localhost'
rsync.path = 'ssh-daemon-module/Storage'
rsync.directories do |dirs|
dirs.add '~/test_data/dir_a'
dirs.add '~/test_data/dir_b'
dirs.add '~/test_data/dir_c'
dirs.exclude 'file_b'
end
rsync.additional_rsync_options = '-vv'
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/dir_a') ).to eq(
dir_contents('~/test_data/dir_a') - ['/file_b']
)
expect( dir_contents('~/Storage/dir_b') ).to eq(
dir_contents('~/test_data/dir_b') - ['/file_b']
)
expect( dir_contents('~/Storage/dir_c') ).to eq(
dir_contents('~/test_data/dir_c') - ['/file_b']
)
end
end # context 'using :ssh_daemon mode'
context 'using :rsync_daemon mode' do
specify 'single directory' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Push do |rsync|
rsync.mode = :rsync_daemon
rsync.host = 'localhost'
rsync.rsync_password = 'daemon-password'
rsync.path = 'rsync-daemon-module/Storage'
rsync.directories do |dirs|
dirs.add '~/test_data'
end
rsync.additional_rsync_options = '-vv'
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/test_data') ).
to eq( dir_contents('~/test_data') )
end
specify 'multiple directories' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Push do |rsync|
rsync.mode = :rsync_daemon
rsync.host = 'localhost'
rsync.rsync_password = 'daemon-password'
rsync.path = 'rsync-daemon-module/Storage'
rsync.directories do |dirs|
dirs.add '~/test_data/dir_a'
dirs.add '~/test_data/dir_b'
dirs.add '~/test_data/dir_c'
end
rsync.additional_rsync_options = '-vv'
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/dir_a') ).
to eq( dir_contents('~/test_data/dir_a') )
expect( dir_contents('~/Storage/dir_b') ).
to eq( dir_contents('~/test_data/dir_b') )
expect( dir_contents('~/Storage/dir_c') ).
to eq( dir_contents('~/test_data/dir_c') )
end
specify 'multiple directories with excludes' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Push do |rsync|
rsync.mode = :rsync_daemon
rsync.host = 'localhost'
rsync.rsync_password = 'daemon-password'
rsync.path = 'rsync-daemon-module/Storage'
rsync.directories do |dirs|
dirs.add '~/test_data/dir_a'
dirs.add '~/test_data/dir_b'
dirs.add '~/test_data/dir_c'
dirs.exclude 'file_b'
end
rsync.additional_rsync_options = '-vv'
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/dir_a') ).to eq(
dir_contents('~/test_data/dir_a') - ['/file_b']
)
expect( dir_contents('~/Storage/dir_b') ).to eq(
dir_contents('~/test_data/dir_b') - ['/file_b']
)
expect( dir_contents('~/Storage/dir_c') ).to eq(
dir_contents('~/test_data/dir_c') - ['/file_b']
)
end
end # context 'using :rsync_daemon mode'
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/acceptance/syncer/rsync/local_spec.rb | vagrant/spec/acceptance/syncer/rsync/local_spec.rb | require File.expand_path('../../../../spec_helper', __FILE__)
module Backup
describe Syncer::RSync::Local do
specify 'single directory' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Local do |rsync|
rsync.path = '~/Storage'
rsync.directories do |dirs|
dirs.add '~/test_data'
end
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/test_data') ).
to eq( dir_contents('~/test_data') )
end
specify 'multiple directories' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Local do |rsync|
rsync.path = '~/Storage'
rsync.directories do |dirs|
dirs.add '~/test_data/dir_a'
dirs.add '~/test_data/dir_b'
dirs.add '~/test_data/dir_c'
end
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/dir_a') ).
to eq( dir_contents('~/test_data/dir_a') )
expect( dir_contents('~/Storage/dir_b') ).
to eq( dir_contents('~/test_data/dir_b') )
expect( dir_contents('~/Storage/dir_c') ).
to eq( dir_contents('~/test_data/dir_c') )
end
specify 'multiple directories with excludes' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
sync_with RSync::Local do |rsync|
rsync.path = '~/Storage'
rsync.directories do |dirs|
dirs.add '~/test_data/dir_a'
dirs.add '~/test_data/dir_b'
dirs.add '~/test_data/dir_c'
dirs.exclude 'file_b'
end
end
end
EOS
backup_perform :my_backup
expect( dir_contents('~/Storage/dir_a') ).to eq(
dir_contents('~/test_data/dir_a') - ['/file_b']
)
expect( dir_contents('~/Storage/dir_b') ).to eq(
dir_contents('~/test_data/dir_b') - ['/file_b']
)
expect( dir_contents('~/Storage/dir_c') ).to eq(
dir_contents('~/test_data/dir_c') - ['/file_b']
)
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/acceptance/encryptor/gpg_spec.rb | vagrant/spec/acceptance/encryptor/gpg_spec.rb | require File.expand_path('../../../spec_helper', __FILE__)
module Backup
describe Encryptor::GPG do
specify ':asymmetric mode with preloaded and imported keys' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
archive :my_archive do |archive|
archive.add '~/test_data'
end
encrypt_with GPG do |encryptor|
# encryptor.mode = :asymmetric (default mode)
encryptor.gpg_homedir = BackupSpec::GPG_HOME_DIR
encryptor.keys = {
# backup03 public key (email as identifier)
'backup03@foo.com' => BackupSpec::GPGKeys[:backup03][:public],
# backup04 public key (long key id as identifier)
'0F45932D3F24426D' => BackupSpec::GPGKeys[:backup04][:public]
}
encryptor.recipients = [
# backup01 (short keyid)
'16325C61',
# backup02 (key fingerprint)
'F9A9 9BD8 A570 182F F190 037C 7118 9938 6A6A 175A',
# backup03 (email)
'backup03@foo.com',
# backup04 (long keyid)
'0F45932D3F24426D'
]
end
store_with Local
end
EOS
# Preload keys for :backup01 and :backup02.
# The keys for :backup03 and :backup04 will be imported from #keys.
import_public_keys_for :backup01, :backup02
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package.path.end_with?('.gpg') ).to be_true
expect( decrypt_with_user(:backup01, job.package.path) ).to be_true
expect( decrypt_with_user(:backup02, job.package.path) ).to be_true
expect( decrypt_with_user(:backup03, job.package.path) ).to be_true
expect( decrypt_with_user(:backup04, job.package.path) ).to be_true
end
specify ':asymmetric mode with missing recipient key' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
archive :my_archive do |archive|
archive.add '~/test_data'
end
encrypt_with GPG do |encryptor|
encryptor.mode = :asymmetric
encryptor.gpg_homedir = BackupSpec::GPG_HOME_DIR
encryptor.keys = {
'backup02@foo.com' => BackupSpec::GPGKeys[:backup02][:public],
}
encryptor.recipients = [
'backup01@foo.com', # preloaded in the system
'backup02@foo.com', # imported from #keys
'backupfoo@foo.com' # no public key available
]
end
store_with Local
end
EOS
import_public_keys_for :backup01
job = backup_perform :my_backup, :exit_status => 1
expect( job.package.exist? ).to be_true
expect( job.package.path.end_with?('.gpg') ).to be_true
expect( job.logger.has_warnings? ).to be_true
log_messages = job.logger.messages.map(&:lines).flatten.join
expect( log_messages ).to match(
/No public key was found in #keys for '<backupfoo@foo.com>'/
)
expect( decrypt_with_user(:backup01, job.package.path) ).to be_true
expect( decrypt_with_user(:backup02, job.package.path) ).to be_true
end
specify ':asymmetric mode with no recipient keys' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
archive :my_archive do |archive|
archive.add '~/test_data'
end
encrypt_with GPG do |encryptor|
encryptor.mode = :asymmetric
encryptor.gpg_homedir = BackupSpec::GPG_HOME_DIR
encryptor.recipients = [
'backupfoo@foo.com',
'backupfoo2@foo.com'
]
end
store_with Local
end
EOS
import_public_keys_for :backup01
job = backup_perform :my_backup, :exit_status => 2
expect( job.package.exist? ).to be_false
expect( job.logger.has_warnings? ).to be_true
log_messages = job.logger.messages.map(&:formatted_lines).flatten.join
# issues warnings about the missing keys
expect( log_messages ).to match(
/\[warn\] No public key was found in #keys for '<backupfoo@foo.com>'/
)
expect( log_messages ).to match(
/\[warn\] No public key was found in #keys for '<backupfoo2@foo.com>'/
)
# issues warning about not being able to perform asymmetric encryption
expect( log_messages ).to match(
/\[warn\] No recipients available for asymmetric encryption/
)
# since there are no other options for encryption, the backup fails
expect( log_messages ).to match(
/\[error\]\sEncryptor::GPG::Error:\s
Encryption\scould\snot\sbe\sperformed\sfor\smode\s'asymmetric'/x
)
end
specify ':symmetric mode' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
archive :my_archive do |archive|
archive.add '~/test_data'
end
encrypt_with GPG do |encryptor|
encryptor.mode = :symmetric
encryptor.gpg_homedir = BackupSpec::GPG_HOME_DIR
encryptor.passphrase = 'a secret'
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package.path.end_with?('.gpg') ).to be_true
expect( decrypt_with_passphrase('a secret', job.package.path) ).to be_true
# without specifying any preferences, the default algorithm used is CAST5
# (these log messages are generated by #decrypt_with_passphrase)
log_messages = Backup::Logger.messages.map(&:formatted_lines).flatten.join
expect( log_messages ).to match(/gpg: CAST5 encrypted data/)
end
specify ':symmetric mode with gpg_config' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
archive :my_archive do |archive|
archive.add '~/test_data'
end
encrypt_with GPG do |encryptor|
encryptor.mode = :symmetric
encryptor.gpg_homedir = BackupSpec::GPG_HOME_DIR
encryptor.passphrase = 'a secret'
encryptor.gpg_config = <<-CONFIG
personal-cipher-preferences AES256 CAST5
CONFIG
end
store_with Local
end
EOS
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package.path.end_with?('.gpg') ).to be_true
expect( decrypt_with_passphrase('a secret', job.package.path) ).to be_true
# preferences specified using AES256 before CAST5
# (these log messages are generated by #decrypt_with_passphrase)
log_messages = Backup::Logger.messages.map(&:formatted_lines).flatten.join
expect( log_messages ).to match(/gpg: AES256 encrypted data/)
end
specify ':both mode' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
archive :my_archive do |archive|
archive.add '~/test_data'
end
encrypt_with GPG do |encryptor|
encryptor.mode = :both
encryptor.gpg_homedir = BackupSpec::GPG_HOME_DIR
encryptor.keys = {
'backup03@foo.com' => BackupSpec::GPGKeys[:backup03][:public],
}
encryptor.passphrase = 'a secret'
encryptor.recipients = [
# backup01 (short keyid)
'16325C61',
# backup03 (email)
'backup03@foo.com'
]
end
store_with Local
end
EOS
# Preload keys for :backup01
# The key for :backup03 will be imported from #keys.
import_public_keys_for :backup01
job = backup_perform :my_backup
expect( job.package.exist? ).to be_true
expect( job.package.path.end_with?('.gpg') ).to be_true
expect( decrypt_with_user(:backup01, job.package.path) ).to be_true
expect( decrypt_with_user(:backup03, job.package.path) ).to be_true
expect( decrypt_with_passphrase('a secret', job.package.path) ).to be_true
end
specify ':both mode with no asymmetric recipient keys' do
create_model :my_backup, <<-EOS
Backup::Model.new(:my_backup, 'a description') do
archive :my_archive do |archive|
archive.add '~/test_data'
end
encrypt_with GPG do |encryptor|
encryptor.mode = :both
encryptor.gpg_homedir = BackupSpec::GPG_HOME_DIR
# not a recipient
encryptor.keys = {
'backup02@foo.com' => BackupSpec::GPGKeys[:backup02][:public],
}
encryptor.passphrase = 'a secret'
# no keys will be imported or found for these identifiers
encryptor.recipients = [
# backup01 (short keyid)
'16325C61',
# backup03 (email)
'backup03@foo.com'
]
end
store_with Local
end
EOS
# :backup04 is preloaded, :backup01 is imported, but neither are recipients
import_public_keys_for :backup04
job = backup_perform :my_backup, :exit_status => 1
expect( job.package.exist? ).to be_true
expect( job.package.path.end_with?('.gpg') ).to be_true
expect( job.logger.has_warnings? ).to be_true
log_messages = job.logger.messages.map(&:formatted_lines).flatten.join
# issues warnings about the missing keys
expect( log_messages ).to match(
/\[warn\] No public key was found in #keys for '16325C61'/
)
expect( log_messages ).to match(
/\[warn\] No public key was found in #keys for '<backup03@foo.com>'/
)
# issues warning about not being able to perform asymmetric encryption
expect( log_messages ).to match(
/\[warn\] No recipients available for asymmetric encryption/
)
expect( decrypt_with_passphrase('a secret', job.package.path) ).to be_true
end
private
def gpg_encryptor
@gpg_encryptor ||= Backup::Encryptor::GPG.new do |gpg|
gpg.gpg_homedir = BackupSpec::GPG_HOME_DIR
end
end
def clean_homedir
FileUtils.rm_rf BackupSpec::GPG_HOME_DIR
gpg_encryptor.send(:setup_gpg_homedir)
end
def import_public_keys_for(*users)
setup_homedir(:public, users)
end
def import_private_keys_for(*users)
setup_homedir(:private, users)
end
# reset the homedir and import keys needed for the test
def setup_homedir(key_type, users)
clean_homedir
# This is removed after each test run, but must exist for #import_key
FileUtils.mkdir_p Config.tmp_path
# GPG#import_key will log a warning if the import is unsuccessful,
# so we'll abort here if the returned keyid is incorrect.
users.each do |user|
keyid = gpg_encryptor.send(:import_key,
user, BackupSpec::GPGKeys[user][key_type]
)
unless keyid == BackupSpec::GPGKeys[user][:long_id]
warn Backup::Logger.messages.map(&:lines).flatten.join("\n")
abort('setup_homedir failed')
end
end
end
def decrypt_with_user(user, path)
import_private_keys_for(user)
decrypt(path)
end
def decrypt_with_passphrase(passphrase, path)
clean_homedir
decrypt(path, passphrase)
end
# returns true if successful and the decrypted tar contents are correct
# returns false if decryption failed, or will fail the expectation
def decrypt(path, passphrase = nil)
outfile = File.join(File.dirname(path), 'decrypted.tar')
FileUtils.rm_f outfile
pass_opt = "--passphrase '#{ passphrase }'" if passphrase
gpg_encryptor.send(:run,
"#{ gpg_encryptor.send(:utility, :gpg) } " +
"#{ gpg_encryptor.send(:base_options) } " +
"#{ pass_opt } -o '#{ outfile }' -d '#{ path }' 2>&1"
)
if File.exist?(outfile)
expect( BackupSpec::TarFile.new(outfile) ).to match_manifest(%q[
1_105_920 my_backup/archives/my_archive.tar
])
else
false
end
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
backup/backup | https://github.com/backup/backup/blob/86c9b07c2a2974376888b1506001f77792d6359a/vagrant/spec/live/storage/s3_spec.rb | vagrant/spec/live/storage/s3_spec.rb | require File.expand_path('../../../spec_helper', __FILE__)
# To run these tests, you need to setup your AWS S3 credentials in
# /vagrant/spec/live.yml
#
# It's recommended you use a dedicated Bucket for this, like:
# <aws_username>-backup-testing
#
# Note: The S3 Bucket you use should have read-after-write consistency.
# So don't use the US Standard region.
module Backup
describe Storage::S3,
:if => BackupSpec::LIVE['storage']['s3']['specs_enabled'] == true do
before { clean_remote }
after { clean_remote }
# Each archive is 1.09 MB (1,090,000).
# This will create 2 package files (6,291,456 + 248,544).
# The default/minimum chunk_size for multipart upload is 5 MiB.
# The first package file will use multipart, the second won't.
it 'stores package', :live do
create_model :my_backup, %q{
Backup::Model.new(:my_backup, 'a description') do
split_into_chunks_of 6 # MiB
6.times do |n|
archive "archive_#{ n }" do |archive|
archive.add '~/test_data'
end
end
config = BackupSpec::LIVE['storage']['s3']
store_with S3 do |s3|
s3.access_key_id = config['access_key_id']
s3.secret_access_key = config['secret_access_key']
s3.region = config['region']
s3.bucket = config['bucket']
s3.path = config['path']
s3.max_retries = 3
s3.retry_waitsec = 5
end
end
}
job = backup_perform :my_backup
files_sent = files_sent_for(job)
expect( files_sent.count ).to be(2)
objects_on_remote = objects_on_remote_for(job)
expect( objects_on_remote.map(&:key) ).to eq files_sent
expect(
objects_on_remote.all? {|obj| obj.storage_class == 'STANDARD' }
).to be(true)
expect(
objects_on_remote.all? {|obj| obj.encryption.nil? }
).to be(true)
end
it 'uses server-side encryption and reduced redundancy', :live do
create_model :my_backup, %q{
Backup::Model.new(:my_backup, 'a description') do
split_into_chunks_of 6 # MiB
6.times do |n|
archive "archive_#{ n }" do |archive|
archive.add '~/test_data'
end
end
config = BackupSpec::LIVE['storage']['s3']
store_with S3 do |s3|
s3.access_key_id = config['access_key_id']
s3.secret_access_key = config['secret_access_key']
s3.region = config['region']
s3.bucket = config['bucket']
s3.path = config['path']
s3.max_retries = 3
s3.retry_waitsec = 5
s3.encryption = :aes256
s3.storage_class = :reduced_redundancy
end
end
}
job = backup_perform :my_backup
files_sent = files_sent_for(job)
expect( files_sent.count ).to be(2)
objects_on_remote = objects_on_remote_for(job)
expect( objects_on_remote.map(&:key) ).to eq files_sent
expect(
objects_on_remote.all? {|obj| obj.storage_class == 'REDUCED_REDUNDANCY' }
).to be(true)
expect(
objects_on_remote.all? {|obj| obj.encryption == 'AES256' }
).to be(true)
end
it 'cycles stored packages', :live do
create_model :my_backup, %q{
Backup::Model.new(:my_backup, 'a description') do
split_into_chunks_of 6 # MiB
6.times do |n|
archive "archive_#{ n }" do |archive|
archive.add '~/test_data'
end
end
config = BackupSpec::LIVE['storage']['s3']
store_with S3 do |s3|
s3.access_key_id = config['access_key_id']
s3.secret_access_key = config['secret_access_key']
s3.region = config['region']
s3.bucket = config['bucket']
s3.path = config['path']
s3.max_retries = 3
s3.retry_waitsec = 5
s3.keep = 2
end
end
}
job_a = backup_perform :my_backup
job_b = backup_perform :my_backup
# package files for job_a should be on the remote
files_sent = files_sent_for(job_a)
expect( files_sent.count ).to be(2)
expect( objects_on_remote_for(job_a).map(&:key) ).to eq files_sent
# package files for job_b should be on the remote
files_sent = files_sent_for(job_b)
expect( files_sent.count ).to be(2)
expect( objects_on_remote_for(job_b).map(&:key) ).to eq files_sent
job_c = backup_perform :my_backup
# package files for job_b should still be on the remote
files_sent = files_sent_for(job_b)
expect( files_sent.count ).to be(2)
expect( objects_on_remote_for(job_b).map(&:key) ).to eq files_sent
# package files for job_c should be on the remote
files_sent = files_sent_for(job_c)
expect( files_sent.count ).to be(2)
expect( objects_on_remote_for(job_c).map(&:key) ).to eq files_sent
# package files for job_a should be gone
expect( objects_on_remote_for(job_a) ).to be_empty
end
private
def cloud_io
config = BackupSpec::LIVE['storage']['s3']
@cloud_io ||= CloudIO::S3.new(
:access_key_id => config['access_key_id'],
:secret_access_key => config['secret_access_key'],
:region => config['region'],
:bucket => config['bucket'],
:path => config['path'],
:chunk_size => 0,
:max_retries => 3,
:retry_waitsec => 5
)
end
def files_sent_for(job)
job.model.package.filenames.map {|name|
File.join(remote_path_for(job), name)
}.sort
end
def remote_path_for(job)
path = BackupSpec::LIVE['storage']['s3']['path']
package = job.model.package
File.join(path, package.trigger, package.time)
end
# objects_on_remote_for(job).map(&:key) should match #files_sent_for(job).
# If the files do not exist, or were removed by cycling, this will return [].
def objects_on_remote_for(job)
cloud_io.objects(remote_path_for(job)).sort_by(&:key)
end
def clean_remote
path = BackupSpec::LIVE['storage']['s3']['path']
objects = cloud_io.objects(path)
cloud_io.delete(objects) unless objects.empty?
end
end
end
| ruby | MIT | 86c9b07c2a2974376888b1506001f77792d6359a | 2026-01-04T15:45:04.712671Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.