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 |
|---|---|---|---|---|---|---|---|---|
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/test/test_change_expectation.rb | test/test_change_expectation.rb | require File.dirname(__FILE__) + '/test_helper.rb'
class TestChangeExpectations < Test::Unit::TestCase
def test_change
var = 1
lambda {var += 1}.should change {var}
end
def test_change_fails
var = 1
lambda do
lambda { }.should change {var}
end.should raise_error
end
def test_change_by
var = 1
lambda {var += 1}.should change {var}.by(1)
end
def test_change_by_fails
var = 1
lambda do
lambda {var += 2}.should change {var}.by(1)
end.should raise_error
end
def test_change_by_at_least
var = 1
lambda {var += 1}.should change {var}.by_at_least(1)
end
def test_change_by_at_least_fails
var = 1
lambda do
lambda {var += 0.9}.should change {var}.by_at_least(1)
end.should raise_error
end
def test_change_by_at_most
var = 1
lambda {var += 1}.should change {var}.by_at_most(1)
end
def test_change_by_at_most_fails
var = 1
lambda do
lambda {var += 1.1}.should change {var}.by_at_most(1)
end.should raise_error
end
def test_change_from_to
var = 1
lambda {var += 1}.should change {var}.from(1).to(2)
end
def test_change_from_to_fails
var = 1
lambda do
lambda {var += 1.1}.should change {var}.from(1).to(2)
end.should raise_error
end
end | ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/test/test_matcher_builder.rb | test/test_matcher_builder.rb | require File.dirname(__FILE__) + '/test_helper.rb'
class TestMatcherBuilder < Test::Unit::TestCase
include Matchy::MatcherBuilder
def setup
@obj = Object.new
end
def test_matcher_responds_to_matches
block = lambda {|given, matcher, args| true}
build_matcher(:m, &block).should respond_to(:matches?)
end
def test_fail_positive
block = lambda {|given, matcher, args| false}
lambda {@obj.should build_matcher(:m, &block)}.should raise_error
end
def test_pass_positive
block = lambda {|given, matcher, args| true}
@obj.should build_matcher(:m, &block)
end
def test_fail_negative
block = lambda {|given, matcher, args| true}
lambda {@obj.should_not build_matcher(:m, &block)}.should raise_error
end
def test_pass_negative
block = lambda {|given, matcher, args| false}
@obj.should_not build_matcher(:m, &block)
end
def test_takes_arguments
block = lambda {|given, matcher, args| $args = args; true}
@obj.should build_matcher(:m,[1,2,3], &block)
$args.should eql([1,2,3])
end
def test_received_method
block = lambda {|given, matcher, args| $msgs = matcher.msgs; true}
@obj.should build_matcher(:m, &block).method1
$msgs[0].name.should eql(:method1)
end
def test_received_method_takes_args
block = lambda {|given, matcher, args| $msgs = matcher.msgs; true}
@obj.should build_matcher(:m, &block).method1(1,2,3)
$msgs[0].args.should eql([1,2,3])
end
def test_received_method_takes_block
block = lambda {|given, matcher, args| $msgs = matcher.msgs; true}
@obj.should build_matcher(:m, &block).method1 { "Hello, World!"}
$msgs[0].block.call.should eql("Hello, World!")
end
def test_received_method_chained
block = lambda {|given, matcher, args| $msgs = matcher.msgs; true}
@obj.should build_matcher(:m, &block).method1(1,2,3) { "Hello, World!"}.
method2(4,5,6) { "Hello chained messages" }
$msgs[0].name.should eql(:method1)
$msgs[1].name.should eql(:method2)
$msgs[0].args.should eql([1,2,3])
$msgs[1].args.should eql([4,5,6])
$msgs[0].block.call.should eql("Hello, World!")
$msgs[1].block.call.should eql("Hello chained messages")
end
end
| ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/test/test_modals.rb | test/test_modals.rb | require File.dirname(__FILE__) + '/test_helper.rb'
class TestModals < Test::Unit::TestCase
def setup
@expectation = build_matcher() {|r,m,a| true}
@bad_expectation = build_matcher() {|r,m,a| false}
end
def test_should
3.should(@expectation)
end
def test_will
3.will(@expectation)
end
def test_should_not
3.should_not(@bad_expectation)
end
def test_will_not
3.will_not(@bad_expectation)
end
def test_wont
3.wont(@bad_expectation)
end
def test_should_operator_expectation_returned
obj = 3.should
assert_equal Matchy::Expectations::OperatorExpectation, obj.class
end
def test_should_not_operator_expectation_returned
obj = 3.should_not
assert_equal Matchy::Expectations::OperatorExpectation, obj.class
end
end
| ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/test/test_helper.rb | test/test_helper.rb | require File.dirname(__FILE__) + '/../lib/matchy.rb'
| ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/test/test_operator_expectations.rb | test/test_operator_expectations.rb | require File.dirname(__FILE__) + '/test_helper.rb'
class TestOperatorExpectations < Test::Unit::TestCase
# EQUALS (==)
def test_equals
3.should == 3
end
def test_equals_fails
lambda {
3.should == 5
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_negative_equals
3.should_not == 4
end
def test_negative_equals_fails
lambda {
3.should_not == 3
}.should raise_error(Test::Unit::AssertionFailedError)
end
# LESS THAN (<)
def test_less_than
3.should < 5
end
def test_less_than_fails
lambda {
4.should < 3
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_less_than_equals
3.should_not < 2
end
def test_negative_less_than_fails
lambda {
4.should_not < 5
}.should raise_error(Test::Unit::AssertionFailedError)
end
# GREATER THAN (>)
def test_greater_than
3.should > 2
end
def test_greater_than_fails
lambda {
4.should > 5
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_greater_than_equals
3.should_not > 5
end
def test_negative_greater_than_fails
lambda {
4.should_not > 3
}.should raise_error(Test::Unit::AssertionFailedError)
end
# LESS THAN EQUAL (<=)
def test_less_than_equal
3.should <= 5
end
def test_less_than_equal_equal
3.should <= 3
end
def test_less_than_equal_fails
lambda {
4.should <= 3
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_negative_less_than_equal
3.should_not <= 2
end
def test_negative_less_than_equal_fails
lambda {
4.should_not <= 5
}.should raise_error(Test::Unit::AssertionFailedError)
end
# GREATER THAN EQUALS (>=)
def test_greater_than_equal
3.should >= 2
end
def test_greater_than_equal_equals
3.should >= 3
end
def test_greater_than_equal_fails
lambda {
4.should >= 5
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_negative_greater_than_equal_equals
3.should_not >= 5
end
def test_negative_greater_than_equal_fails
lambda {
4.should_not >= 3
}.should raise_error(Test::Unit::AssertionFailedError)
end
# MATCHES (=~)
def test_matches
"hey world".should =~ /world/
end
def test_matches_fails
lambda {
"d00d ur 1337".should =~ /world/
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_negative_matches
"1337@age".should_not =~ /434/
end
def test_negative_matches_fails
lambda {
"it's a freak out!".should_not =~ /freak/
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_fail_message
obj = Matchy::Expectations::OperatorExpectation.new(3, true)
def obj.flunk(msg)
msg
end
(obj == 4).should == "Expected 3 to == 4."
end
def test_negative_fail_message
obj = Matchy::Expectations::OperatorExpectation.new(3, false)
def obj.flunk(msg)
msg
end
(obj == 3).should == "Expected 3 to not == 3."
end
end
| ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/test/test_expectation_builder.rb | test/test_expectation_builder.rb | require File.dirname(__FILE__) + '/test_helper.rb'
class TestExpectationBuilder < Test::Unit::TestCase
def setup
@obj = Object.new
end
def test_should
exp = Matchy::ExpectationBuilder.build_expectation(true, nil, @obj)
exp.send(:==, @obj)
end
def test_should_fails
expect_1 = Matchy::ExpectationBuilder.build_expectation(true, nil, 1)
lambda {expect_1.send(:==, 2)}.should raise_error
end
def test_should_not
exp = Matchy::ExpectationBuilder.build_expectation(false, nil, @obj)
exp.send(:==, 1)
end
def test_should_not_fails
expect_not_1 = Matchy::ExpectationBuilder.build_expectation(false, nil, 1)
lambda {expect_not_1.send(:==, 1)}.should raise_error
end
end | ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/test/test_def_matcher.rb | test/test_def_matcher.rb | require File.dirname(__FILE__) + '/test_helper.rb'
class TestDefMatcher < Test::Unit::TestCase
def setup
@obj = Object.new
end
def test_defines_method
def_matcher :method_ do |given, matcher, args|
end
self.should respond_to(:method_)
end
def test_object_responds_to_matches
def_matcher :method_ do |given, matcher, args|
end
method_.should respond_to(:matches?)
end
def test_fail_positive
def_matcher :matcher do |given, matcher, args|
false
end
lambda {1.should matcher}.should raise_error
end
def test_pass_positive
def_matcher :matcher do |given, matcher, args|
true
end
1.should matcher
end
def test_fail_negative
def_matcher :matcher do |given, matcher, args|
true
end
lambda {1.should_not matcher}.should raise_error
end
def test_pass_negative
def_matcher :matcher do |given, matcher, args|
false
end
1.should_not matcher
end
def test_takes_arguments
def_matcher :matcher do |given, matcher, args|
$args = args
true
end
@obj.should matcher(1,2,3)
$args.should eql([1,2,3])
end
def test_received_method
def_matcher :matcher do |given, matcher, args|
$msgs = matcher.msgs
true
end
@obj.should matcher.method1
$msgs[0].name.should eql(:method1)
end
def test_received_method_takes_args
def_matcher :matcher do |given, matcher, args|
$msgs = matcher.msgs
true
end
@obj.should matcher.method1(1,2,3)
$msgs[0].args.should eql([1,2,3])
end
def test_received_method_takes_block
def_matcher :matcher do |given, matcher, args|
$msgs = matcher.msgs
true
end
@obj.should matcher.method1 { "Hello, World!"}
$msgs[0].block.call.should eql("Hello, World!")
end
def test_received_method_chained
def_matcher :matcher do |given, matcher, args|
$msgs = matcher.msgs
true
end
@obj.should matcher.method1(1,2,3) { "Hello, World!"}.
method2(4,5,6) { "Hello chained messages" }
$msgs[0].name.should eql(:method1)
$msgs[1].name.should eql(:method2)
$msgs[0].args.should eql([1,2,3])
$msgs[1].args.should eql([4,5,6])
$msgs[0].block.call.should eql("Hello, World!")
$msgs[1].block.call.should eql("Hello chained messages")
end
end
| ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/test/test_truth_expectations.rb | test/test_truth_expectations.rb | require File.dirname(__FILE__) + '/test_helper.rb'
class Exister
def initialize(what)
@what = what
end
def exist?
@what
end
end
class TestTruthExpectations < Test::Unit::TestCase
def setup
@obj = Object.new
end
def test_equal
3.should equal(3)
end
def test_negative_equal
instance = String.new
instance.should_not equal(String.new)
end
def test_equal_fail
lambda {
3.should equal(4)
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_negative_equal_fail
lambda {
3.should_not equal(3)
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_eql
3.should eql(3)
end
def test_eql_array
[1,2,3].should eql([1,2,3])
end
def test_negative_eql
3.should_not eql(9)
end
def test_eql_fail
lambda {
3.should eql(13)
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_negative_eql_fail
lambda {
3.should_not eql(3)
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_exists
thing = Exister.new(true)
thing.should exist
end
def test_negative_exists
thing = Exister.new(false)
thing.should_not exist
end
def test_exists_fail
lambda {
thing = Exister.new(false)
thing.should exist
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_negative_exists_fail
lambda {
thing = Exister.new(true)
thing.should_not exist
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_be
true.should be(true)
end
def test_be_array
[1,2,3].should be([1,2,3])
end
def test_negative_be
true.should_not be(false)
end
def test_be_fail
lambda {
true.should be(false)
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_be_close
(5.0 - 2.0).should be_close(3.0)
end
def test_be_close_with_delta
(5.0 - 2.0).should be_close(3.0, 0.2)
end
def test_be_close_fail
lambda {
(19.0 - 13.0).should be_close(33.04)
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_be_close_with_delta_fail
lambda {
(19.0 - 13.0).should be_close(6.0, 0.0)
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_satisfy
13.should satisfy(lambda {|i| i < 15})
end
def test_negative_satisfy
13.should_not satisfy(lambda {|i| i < 10})
end
def test_satisfy_fail
lambda {
13.should satisfy(lambda {|i| i > 15})
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_negative_satisfy_fail
lambda {
13.should_not satisfy(lambda {|i| i < 15})
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_equal_fail_message
obj = equal(4)
obj.matches?(5)
obj.failure_message.should be("Expected 5 to return true for equal?, with '4'.")
end
def test_equal_negative_fail_message
obj = equal(5)
obj.matches?(5)
obj.negative_failure_message.should be("Expected 5 to not return true for equal?, with '5'.")
end
def test_eql_fail_message
obj = eql(4)
obj.matches?(5)
obj.failure_message.should be("Expected 5 to return true for eql?, with '4'.")
end
def test_eql_negative_fail_message_for_eql
obj = eql(5)
obj.matches?(5)
obj.negative_failure_message.should be("Expected 5 to not return true for eql?, with '5'.")
end
def test_exist_fail_message
obj = exist
obj.matches?(Exister.new(false))
obj.failure_message.should =~ /Expected #<(.*)> to return true for exist?./
end
def test_exist_negative_fail_message
obj = exist
obj.matches?(Exister.new(true))
obj.negative_failure_message.should =~ /Expected #<(.*)> to not return true for exist?./
end
def test_be_close_fail_message
obj = be_close(3.0)
obj.matches?(6.0)
obj.failure_message.should be("Expected 6.0 to be close to 3.0 (delta: 0.3).")
end
def test_be_close_negative_fail_message
obj = be_close(5.0)
obj.matches?(5.0)
obj.negative_failure_message.should be("Expected 5.0 to not be close to 5.0 (delta: 0.3).")
end
def test_be_fail_message
obj = be(4)
obj.matches?(5)
obj.failure_message.should be("Expected 5 to be 4.")
end
def test_be_negative_fail_message
obj = be(5)
obj.matches?(5)
obj.negative_failure_message.should be("Expected 5 to not be 5.")
end
def test_satisfy_fail_message
obj = satisfy(lambda {|x| x == 4})
obj.matches?(6)
obj.failure_message.should be("Expected 6 to satisfy given block.")
end
def test_eql_negative_fail_message_for_matches
obj = satisfy(lambda {|x| x == 4})
obj.matches?(4)
obj.negative_failure_message.should be("Expected 4 to not satisfy given block.")
end
def test_kind_of
3.should be_kind_of(Fixnum)
end
def test_kind_of_fail
lambda {
3.should be_kind_of(Hash)
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_negative_kind_of
3.should_not be_kind_of(Hash)
end
def test_negative_kind_of_fail
lambda {
3.should_not be_kind_of(Fixnum)
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_respond_to
"foo".should respond_to(:length)
end
def test_respond_to_fail
lambda {
"foo".should respond_to(:nonexistant_method)
}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_negative_respond_to
"foo".should_not respond_to(:nonexistant_method)
end
def test_negative_respond_to_fail
lambda {
"foo".should_not respond_to(:length)
}.should raise_error(Test::Unit::AssertionFailedError)
end
# be_something
def test_positive_be_something_method_missing_pass
def @obj.something?
true
end
@obj.should be_something
end
def test_positive_be_something_method_missing_fails
def @obj.something?
false
end
lambda {@obj.should be_something}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_negative_be_something_method_missing_pass
def @obj.something?
false
end
@obj.should_not be_something
end
def test_negative_be_something_method_missing_fails
def @obj.something?
true
end
lambda {@obj.should_not be_something}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_be_something_method_missing_fail_message
obj = "foo"
def obj.something?
true
end
matcher_obj = be_something
obj.should matcher_obj
matcher_obj.failure_message.should be("Expected \"foo\" to return true for something?, with 'no args'.")
end
def test_be_something_method_missing_negative_fail_message
obj = "foo"
def obj.something?
false
end
matcher_obj = be_something
obj.should_not matcher_obj
matcher_obj.negative_failure_message.should =~ /Expected \"foo\" to not return true for something?/
end
# be_something(arg)
def test_positive_be_something_with_arg_method_missing_pass
def @obj.something?(arg)
true
end
@obj.should be_something(1)
end
def test_positive_be_something_with_arg_method_missing_fails
def @obj.something?(arg)
false
end
lambda {@obj.should be_something(1)}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_negative_be_something_method_missing_pass
def @obj.something?(arg)
false
end
@obj.should_not be_something(1)
end
def test_negative_be_something_method_missing_fails
def @obj.something?(arg)
true
end
lambda {@obj.should_not be_something(1)}.should raise_error(Test::Unit::AssertionFailedError)
end
def test_be_something_method_missing_fail_message
obj = "foo"
def obj.something?(arg)
true
end
matcher_obj = be_something(1)
obj.should matcher_obj
matcher_obj.failure_message.should be("Expected \"foo\" to return true for something?, with '1'.")
end
def test_be_something_method_missing_negative_fail_message
obj = "foo"
def obj.something?(arg)
false
end
matcher_obj = be_something(1)
obj.should_not matcher_obj
matcher_obj.negative_failure_message.should be("Expected \"foo\" to not return true for something?, with '1'.")
end
end
| ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/test/all.rb | test/all.rb | dir = File.dirname(__FILE__)
Dir[File.expand_path("#{dir}/*.rb")].uniq.each do |file|
if file =~ /\/test_\w+\.rb$/
puts file
require file
end
end | ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/lib/matchy.rb | lib/matchy.rb | $:.unshift(File.dirname(__FILE__)) unless
$:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
# Matchy should work with either test/unit
# or minitest
module Matchy
def self.minitest?
# This needs to be better.
# How can we decide if we really have a
# suite of MiniTest Tests?
# Rails for example defines MiniTest, so only check for
# defined?(MiniTest) would be malicious
defined?(MiniTest) && defined?(MiniTest::Assertions) &&
(!defined?(Test::Unit::TestCase) || !(Test::Unit::TestCase < MiniTest::Assertions))
end
def self.assertions_module
minitest? ? MiniTest::Assertions : Test::Unit::Assertions
end
def self.test_case_class
minitest? ? MiniTest::Unit::TestCase : Test::Unit::TestCase
end
end
require 'rubygems'
require 'test/unit' unless Matchy.minitest?
require 'matchy/expectation_builder'
require 'matchy/modals'
require 'matchy/version'
require 'matchy/matcher_builder'
require 'matchy/def_matcher'
require 'matchy/built_in/enumerable_expectations'
require 'matchy/built_in/error_expectations'
require 'matchy/built_in/truth_expectations'
require 'matchy/built_in/operator_expectations'
require 'matchy/built_in/change_expectations'
# Hack of Evil.
# Track the current testcase and
# provide it to the operator matchers.
Matchy.test_case_class.class_eval do
alias_method :old_run_method_aliased_by_matchy, :run
def run(whatever, *args, &block)
$current_test_case = self
old_run_method_aliased_by_matchy(whatever, *args, &block)
end
end
Matchy.test_case_class.send(:include, Matchy::Expectations::TestCaseExtensions)
include Matchy::DefMatcher
| ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/lib/matchy/expectation_builder.rb | lib/matchy/expectation_builder.rb | module Matchy
module ExpectationBuilder
def self.build_expectation(match, exp, obj)
return Matchy::Expectations::OperatorExpectation.new(obj, match) unless exp
(exp.matches?(obj) != match) ? exp.fail!(match) : exp.pass!(match)
end
end
end | ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/lib/matchy/version.rb | lib/matchy/version.rb | module Matchy
module VERSION #:nodoc:
MAJOR = 0
MINOR = 3
TINY = 0
STRING = [MAJOR, MINOR, TINY].join('.')
end
end
| ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/lib/matchy/def_matcher.rb | lib/matchy/def_matcher.rb | module Matchy
module DefMatcher
include Matchy::MatcherBuilder
def def_matcher(matcher_name, &block)
self.class.send :define_method, matcher_name do |*args|
build_matcher(matcher_name, args, &block)
end
end
end
end
| ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/lib/matchy/modals.rb | lib/matchy/modals.rb | module Matchy
module Modals
# Tests an expectation against the given object.
#
# ==== Examples
#
# "hello".should eql("hello")
# 13.should equal(13)
# lambda { raise "u r doomed" }.should raise_error
#
def should(expectation = nil)
Matchy::ExpectationBuilder.build_expectation(true, expectation, self)
end
alias :will :should
# Tests that an expectation doesn't match the given object.
#
# ==== Examples
#
# "hello".should_not eql("hi")
# 41.should_not equal(13)
# lambda { "savd bai da bell" }.should_not raise_error
#
def should_not(expectation = nil)
Matchy::ExpectationBuilder.build_expectation(false, expectation, self)
end
alias :will_not :should_not
alias :wont :should_not
end
end
Object.send(:include, Matchy::Modals) | ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/lib/matchy/matcher_builder.rb | lib/matchy/matcher_builder.rb | module Matchy
module MatcherBuilder
def build_matcher(matcher_name=nil, args=[], &block)
match_block = lambda do |actual, matcher|
block.call(actual, matcher, args)
end
body = lambda do |klass|
include Matchy.assertions_module
@matcher_name = matcher_name.to_s
def self.matcher_name
@matcher_name
end
attr_accessor :positive_msg, :negative_msg, :msgs
attr_reader :matcher_name
def initialize match_block, test_case
@match_block, @test_case = match_block, test_case
@matcher_name = self.class.matcher_name
end
def method_missing id, *args, &block
require 'ostruct'
(self.msgs ||= []) << OpenStruct.new( "name" => id, "args" => args, "block" => block )
self
end
def matches? given
@positive_msg ||= "Matching with '#{matcher_name}' failed, although it should match."
@negative_msg ||= "Matching with '#{matcher_name}' passed, although it should_not match."
@match_block.call(given, self)
end
def fail!(which)
@test_case.flunk(which ? failure_message : negative_failure_message)
end
def pass!(which)
@test_case.assert true
end
alias_method :failure_message, :positive_msg
alias_method :negative_failure_message, :negative_msg
end
Class.new(&body).new(match_block, self)
end
end
end | ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/lib/matchy/built_in/truth_expectations.rb | lib/matchy/built_in/truth_expectations.rb | module Matchy
module Expectations
module TestCaseExtensions
# Simply checks if the receiver matches the expected object.
# TODO: Fill this out to implement much of the RSpec functionality (and then some)
#
# ==== Examples
#
# "hello".should be("hello")
# (13 < 20).should be(true)
#
def be(*obj)
build_matcher(:be, obj) do |receiver, matcher, args|
@receiver, expected = receiver, args[0]
matcher.positive_msg = "Expected #{@receiver.inspect} to be #{expected.inspect}."
matcher.negative_msg = "Expected #{@receiver.inspect} to not be #{expected.inspect}."
expected == @receiver
end
end
# Checks if the given object is within a given object and delta.
#
# ==== Examples
#
# (20.0 - 2.0).should be_close(18.0)
# (13.0 - 4.0).should be_close(9.0, 0.5)
#
def be_close(obj, delta = 0.3)
build_matcher(:be_close, [obj, delta]) do |receiver, matcher, args|
@receiver, expected, delta = receiver, args[0], args[1]
matcher.positive_msg = "Expected #{@receiver.inspect} to be close to #{expected.inspect} (delta: #{delta})."
matcher.negative_msg = "Expected #{@receiver.inspect} to not be close to #{expected.inspect} (delta: #{delta})."
(@receiver - expected).abs < delta
end
end
# Calls +exist?+ on the given object.
#
# ==== Examples
#
# # found_user.exist?
# found_user.should exist
#
def exist
ask_for(:exist, :with_arg => nil)
end
# Calls +eql?+ on the given object (i.e., are the objects the same value?)
#
# ==== Examples
#
# 1.should_not eql(1.0)
# (12 / 6).should eql(6)
#
def eql(*obj)
ask_for(:eql, :with_arg => obj)
end
# Calls +equal?+ on the given object (i.e., do the two objects have the same +object_id+?)
#
# ==== Examples
#
# x = [1,2,3]
# y = [1,2,3]
#
# # Different object_id's...
# x.should_not equal(y)
#
# # The same object_id
# x[0].should equal(y[0])
#
def equal(*obj)
ask_for(:equal, :with_arg => obj)
end
# A last ditch way to implement your testing logic. You probably shouldn't use this unless you
# have to.
#
# ==== Examples
#
# (13 - 4).should satisfy(lambda {|i| i < 20})
# "hello".should_not satisfy(lambda {|s| s =~ /hi/})
#
def satisfy(*obj)
build_matcher(:satisfy, obj) do |receiver, matcher, args|
@receiver, expected = receiver, args[0]
matcher.positive_msg = "Expected #{@receiver.inspect} to satisfy given block."
matcher.negative_msg = "Expected #{@receiver.inspect} to not satisfy given block."
expected.call(@receiver) == true
end
end
# Checks if the given object responds to the given method
#
# ==== Examples
#
# "foo".should respond_to(:length)
# {}.should respond_to(:has_key?)
def respond_to(*meth)
ask_for(:respond_to, :with_arg => meth)
end
# Asks given for success?().
# This is necessary because Rails Integration::Session
# overides method_missing without grace.
#
# ==== Examples
#
# @response.should be_success
def be_success
ask_for(:success, :with_arg => nil)
end
alias_method :old_missing, :method_missing
# ==be_*something(*args)
#
# ===This method_missing acts as a matcher builder.
# If a call to be_xyz() reaches this method_missing (say: obj.should be_xyz),
# a matcher with the name xyz will be built, whose defining property
# is that it returns the value of obj.xyz? for matches?.
# ==== Examples
#
# nil.should be_nil
# 17.should be_kind_of(Fixnum)
# obj.something? #=> true
# obj.should be_something
def method_missing(name, *args, &block)
if (name.to_s =~ /^be_(.+)/)
ask_for($1, :with_arg => args)
else
old_missing(name, *args, &block)
end
end
private
def ask_for(sym, option={})
build_matcher(sym, (option[:with_arg] || [])) do |receiver, matcher, args|
expected, meth = args[0], (sym.to_s + "?" ).to_sym
matcher.positive_msg = "Expected #{receiver.inspect} to return true for #{sym}?, with '#{(expected && expected.inspect) || 'no args'}'."
matcher.negative_msg = "Expected #{receiver.inspect} to not return true for #{sym}?, with '#{(expected && expected.inspect) || 'no args'}'."
expected ? receiver.send(meth, expected) : receiver.send(meth)
end
end
end
end
end | ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/lib/matchy/built_in/error_expectations.rb | lib/matchy/built_in/error_expectations.rb | module Matchy
module Expectations
module TestCaseExtensions
# Expects a lambda to raise an error. You can specify the error or leave it blank to encompass
# any error.
#
# ==== Examples
#
# lambda { raise "FAILURE." }.should raise_error
# lambda { puts i_dont_exist }.should raise_error(NameError)
#
def raise_error(*obj)
build_matcher(:raise_error, obj) do |receiver, matcher, args|
expected = args[0] || Exception
raised = false
error = nil
begin
receiver.call
rescue Exception => e
raised = true
error = e
end
if expected.respond_to?(:ancestors) && expected.ancestors.include?(Exception)
matcher.positive_msg = "Expected #{receiver.inspect} to raise #{expected.name}, " +
(error ? "but #{error.class.name} was raised instead." : "but none was raised.")
matcher.negative_msg = "Expected #{receiver.inspect} to not raise #{expected.name}."
comparison = (raised && error.class.ancestors.include?(expected))
else
message = error ? error.message : "none"
matcher.positive_msg = "Expected #{receiver.inspect} to raise error with message matching '#{expected}', but '#{message}' was raised."
matcher.negative_msg = "Expected #{receiver.inspect} to raise error with message not matching '#{expected}', but '#{message}' was raised."
comparison = (raised && (expected.kind_of?(Regexp) ? ((error.message =~ expected) ? true : false) : expected == error.message))
end
comparison
end
end
# Expects a lambda to throw an error.
#
# ==== Examples
#
# lambda { throw :thing }.should throw_symbol(:thing)
# lambda { "not this time" }.should_not throw_symbol(:hello)
#
def throw_symbol(*obj)
build_matcher(:throw_symbol, obj) do |receiver, matcher, args|
raised, thrown_symbol, expected = false, nil, args[0]
begin
receiver.call
rescue NameError => e
raise e unless e.message =~ /uncaught throw/
raised = true
thrown_symbol = e.name.to_sym if e.respond_to?(:name)
rescue ArgumentError => e
raise e unless e.message =~ /uncaught throw/
thrown_symbol = e.message.match(/uncaught throw :(.+)/)[1].to_sym
end
matcher.positive_msg = "Expected #{receiver.inspect} to throw :#{expected}, but " +
"#{thrown_symbol ? ':' + thrown_symbol.to_s + ' was thrown instead' : 'no symbol was thrown'}."
matcher.negative_msg = "Expected #{receiver.inspect} to not throw :#{expected}."
expected == thrown_symbol
end
end
end
end
end | ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/lib/matchy/built_in/change_expectations.rb | lib/matchy/built_in/change_expectations.rb | module Matchy
module Expectations
module TestCaseExtensions
# Checks if the given block alters the value of the block attached to change
#
# ==== Examples
# lambda {var += 1}.should change {var}.by(1)
# lambda {var += 2}.should change {var}.by_at_least(1)
# lambda {var += 1}.should change {var}.by_at_most(1)
# lambda {var += 2}.should change {var}.from(1).to(3) if var = 1
def change(&block)
build_matcher(:change) do |receiver, matcher, args|
before, done, after = block.call, receiver.call, block.call
comparison = after != before
if list = matcher.msgs
comparison = case list[0].name
# todo: provide meaningful messages
when :by then (after == before + list[0].args[0] || after == before - list[0].args[0])
when :by_at_least then (after >= before + list[0].args[0] || after <= before - list[0].args[0])
when :by_at_most then (after <= before + list[0].args[0] && after >= before - list[0].args[0])
when :from then (before == list[0].args[0]) && (after == list[1].args[0])
end
end
matcher.positive_msg = "given block shouldn't alter the block attached to change"
matcher.negative_msg = "given block should alter the block attached to change"
comparison
end
end
end
end
end | ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/lib/matchy/built_in/enumerable_expectations.rb | lib/matchy/built_in/enumerable_expectations.rb | module Matchy
module Expectations
module TestCaseExtensions
# Calls +include?+ on the receiver for any object. You can also provide
# multiple arguments to see if all of them are included.
#
# ==== Examples
#
# [1,2,3].should include(1)
# [7,8,8].should_not include(3)
# ['a', 'b', 'c'].should include('a', 'c')
#
def include(*obj)
_clude(:include, obj)
end
# Expects the receiver to exclude the given object(s). You can provide
# multiple arguments to see if all of them are included.
#
# ==== Examples
#
# [1,2,3].should exclude(16)
# [7,8,8].should_not exclude(7)
# ['a', 'b', 'c'].should exclude('e', 'f', 'g')
#
def exclude(*obj)
_clude(:exclude, obj)
end
private
def _clude(sym, obj)
build_matcher(sym, obj) do |given, matcher, args|
matcher.positive_msg = "Expected #{given.inspect} to #{sym} #{args.inspect}."
matcher.negative_msg = "Expected #{given.inspect} to not #{sym} #{args.inspect}."
args.inject(true) {|m,o| m && (given.include?(o) == (sym == :include)) }
end
end
end
end
end | ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/lib/matchy/built_in/operator_expectations.rb | lib/matchy/built_in/operator_expectations.rb | module Matchy
module Expectations
# Class to handle operator expectations.
#
# ==== Examples
#
# 13.should == 13
# "hello".length.should_not == 2
#
class OperatorExpectation #< Base
include Matchy.assertions_module
def initialize(receiver, match)
@receiver, @match = receiver, match
end
['==', '===', '=~', '>', '>=', '<', '<='].each do |op|
define_method(op) do |expected|
@expected = expected
(@receiver.send(op,expected) ? true : false) == @match ? pass! : fail!(op)
end
end
protected
def pass!
defined?($current_test_case) ? $current_test_case.assert(true) : (assert true)
end
def fail!(operator)
flunk @match ? failure_message(operator) : negative_failure_message(operator)
end
def failure_message(operator)
"Expected #{@receiver.inspect} to #{operator} #{@expected.inspect}."
end
def negative_failure_message(operator)
"Expected #{@receiver.inspect} to not #{operator} #{@expected.inspect}."
end
end
end
end | ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/config/hoe.rb | config/hoe.rb | require 'matchy/version'
AUTHOR = 'Jeremy McAnally' # can also be an array of Authors
EMAIL = "jeremy@entp.com"
DESCRIPTION = "RSpec-esque matchers for use in Test::Unit"
GEM_NAME = 'matchy' # what ppl will type to install your gem
RUBYFORGE_PROJECT = 'matchy' # The unix name for your project
HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org"
DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}"
EXTRA_DEPENDENCIES = [
# ['activesupport', '>= 1.3.1']
] # An array of rubygem dependencies [name, version]
@config_file = "~/.rubyforge/user-config.yml"
@config = nil
RUBYFORGE_USERNAME = "unknown"
def rubyforge_username
unless @config
begin
@config = YAML.load(File.read(File.expand_path(@config_file)))
rescue
puts <<-EOS
ERROR: No rubyforge config file found: #{@config_file}
Run 'rubyforge setup' to prepare your env for access to Rubyforge
- See http://newgem.rubyforge.org/rubyforge.html for more details
EOS
exit
end
end
RUBYFORGE_USERNAME.replace @config["username"]
end
REV = nil
# UNCOMMENT IF REQUIRED:
# REV = YAML.load(`svn info`)['Revision']
VERS = Matchy::VERSION::STRING + (REV ? ".#{REV}" : "")
RDOC_OPTS = ['--quiet', '--title', 'matchy documentation',
"--opname", "index.html",
"--line-numbers",
"--main", "README.rdoc",
"--inline-source"]
class Hoe
def extra_deps
@extra_deps.reject! { |x| Array(x).first == 'hoe' }
@extra_deps
end
end
# Generate all the Rake tasks
# Run 'rake -T' to see list of generated tasks (from gem root directory)
$hoe = Hoe.new(GEM_NAME, VERS) do |p|
p.developer(AUTHOR, EMAIL)
p.description = DESCRIPTION
p.summary = DESCRIPTION
p.url = HOMEPATH
p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT
p.test_globs = ["test/**/test_*.rb"]
p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean.
# == Optional
p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n")
#p.extra_deps = EXTRA_DEPENDENCIES
#p.spec_extras = {} # A hash of extra values to set in the gemspec.
end
CHANGES = $hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n")
PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}"
$hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''), 'rdoc')
$hoe.rsync_args = '-av --delete --ignore-errors'
$hoe.spec.post_install_message = File.open(File.dirname(__FILE__) + "/../PostInstall.txt").read rescue "" | ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
jm/matchy | https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/config/requirements.rb | config/requirements.rb | require 'fileutils'
include FileUtils
require 'rubygems'
%w[rake hoe newgem rubigen].each do |req_gem|
begin
require req_gem
rescue LoadError
puts "This Rakefile requires the '#{req_gem}' RubyGem."
puts "Installation: gem install #{req_gem} -y"
exit
end
end
$:.unshift(File.join(File.dirname(__FILE__), %w[.. lib]))
| ruby | MIT | 2e01918ad8d601685386aa9ac5d547ffb9b70b27 | 2026-01-04T17:56:08.640464Z | false |
ryw/pinboard | https://github.com/ryw/pinboard/blob/5c813b7018b7df9a6d359c34ed294eb0d65cb28a/spec/helper.rb | spec/helper.rb | require 'pinboard'
require 'rspec'
require 'webmock/rspec'
def a_get(path)
a_request(:get, Pinboard.endpoint + path)
end
def stub_get(path)
stub_request(:get, uri(path))
end
def stub_post(path)
stub_request(:post, uri(path))
end
def uri(path)
"https://api.pinboard.in/v1/#{path}"
end
def fixture_path
File.expand_path("../fixtures", __FILE__)
end
def fixture(file)
File.new(fixture_path + '/' + file)
end
| ruby | MIT | 5c813b7018b7df9a6d359c34ed294eb0d65cb28a | 2026-01-04T17:56:09.554894Z | false |
ryw/pinboard | https://github.com/ryw/pinboard/blob/5c813b7018b7df9a6d359c34ed294eb0d65cb28a/spec/pinboard_spec.rb | spec/pinboard_spec.rb | require 'helper'
describe Pinboard do
describe ".new" do
it "returns a Pinboard client" do
Pinboard.new.should be_a Pinboard::Client
end
end
describe ".endpoint" do
it "sets the endpoint" do
Pinboard.endpoint.should == 'https://api.pinboard.in:443/v1'
end
end
end
| ruby | MIT | 5c813b7018b7df9a6d359c34ed294eb0d65cb28a | 2026-01-04T17:56:09.554894Z | false |
ryw/pinboard | https://github.com/ryw/pinboard/blob/5c813b7018b7df9a6d359c34ed294eb0d65cb28a/spec/pinboard/client_spec.rb | spec/pinboard/client_spec.rb | require 'helper'
describe Pinboard::Client do
describe "#posts" do
let(:client) { Pinboard::Client.new }
context "when there are many posts" do
before do
stub_get("posts/all?").
to_return(:body => fixture("multiple_posts.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "returns a collection of posts" do
expected =
[
Pinboard::Post.new(
:href => "http://foo.com/",
:description => "Foo!",
:extended => "long description Foo",
:tag => 'foo bar',
:toread => 'yes',
:time => Time.parse("2011-07-26T17:52:04Z")),
Pinboard::Post.new(
:href => "http://bar.com/",
:description => "Bar!",
:extended => "long description Bar",
:tag => 'foo bar',
:toread => 'yes',
:time => Time.parse("2011-07-26T17:52:04Z")),
]
client.posts.should == expected
end
end
context "where there is a single post" do
before do
stub_get("posts/all?").
to_return(:body => fixture("single_post.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "still returns an array" do
client.posts.class.should == Array
end
end
context "when there are no posts" do
before do
stub_get("posts/all?").
to_return(:body => fixture("no_posts.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "returns an empty array" do
client.posts.should == []
end
end
end
describe "#delete" do
let(:client) { Pinboard::Client.new }
context "when there are many posts" do
before do
stub_get("posts/delete?url=http://bar.com/").
to_return(:body => fixture("deleted.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "succeeds without raising an error" do
expect{client.delete("http://bar.com/")}.to_not raise_error
end
end
context "when specified url is not found" do
before do
stub_get("posts/delete?url=http://baz.com/").
to_return(:body => fixture("not_found.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "throws an error" do
expect{client.delete("http://baz.com/")}.to raise_error(Pinboard::Error, 'item not found')
end
end
end
describe "#add" do
let(:client) do
Pinboard::Client.new
end
context "where the post does not exist yet" do
context 'and the url is missing' do
before do
stub_post("posts/add").
to_return(:body => fixture("missing_url.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "throws an error" do
expect { client.add(nil) }.to raise_error
end
end
context 'and the description is missing' do
before do
stub_post("posts/add?url=http://baz.com/").
to_return(:body => fixture("missing_description.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "throws an error" do
expect { client.add(:url => "http://baz.com/") }.to raise_error(Pinboard::Error, 'missing description')
end
end
context 'and the description is present' do
before do
stub_post("posts/add?url=http://baz.com/&description=title").
to_return(:body => fixture("created.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "succeeds without raising an exception" do
expect {client.add(:url => "http://baz.com/", :description => 'title')}.to_not raise_error
end
end
context 'and toread is set to true' do
before do
stub_post("posts/add?url=http://baz.com/&description=title&toread=yes").
to_return(:body => fixture("created.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "succeeds without raising an exception" do
expect {client.add(:url => "http://baz.com/", :description => 'title', :toread => true)}.to_not raise_error
end
end
context 'and toread is set to false' do
before do
stub_post("posts/add?url=http://baz.com/&description=title&toread=no").
to_return(:body => fixture("created.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "succeeds without raising an exception" do
expect {client.add(:url => "http://baz.com/", :description => 'title', :toread => false)}.to_not raise_error
end
end
context 'and replace is set to true' do
before do
stub_post("posts/add?url=http://baz.com/&description=title&replace=yes").
to_return(:body => fixture("created.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "succeeds without raising an exception" do
expect {client.add(:url => "http://baz.com/", :description => 'title', :replace => true)}.to_not raise_error
end
end
context 'and replace is set to false' do
before do
stub_post("posts/add?url=http://baz.com/&description=title&replace=no").
to_return(:body => fixture("created.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "succeeds without raising an exception" do
expect {client.add(:url => "http://baz.com/", :description => 'title', :replace => false)}.to_not raise_error
end
end
context 'and shared is set to true' do
before do
stub_post("posts/add?url=http://baz.com/&description=title&shared=yes").
to_return(:body => fixture("created.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "succeeds without raising an exception" do
expect {client.add(:url => "http://baz.com/", :description => 'title', :shared => true)}.to_not raise_error
end
end
context 'and shared is set to false' do
before do
stub_post("posts/add?url=http://baz.com/&description=title&shared=no").
to_return(:body => fixture("created.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "succeeds without raising an exception" do
expect {client.add(:url => "http://baz.com/", :description => 'title', :shared => false)}.to_not raise_error
end
end
context 'and replace, shared, and toread are all set to true' do
before do
stub_post("posts/add?url=http://baz.com/&description=title&replace=yes&shared=yes&toread=yes").
to_return(:body => fixture("created.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "succeeds without raising an exception" do
expect {client.add(:url => "http://baz.com/",
:description => 'title',
:replace => true,
:shared => true,
:toread => true)}.to_not raise_error
end
end
context 'and replace, shared, and toread are all set to false' do
before do
stub_post("posts/add?url=http://baz.com/&description=title&replace=no&shared=no&toread=no").
to_return(:body => fixture("created.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "succeeds without raising an exception" do
expect {client.add(:url => "http://baz.com/",
:description => 'title',
:replace => false,
:shared => false,
:toread => false)}.to_not raise_error
end
end
end
end
describe "#update" do
let(:client) { Pinboard::Client.new }
before do
stub_get("posts/update?").
to_return(:body => fixture("post_update.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "returns the time of last update" do
expected = Time.parse "2013-04-20 13:58:56 +0200"
client.update.should == expected
end
end
describe "#recent" do
let(:client) { Pinboard::Client.new }
before do
stub_get("posts/recent?").
to_return(:body => fixture("multiple_posts.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "returns recent items" do
expected = [
Pinboard::Post.new(
:href => "http://foo.com/",
:description => "Foo!",
:extended => "long description Foo",
:tag => 'foo bar',
:toread => 'yes',
:time => Time.parse("2011-07-26T17:52:04Z")),
Pinboard::Post.new(
:href => "http://bar.com/",
:description => "Bar!",
:extended => "long description Bar",
:tag => 'foo bar',
:toread => 'yes',
:time => Time.parse("2011-07-26T17:52:04Z")),
]
client.recent.should == expected
end
end
describe "#dates" do
let(:client) { Pinboard::Client.new }
context "unfiltered" do
before do
stub_get("posts/dates?").
to_return(:body => fixture("dates.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "returns a list of dates with the number of posts at each date" do
expected = {
"2013-04-19" => 1,
"2013-04-18" => 2,
"2013-04-17" => 3
}
client.dates.should == expected
end
end
context "filtered by tag" do
before do
stub_get("posts/dates?tag=tag").
to_return(:body => fixture("dates_filtered.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "returns a list of dates with the number of posts at each date" do
expected = {
"2013-04-19" => 1,
"2013-04-18" => 2,
"2013-04-17" => 3
}
client.dates("tag").should == expected
end
end
end
describe "#notes_list" do
let(:client) { Pinboard::Client.new }
before do
stub_get("notes/list?").
to_return(:body => fixture("notes_list.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "returns a list of notes" do
notes = client.notes_list
notes.size.should == 2
notes.first.title.should == "Paul Graham on Hirin' The Ladies"
end
end
describe "#user_secret" do
let(:client) { Pinboard::Client.new }
before do
stub_get("user/secret?").
to_return(:body => fixture("user_secret.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "returns the user's secret RSS key" do
secret = client.user_secret
secret.should == "6493a84f72d86e7de130"
end
end
describe "#user_api_token" do
let(:client) { Pinboard::Client.new }
before do
stub_get("user/api_token?").
to_return(:body => fixture("user_api_token.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "returns the user's API token" do
token = client.user_api_token
token.should == "XOG86E7JIYMI"
end
end
describe "#get" do
let(:client) { Pinboard::Client.new }
context "when there are many posts" do
before do
stub_get("posts/get?").
to_return(:body => fixture("multiple_posts.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "returns a collection of posts" do
expected =
[
Pinboard::Post.new(
:href => "http://foo.com/",
:description => "Foo!",
:extended => "long description Foo",
:tag => 'foo bar',
:toread => 'yes',
:time => Time.parse("2011-07-26T17:52:04Z")),
Pinboard::Post.new(
:href => "http://bar.com/",
:description => "Bar!",
:extended => "long description Bar",
:tag => 'foo bar',
:toread => 'yes',
:time => Time.parse("2011-07-26T17:52:04Z")),
]
client.get.should == expected
end
end
context "where there is a single post" do
before do
stub_get("posts/get?").
to_return(:body => fixture("single_post.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "still returns an array" do
client.get.class.should == Array
end
end
context "when there are no posts" do
before do
stub_get("posts/get?").
to_return(:body => fixture("no_posts.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "returns an empty array" do
client.get.should == []
end
end
end
describe "#suggest" do
let(:client) { Pinboard::Client.new }
let(:url) { 'http://example.com' }
context "when there are many popular and recommended tags" do
before do
stub_get("posts/suggest").
with(:query => { 'url' => url }).
to_return(:body => fixture("multiple_suggest.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "returns a collections of tags" do
suggest = client.suggest(url)
suggest[:popular].should == %w[blog blogs]
suggest[:recommended].should == %w[writing weblog]
end
end
context "when there are single popular and recommended tags" do
before do
stub_get("posts/suggest?").
with(:query => { 'url' => url }).
to_return(:body => fixture("single_suggest.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "still returns an array" do
suggest = client.suggest(url)
suggest[:popular].class.should == Array
suggest[:recommended].class.should == Array
end
end
context "when there are no popular and recommended tags" do
before do
stub_get("posts/suggest?").
with(:query => { 'url' => url }).
to_return(:body => fixture("no_suggest.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "returns an empty array" do
suggest = client.suggest(url)
suggest[:popular].should == []
suggest[:recommended].should == []
end
end
end
end
| ruby | MIT | 5c813b7018b7df9a6d359c34ed294eb0d65cb28a | 2026-01-04T17:56:09.554894Z | false |
ryw/pinboard | https://github.com/ryw/pinboard/blob/5c813b7018b7df9a6d359c34ed294eb0d65cb28a/spec/pinboard/post_spec.rb | spec/pinboard/post_spec.rb | require 'helper'
describe Pinboard::Post do
describe ".all" do
let(:posts) { Pinboard::Post.all }
before do
stub_get("posts/all").
to_return(:body => fixture("multiple_posts.xml"),
:headers => { 'content-type' => 'text/xml' })
end
it "returns a collection" do
posts.count.should == 2
end
it "loads posts with valid attributes" do
post = posts.first
post.href.should == "http://foo.com/"
post.description.should == "Foo!"
post.extended.should == "long description Foo"
post.tag.should == ["foo", "bar"]
post.time.should == Time.parse('Tue Jul 26 17:52:04 UTC 2011')
end
end
describe ".new" do
let(:post) {
Pinboard::Post.new(
:href => 'http://foo.com',
:description => 'Foo!',
:extended => "long description Foo",
:tag => 'rspec pinboard',
:time => Time.mktime(2011, 1, 1))
}
it "initializes attributes" do
post.href.should == 'http://foo.com'
post.description.should == 'Foo!'
post.extended.should == "long description Foo"
post.tag.should == %w{rspec pinboard}
post.time.should == Time.mktime(2011, 1, 1)
end
end
end
| ruby | MIT | 5c813b7018b7df9a6d359c34ed294eb0d65cb28a | 2026-01-04T17:56:09.554894Z | false |
ryw/pinboard | https://github.com/ryw/pinboard/blob/5c813b7018b7df9a6d359c34ed294eb0d65cb28a/lib/pinboard.rb | lib/pinboard.rb | require 'pinboard/util'
require 'pinboard/client'
require 'pinboard/post'
require 'pinboard/tag'
require 'pinboard/note'
module Pinboard
class << self
def new(options={})
Pinboard::Client.new(options)
end
def endpoint
Pinboard::Client.base_uri
end
end
end
| ruby | MIT | 5c813b7018b7df9a6d359c34ed294eb0d65cb28a | 2026-01-04T17:56:09.554894Z | false |
ryw/pinboard | https://github.com/ryw/pinboard/blob/5c813b7018b7df9a6d359c34ed294eb0d65cb28a/lib/pinboard/tag.rb | lib/pinboard/tag.rb | module Pinboard
class Tag < Struct.new(:tag, :count)
def initialize(attributes={})
self.tag = attributes.delete(:tag)
self.count = attributes.delete(:count).to_i
end
end
end
| ruby | MIT | 5c813b7018b7df9a6d359c34ed294eb0d65cb28a | 2026-01-04T17:56:09.554894Z | false |
ryw/pinboard | https://github.com/ryw/pinboard/blob/5c813b7018b7df9a6d359c34ed294eb0d65cb28a/lib/pinboard/note.rb | lib/pinboard/note.rb | module Pinboard
class Note < Struct.new(:id, :title, :created_at, :updated_at, :length, :text)
def initialize(attributes={})
self.id = attributes[:id]
self.title = attributes[:title]
self.created_at = attributes[:created_at] && Util.parse_time(attributes[:created_at])
self.updated_at = attributes[:updated_at] && Util.parse_time(attributes[:updated_at])
self.length = attributes[:length].to_i
self.text = attributes[:text]
end
def to_json(*args)
{
id: id,
title: title,
created_at: created_at,
updated_at: updated_at,
length: length
}.to_json(*args)
end
end
end
| ruby | MIT | 5c813b7018b7df9a6d359c34ed294eb0d65cb28a | 2026-01-04T17:56:09.554894Z | false |
ryw/pinboard | https://github.com/ryw/pinboard/blob/5c813b7018b7df9a6d359c34ed294eb0d65cb28a/lib/pinboard/post.rb | lib/pinboard/post.rb | module Pinboard
class Post < Struct.new(:href, :description, :extended, :tag, :time, :replace, :shared, :toread)
def self.all(options={})
client = Pinboard::Client.new(options)
posts = client.class.get('/posts/all',
:basic_auth => options)['posts']['post']
posts.map { |p| Post.new(Util.symbolize_keys(p)) }
end
def initialize(attributes={})
self.time = Util.parse_time(attributes.delete(:time))
self.tag = attributes.delete(:tag).split(" ")
attributes.each do |attribute, value|
send("#{attribute}=", value) if respond_to?("#{attribute}=")
end
end
def to_json(*args)
{
href: href,
description: description,
extended: extended,
tag: tag,
time: time,
replace: replace,
shared: shared,
toread: toread
}.to_json(*args)
end
# Creates hash for API (e.g. pass it to '/posts/add')
#
# @param [Boolean, nil] replace Overwrite replace attribute if not nil
# @return [Hash]
def api_hash(replace = nil)
self.replace = replace unless replace.nil?
{
url: href,
description: description,
extended: extended,
tags: tag.join(" "),
replace: replace,
shared: shared,
toread: toread
}.select { |key, value| ! value.nil? }
end
end
end
| ruby | MIT | 5c813b7018b7df9a6d359c34ed294eb0d65cb28a | 2026-01-04T17:56:09.554894Z | false |
ryw/pinboard | https://github.com/ryw/pinboard/blob/5c813b7018b7df9a6d359c34ed294eb0d65cb28a/lib/pinboard/client.rb | lib/pinboard/client.rb | require 'httparty'
require 'time'
module Pinboard
# Raised when API returns failure
Error = Class.new(StandardError)
class Client
include HTTParty
base_uri 'api.pinboard.in:443/v1'
# Construct a new instance of the client
#
# @param [Hash] options Options for the connection
# @option options [String] :token The Pinboard API token (prefered over username & password)
# @option options [String] :username Pinboard username
# @option options [String] :password Pinboard password
def initialize(options={})
@auth = nil
@auth_token = nil
if (token=options.delete(:token))
@auth_token = token
else
@auth = {
username: options[:username],
password: options[:password]
}
end
end
# Returns all bookmarks in the user's account.
#
# @option params [String] :tag filter by up to three tags
# @option params [Integer] :start offset value (default is 0)
# @option params [Integer] :results number of results to return. Default is all
# @option params [Time] :fromdt return only bookmarks created after this time
# @option params [Time] :todt return only bookmarks created before this time
# @option params [Integer] :meta include a change detection signature for each bookmark
# @return [Array<Post>] the list of bookmarks
def posts(params = {})
options = create_params(params)
posts = self.class.get('/posts/all', options)['posts']['post']
posts = [] if posts.nil?
posts = [posts] if posts.class != Array
posts.map { |p| Post.new(Util.symbolize_keys(p)) }
end
# Returns one or more posts on a single day matching the arguments.
# If no date or url is given, date of most recent bookmark will be used.
#
# @option params [String] :tag filter by up to three tags
# @option params [Time] :dt return results bookmarked on this day
# @option params [String] :url return bookmark for this URL
# @option params [Boolean] :meta include a change detection signature in a meta attribute
# @return [Array<Post>] the list of bookmarks
def get(params = {})
params[:dt] = params[:dt].to_date.to_s if params.is_a? Time
params[:meta] = params[:meta] ? 'yes' : 'no' if params.has_key?(:meta)
options = create_params(params)
posts = self.class.get('/posts/get', options)['posts']['post']
posts = [] if posts.nil?
posts = [posts] if posts.class != Array
posts.map { |p| Post.new(Util.symbolize_keys(p)) }
end
# Returns a list of popular tags and recommended tags for a given URL.
# Popular tags are tags used site-wide for the url; recommended tags
# are drawn from the user's own tags.
#
# @param [String] url
# @return [Hash<String, Array>]
def suggest(url)
options = create_params({url: url})
suggested = self.class.get('/posts/suggest', options)['suggested']
if suggested.nil?
popular = []
recommended = []
else
popular = suggested['popular']
recommended = suggested['recommended']
end
popular = [popular] if popular.class != Array
recommended = [recommended] if recommended.class != Array
{:popular => popular, :recommended => recommended}
end
# Add a bookmark
#
# @param [Hash] params Arguments for this call
# @option params [String] :url the URL of the item (required)
# @option params [String] :description Title of the item (required)
# @option params [String] :extended Description of the item
# @option params [Array] :tags List of up to 100 tags
# @option params [Time] :dt creation time for this bookmark. Defaults to current
# time. Datestamps more than 10 minutes ahead of server time will be reset to
# current server time
# @option params [Boolean] :replace Replace any existing bookmark with this URL.
# Default is true. If set to false, will throw an error if bookmark exists
# @option params [Boolean] :shared Make bookmark public. Default is true unless
# user has enabled the "save all bookmarks as private" user setting, in which
# case default is false
# @option params [Boolean] :toread Marks the bookmark as unread (default: false)
#
# @return [String] "done" when everything went as expected
# @raise [Error] if result code is not "done"
def add(params={})
# Pinboard expects multiple tags=foo,bar separated by comma instead of tag=foo&tag=bar
params[:tags] = Array(params[:tags]).join(',') if params[:tags]
# Pinboard expects datetime as UTC timestamp in this format:
# 2010-12-11T19:48:02Z. Valid date range is Jan 1, 1 AD to January 1, 2100
params[:dt] = params[:dt].iso8601 if params[:dt].is_a? Time
# Pinboard expects replace, shared and toread as yes/no instead of true/false
[:replace, :shared, :toread].each do |boolean|
if params.has_key?(boolean) && !['yes', 'no'].include?(params[boolean])
params[boolean] = params[boolean] ? 'yes' : 'no'
end
end
options = create_params(params)
result_code = self.class.post('/posts/add', options).parsed_response["result"]["code"]
raise Error.new(result_code) if result_code != "done"
result_code
end
# Returns the most recent time a bookmark was added, updated or deleted.
#
# Use this before calling {#posts} to see if the data has changed
# since the last fetch.
#
# @return [Time] the time a bookmark was modified
def update
options = create_params({})
time = self.class.get('/posts/update', options)["update"]["time"]
Time.parse time
end
# Returns a list of the user's most recent posts, filtered by tag.
#
# @param <Hash> params the options to filter current posts
# @option params [String] :tag filter by up to three tags
# @option params [String] :count Number of results to return.
# Default is 15, max is 100
#
# @return [Array<Post>] the list of recent posts
def recent(params={})
options = create_params(params)
posts = self.class.get('/posts/recent', options)['posts']['post']
posts = [] if posts.nil?
posts = [*posts]
posts.map { |p| Post.new(Util.symbolize_keys(p)) }
end
# Returns a list of dates with the number of posts at each date
#
# @param [String] tag Filter by up to three tags
#
# @return [Hash<String,Fixnum>] List of dates with number of posts
# at each date
def dates(tag=nil)
params = {}
params[:tag] = tag if tag
options = create_params(params)
dates = self.class.get('/posts/dates', options)['dates']['date']
dates = [] if dates.nil?
dates = [*dates]
dates.each_with_object({}) { |value, hash|
hash[value["date"]] = value["count"].to_i
}
end
# Delete a bookmark
#
# @param [String] url The url to delete
#
# @return [String] "done" when everything went as expected
# @raise [Error] if result code is not "done"
def delete(url)
params = { url: url }
options = create_params(params)
result_code = self.class.get('/posts/delete', options).parsed_response["result"]["code"]
raise Error.new(result_code) if result_code != "done"
result_code
end
# Returns a full list of the user's tags along with the number of
# times they were used.
#
# @return [Array<Tag>] List of all tags
def tags_get(params={})
options = create_params(params)
tags = self.class.get('/tags/get', options)['tags']['tag']
tags = [] if tags.nil?
tags = [*tags]
tags.map { |p| Tag.new(Util.symbolize_keys(p)) }
end
# Rename an tag or fold it into an existing tag
#
# @param [String] old_tag Tag to rename (not case sensitive)
# @param [String] new_tag New tag (if empty nothing will happen)
#
# @return [String] "done" when everything went as expected
# @raise [Error] if result code is not "done"
def tags_rename(old_tag, new_tag=nil)
params = {}
params[:old] = old_tag
params[:new] = new_tag if new_tag
options = create_params(params)
result_code = self.class.get('/tags/rename', options).parsed_response["result"]
raise Error.new(result_code) if result_code != "done"
result_code
end
# Delete an existing tag
#
# @param [String] tag Tag to delete
# @return [nil]
def tags_delete(tag)
params = { tag: tag }
options = create_params(params)
self.class.get('/tags/delete', options)
nil
end
# Returns the user's secret RSS key (for viewing private feeds)
#
# @return [String]
def user_secret()
self.class.get('/user/secret', create_params({}))['result']
end
# Returns the user's API token (for making API calls without a password)
#
# @return [String]
def user_api_token()
self.class.get('/user/api_token', create_params({}))['result']
end
# Returns a list of the user's notes
#
# @return [Array<Note>] list of notes
def notes_list
options = create_params({})
notes = self.class.get('/notes/list', options)['notes']['note']
notes = [] if notes.nil?
notes = [*notes]
notes.map { |p| Note.new(Util.symbolize_keys(p)) }
end
# Returns an individual user note. The hash property is a
# 20 character long sha1 hash of the note text.
#
# @return [Note] the note
def notes_get(id)
options = create_params({})
note = self.class.get("/notes/#{id}", options)['note']
return nil unless note
# Complete hack, because the API is still broken
content = '__content__'
Note.new({
id: note['id'],
# Remove whitespace around the title,
# because of missing xml tag around
title: note[content].gsub(/\n| +/, ''),
length: note['length'][content].to_i,
text: note['text'][content]
})
end
private
# Construct params hash for HTTP request
#
# @param [Hash] params Query arguments to include in request
# @return [Hash] Options hash for request
def create_params params
options = {}
options[:query] = params
if @auth_token
options[:query].merge!(auth_token: @auth_token)
else
options[:basic_auth] = @auth
end
options
end
end
end
| ruby | MIT | 5c813b7018b7df9a6d359c34ed294eb0d65cb28a | 2026-01-04T17:56:09.554894Z | false |
ryw/pinboard | https://github.com/ryw/pinboard/blob/5c813b7018b7df9a6d359c34ed294eb0d65cb28a/lib/pinboard/util.rb | lib/pinboard/util.rb | module Pinboard
module Util
extend self
def symbolize_keys(hash)
hash.inject({}) do |options, (key, value)|
options[(key.to_sym rescue key) || key] = value
options
end
end
def parse_time(time)
return time if time.is_a?(Time)
return time.to_time if time.is_a?(Date)
Time.parse(time)
end
end
end
| ruby | MIT | 5c813b7018b7df9a6d359c34ed294eb0d65cb28a | 2026-01-04T17:56:09.554894Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/benchmark/run.rb | benchmark/run.rb | #!/usr/bin/env ruby
# frozen_string_literal: true
$LOAD_PATH.unshift('./lib')
require 'benchmark'
require 'masking'
Masking.configure do |config|
config.target_columns_file_path = 'benchmark/masking.yml'
end
n = 30
fixture = File.open('benchmark/users.sql')
Benchmark.bm do |x|
x.report do
n.times do
Masking::Main.new(input: fixture, output: File.open(File::NULL, 'w')).run
fixture.rewind
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking_spec.rb | spec/masking_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Masking do
describe '.run' do
subject { described_class.run }
it 'call Main.new.run' do
expect(Masking::Main).to receive_message_chain(:new, :run)
expect { subject }.not_to raise_error
end
end
describe Masking::Main do
describe '#run' do
subject { described_class.new(input: input, output: _output, line_processor: line_processor).run }
context "with input: 'string'" do
let(:input) { StringIO.new('string') }
let(:_output) { $stdout }
let(:line_processor) do
class_double(
Masking::SQLDumpLine,
new: instance_double(Masking::SQLDumpLine, mask: 'string')
)
end
it "output 'string' to STDOUT" do
expect { subject }.to output('string').to_stdout
end
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
require 'bundler/setup'
require 'rspec'
require 'tapp'
require 'simplecov'
if ENV['CI'] == 'true' &&
# compare only for major/minor version of Ruby in order to enable report for Coverall
Gem::Version.new(RUBY_VERSION).segments[0..1] == \
Gem::Version.new(File.read(File.join(File.dirname(__FILE__), '../.ruby-version'))).segments[0..1]
require 'codecov'
SimpleCov.formatter = SimpleCov::Formatter::Codecov
end
SimpleCov.start { add_filter %r{^/spec/} }
require 'masking'
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure, disable for CI in order to avoid Permission denied error
config.example_status_persistence_file_path = '.rspec_status' unless ENV['CI'] == 'true'
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
def config_fixture_path(name = 'masking.yml')
Pathname('spec/fixtures/config').join(name)
end
def insert_statement_fixture(name = 'sample.sql')
Pathname('spec/fixtures/insert_statement').join(name).read.b
end
def sql_dump_line_fixture(name)
Pathname('spec/fixtures/sql_dump_line').join(name).read.b
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/sql_dump_line_spec.rb | spec/masking/sql_dump_line_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/sql_dump_line'
RSpec.describe Masking::SQLDumpLine do
describe '#mask' do
subject { described_class.new(line, mask_processor: mask_processor).mask }
let(:mask_processor) { class_double(Masking::DataMaskProcessor) }
shared_examples 'should be same with line' do
it { is_expected.to eq line }
end
context 'when line is NOT insert statement line' do
context 'empty' do
let(:line) { '' }
it_behaves_like 'should be same with line'
end
context 'headline' do
let(:line) { sql_dump_line_fixture('headline.sql') }
it_behaves_like 'should be same with line'
end
context 'metadata' do
let(:line) { sql_dump_line_fixture('metadata.sql') }
it_behaves_like 'should be same with line'
end
context 'DDL' do
let(:line) { sql_dump_line_fixture('ddl.sql') }
it_behaves_like 'should be same with line'
end
end
context 'when line is insert statement' do
subject { described_class.new(line, mask_processor: mask_processor).mask }
let(:line) { insert_statement_fixture }
let(:mask_processor) do
class_double(
Masking::DataMaskProcessor,
new: instance_double(Masking::DataMaskProcessor).tap { |double|
expect(double).to receive(:process).and_return(line)
}
)
end
it_behaves_like 'should be same with line'
context 'including invalid utf8 char' do
let(:line) { insert_statement_fixture('with_binary.sql') }
it_behaves_like 'should be same with line'
end
end
end
describe '#insert_statement?' do
subject { described_class.new(line, mask_processor: mask_processor).insert_statement? }
let(:mask_processor) { class_double(Masking::DataMaskProcessor) }
context 'when line is NOT insert statement' do
context 'empty' do
let(:line) { '' }
it { is_expected.to be false }
end
context 'headline' do
let(:line) { sql_dump_line_fixture('headline.sql') }
it { is_expected.to be false }
end
end
context 'when line is insert statement' do
let(:line) { insert_statement_fixture }
it { is_expected.to be true }
end
context 'when line is insert statement including invalid utf8 char' do
let(:line) { insert_statement_fixture('with_binary.sql') }
it { is_expected.to be true }
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/version_spec.rb | spec/masking/version_spec.rb | # frozen_string_literal: true
require 'masking/version'
RSpec.describe Masking::VERSION do
it 'has a version number' do
expect(Masking::VERSION).not_to be_nil # rubocop:disable RSpec/DescribedClass
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/insert_statement_spec.rb | spec/masking/insert_statement_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/insert_statement'
RSpec.describe Masking::InsertStatement do
subject { described_class.new(raw_line, sql_builder: sql_builder) }
let(:raw_line) { insert_statement_fixture }
let(:sql_builder) do
class_double(
Masking::InsertStatement::SQLBuilder,
new: instance_double(Masking::InsertStatement::SQLBuilder, sql: 'dummy sql')
)
end
describe '#table' do
it { expect(subject.table).to eq 'users' }
end
describe '#columns' do
it { expect(subject.columns).to eq %i[id name email password_digest created_at updated_at] }
end
describe '#column_index' do
subject { described_class.new(raw_line, sql_builder: sql_builder).column_index(column_name) }
context 'with contains column name' do
let(:column_name) { :password_digest }
it { is_expected.to eq 3 }
end
context 'without contains column name' do
let(:column_name) { 'hoge' }
it { is_expected.to be_nil }
end
end
describe '#sql' do
before do
expect(sql_builder).to receive(:new).with(
table: 'users',
columns: %i[id name email password_digest created_at updated_at],
values: [
instance_of(Array),
instance_of(Array)
]
)
end
it 'call SQLBuilder' do
expect { subject.sql }.not_to raise_error
end
end
# rubocop:disable Layout/LineLength
describe '#mask_value' do
subject { described_class.new(raw_line).mask_value(column_index: column_index, mask_method: mask_method) }
let(:column_index) { 2 }
let(:mask_method) { double.tap { |d| allow(d).to receive(:call).and_return("'123@email.com'", "'456@email.com'") } }
it {
expect(subject).to match_array [
['1', "'Super Chikahiro'", "'123@email.com'", "'password_digest'", "'2018-03-14 00:00:00'",
"'2018-03-29 00:00:00'"],
['2', "'Super Tokoro'", "'456@email.com'", "'password_digest2'", "'2018-04-01 00:00:00'",
"'2018-04-03 12:00:00'"]
]
}
end
describe '#values' do
subject { described_class.new(raw_line, sql_builder: sql_builder).values }
it 'returns array of InsertStatement::Value' do
expect(subject).to match_array [
['1', "'Super Chikahiro'", "'kibitan@example.com'", "'password_digest'", "'2018-03-14 00:00:00'",
"'2018-03-29 00:00:00'"],
['2', "'Super Tokoro'", "'kibitan++@example.com'", "'password_digest2'", "'2018-04-01 00:00:00'",
"'2018-04-03 12:00:00'"]
]
end
context 'with comma and bracket in value' do
let(:raw_line) {
insert_statement_fixture('comma_and_bracket_and_single_quote_and_empty_string_and_null_in_value.sql')
}
it 'returns array of InsertStatement::Value' do
expect(subject).to match_array [
['1.23',
"'comma ,,, and bracket () and single quote \\' and particular patten ),( and finished on backslash \\\\'", "'kibitan@example.com'"],
['-2.5', "''", 'NULL']
]
end
end
context 'with bracket and comman more than once in value' do
let(:raw_line) { insert_statement_fixture('bracket_and_comma_appears_more_than_once.sql') }
it 'returns array of InsertStatement::Value' do
expect(subject).to match_array [
['1', "'patten ),( and ),( more than once ),('", "'kibitan2@example.com'"],
['-2', "'single quote \\' also appear '", 'NULL']
]
end
end
context 'string seated in last order of columns and include apostrophe and ending parenthesis' do
let(:raw_line) { insert_statement_fixture('string_include_parenthesis.sql') }
it 'returns array of InsertStatement::Value' do
expect(subject).to match_array [
['1', "'sample text'",
%q|'last order of columns and include apostrophe and ending parenthesis \') \') \') this pattern can be wrong'|],
['2', "'sample text 2'", "'test text 2'"]
]
end
end
context 'with Scientific notation in value' do
let(:raw_line) { insert_statement_fixture('number_with_scientific_notation.sql') }
it 'returns array of InsertStatement::Value' do
expect(subject).to match_array [
['9.71726e-17', '1e+030', 'NULL'],
['1.2E3', '-1.2E-3', "'test string'"]
]
end
end
context 'with binary type' do
let(:raw_line) { insert_statement_fixture('with_binary_type.sql') }
it 'returns array of InsertStatement::Value' do
expect(subject).to match_array [
['1', "'sample text'", "_binary 'binarydata'", "_binary 'blob'", "'varchar2'", "'text text'", '123'],
['2', "'sample text 2'", "_binary 'binarydata 2'", "_binary 'blob 2'", "'varchar2 2'", "'text text text'",
'1234']
]
end
end
context 'binary type seated in last order of columns and include apostrophe and ending parenthesis' do
let(:raw_line) { insert_statement_fixture('binary_type_include_parenthesis.sql') }
it 'returns array of InsertStatement::Value' do
expect(subject).to match_array [
['1', "'sample text'",
%q|_binary 'last order of columns and include apostrophe and ending parenthesis \') \') \') this pattern can be wrong'|],
['2', "'sample text 2'", "_binary 'test binary'"]
]
end
end
context 'unhappy path' do
shared_examples_for 'raises error InsertStatementParseError' do
it 'raises error InsertStatementParseError' do
expect { subject }.to raise_error(Masking::Error::InsertStatementParseError)
end
end
context 'without --complete-insert-option statement' do
let(:raw_line) { insert_statement_fixture('without_complete_insert_option.sql') }
it_behaves_like 'raises error InsertStatementParseError'
end
context 'invalid insert statement' do
let(:raw_line) { insert_statement_fixture('invalid_insert_statement.sql') }
it_behaves_like 'raises error InsertStatementParseError'
end
end
end
# rubocop:enable Layout/LineLength
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/data_mask_processor_spec.rb | spec/masking/data_mask_processor_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/data_mask_processor'
class DummyCache
def self.fetch_or_store_if_no_cache(table:, proc:) # rubocop:disable Lint/UnusedMethodArgument
proc.call
end
end
RSpec.describe Masking::DataMaskProcessor do
describe '#process' do
subject {
described_class.new(
insert_statement_line,
target_columns: target_columns,
cache_store: cache_store
).process
}
# TODO: use mock instead of real object or refactoring
let(:target_columns) { Masking::Config::TargetColumns.new(config_fixture_path) }
let(:cache_store) { DummyCache }
context 'when input InsertStatement Line is NOT target_table' do
let(:insert_statement_line) { insert_statement_fixture('dummy_table.sql') }
it { is_expected.to eq(insert_statement_line) }
end
context 'when input InsertStatement Line is target_table' do
context 'when input InsertStatement Line has target_column' do
let(:insert_statement_line) { insert_statement_fixture }
it { is_expected.to eq insert_statement_fixture('sample_masked.sql') }
end
context 'when input InsertStatement Line does NOT have target_column' do
let(:insert_statement_line) { insert_statement_fixture('dummy_columns.sql') }
it { is_expected.to eq(insert_statement_line) }
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/cli_spec.rb | spec/masking/cli_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Masking::Cli do
describe '#run' do
subject { described_class.new(argv).run }
shared_examples 'set config and call Main.run' do
it 'set config and call Main.run' do
expect(Masking).to receive(:config).and_return(
instance_double(Masking::Config).tap do |config|
expect(config).to receive(:target_columns_file_path=).with('config.yml')
end
)
expect(Masking).to receive(:run)
subject
end
end
context 'with option `-cconfig.yml`' do
let(:argv) { ['-cconfig.yml'] }
it_behaves_like 'set config and call Main.run'
end
shared_examples 'print Version and exit' do
it do
expect { subject }.to raise_error(SystemExit) &
output("#{Masking::VERSION}\n").to_stdout
end
it 'exit status is 0' do
$stdout = File.new(File::NULL, 'w')
subject
rescue SystemExit => e
expect(e.status).to eq(0)
ensure
$stdout = STDOUT
end
end
context 'with option `-v`' do
let(:argv) { ['-v'] }
it_behaves_like 'print Version and exit'
end
context 'with option `--version`' do
let(:argv) { ['--version'] }
it_behaves_like 'print Version and exit'
end
context 'with option `-c config.yml`' do
let(:argv) { ['-c', 'config.yml'] }
it_behaves_like 'set config and call Main.run'
end
context 'with option `--config`' do
let(:argv) { ['--config', 'config.yml'] }
it_behaves_like 'set config and call Main.run'
end
context 'unhappy path' do
before do
allow(Masking).to receive(:run)
.and_raise(raising_error)
end
let(:argv) { [] }
shared_examples 'with errormessage and exitstatus is 1' do |error_text|
it do
expect { subject }.to raise_error(SystemExit) &
output(error_text).to_stderr
end
it 'exit status is 1' do
$stdout = File.new(File::NULL, 'w')
subject
rescue SystemExit => e
expect(e.status).to eq(1)
ensure
$stdout = STDOUT
end
end
context 'raise Masking::Config::TargetColumns::FileDoesNotExist' do
let(:raising_error) { Masking::Error::ConfigFileDoesNotExist }
it_behaves_like 'with errormessage and exitstatus is 1', \
"ERROR: config file (masking.yml) does not exist\n"
end
context 'raise Masking::Config::TargetColumns::FileDoesNotExist' do
let(:raising_error) { Masking::Error::ConfigFileIsNotFile }
it_behaves_like 'with errormessage and exitstatus is 1', \
"ERROR: config file (masking.yml) is not file\n"
end
context 'raise Masking::Config::TargetColumns::ConfigFileIsNotValidYaml' do
let(:raising_error) { Masking::Error::ConfigFileIsNotValidYaml }
it_behaves_like 'with errormessage and exitstatus is 1', \
"ERROR: config file (masking.yml) is not valid yaml format\n"
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/config_spec.rb | spec/masking/config_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Masking::Config do
describe 'Masking.config' do
subject { Masking.config }
it { is_expected.to be_instance_of described_class }
end
describe 'Masking.configure' do
subject do
Masking.configure do |config|
config.sample_method = :sample
end
end
it 'delegate method to config object' do
expect_any_instance_of(described_class).to receive(:sample_method=).with(:sample)
subject
end
end
describe '#target_columns_file_path' do
subject { config.target_columns_file_path }
let(:config) { described_class.new }
context 'setting with default' do
it { expect(config.target_columns_file_path).to eq Pathname('masking.yml') }
end
end
describe '#target_columns_file_path=' do
subject { config.target_columns_file_path = target_columns_file_path }
let(:config) { described_class.new }
let(:target_columns_file_path) { config_fixture_path }
it 'set target_columns_file_path' do
subject
expect(config.target_columns_file_path).to eq Pathname(config_fixture_path)
expect(config.target_columns).to eq Masking::Config::TargetColumns.new(config_fixture_path)
end
end
describe '#target_columns' do
subject { config.target_columns }
let(:config) { described_class.new }
it 'return Masking::Config::TargetColumns' do
expect(Masking::Config::TargetColumns).to receive(:new).with(Pathname('masking.yml'))
subject
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/data_mask_processor/cache_spec.rb | spec/masking/data_mask_processor/cache_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/data_mask_processor'
RSpec.describe Masking::DataMaskProcessor::Cache do
describe '.fetch_or_store_if_no_cache' do
subject { described_class.fetch_or_store_if_no_cache(table: 'sample_table', proc: proc { 'sample_value' }) }
before { described_class.clear }
context 'there is no cache' do
it { is_expected.to eq 'sample_value' }
end
context 'if there is a cache' do
before { described_class.fetch_or_store_if_no_cache(table: 'sample_table', proc: proc { 'cached_value' }) }
it { is_expected.to eq 'cached_value' }
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/insert_statement/sql_builder_spec.rb | spec/masking/insert_statement/sql_builder_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/insert_statement/sql_builder'
RSpec.describe Masking::InsertStatement::SQLBuilder do
describe '#sql' do
subject { described_class.new(table: table, columns: columns, values: values).sql }
let(:table) { 'users' }
let(:columns) { %i[id name email address] }
let(:values) do
[
[1, "'John'", "'john@example.com'", "'berlin'"],
[2, "'Super Chikahiro'", "'kibitan++@example.com'", "'tokyo'"]
]
end
it {
expect(subject).to eq \
%|INSERT INTO `users` (`id`, `name`, `email`, `address`) VALUES (1,'John','john@example.com','berlin'),(2,'Super Chikahiro','kibitan++@example.com','tokyo');\n| # rubocop:disable Layout/LineLength
}
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/config/target_columns_spec.rb | spec/masking/config/target_columns_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/config/target_columns'
RSpec.describe Masking::Config::TargetColumns do
describe '#initialize' do
subject { described_class.new(file_path) }
context 'file_path is valid' do
let(:file_path) { config_fixture_path }
it 'contains file_path' do
expect(subject.file_path).to eq config_fixture_path
end
end
context 'file_path does NOT exist' do
let(:file_path) { Pathname('unexist.txt') }
it 'raise error' do
expect { subject }.to raise_error Masking::Error::ConfigFileDoesNotExist
end
end
context 'file_path is directory(NOT file)' do
let(:file_path) { Pathname('tmp/') }
it 'raise error' do
expect { subject }.to raise_error Masking::Error::ConfigFileIsNotFile
end
end
end
describe '#contains?' do
context 'arguments has just table_name' do
subject { described_class.new(file_path).contains?(table_name: table_name) }
let(:file_path) { config_fixture_path }
context 'table_name is included in config yaml' do
let(:table_name) { 'users' }
it { is_expected.to be true }
context 'file_path is NOT valid Yaml' do
let(:file_path) { config_fixture_path('invalid_yaml.yml') }
it 'raise error' do
expect { subject }.to raise_error Masking::Error::ConfigFileIsNotValidYaml
end
end
end
context 'table_name is NOT included in config yaml' do
let(:table_name) { 'hogehoge' }
it { is_expected.to be false }
end
end
end
describe '#columns' do
subject { described_class.new(file_path).columns(table_name: table_name) }
let(:file_path) { config_fixture_path }
context 'table_name is included in config yaml' do
let(:table_name) { 'users' }
it do
expect(subject).to match [
Masking::Config::TargetColumns::Column.new('name', table_name: 'users', method_value: 'name'),
Masking::Config::TargetColumns::Column.new('email', table_name: 'users', method_value: 'email'),
Masking::Config::TargetColumns::Column.new('password_digest', table_name: 'users', method_value: 'string')
]
end
end
context 'table_name is NOT included in config yaml' do
let(:table_name) { 'dummy_users' }
it { is_expected.to be_nil }
end
end
describe '#tables' do
subject { described_class.new(file_path).send(:tables) }
let(:file_path) { config_fixture_path }
specify do
expect(subject).to match(
admin: instance_of(Masking::Config::TargetColumns::Table),
users: instance_of(Masking::Config::TargetColumns::Table)
)
end
context 'file is NOT valid Yaml(contains null as column name)' do
let(:file_path) { config_fixture_path('invalid_yaml_null_column.yml') }
it 'raise error' do
expect { subject }.to raise_error Masking::Error::ConfigFileContainsNullAsColumnName
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/config/target_columns/column_spec.rb | spec/masking/config/target_columns/column_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/config/target_columns/column'
require 'masking/config/target_columns/table'
RSpec.describe Masking::Config::TargetColumns::Column do
let(:name) { 'sample_column' }
let(:table_name) { 'sample_table' }
let(:method_value) { 'sample_method' }
let(:subject_object) { described_class.new(name, table_name: table_name, method_value: method_value) }
describe '#name' do
subject { subject_object.name }
it { is_expected.to eq :sample_column }
context 'column name is nil' do
let(:name) { nil }
it { expect { subject }.to raise_error Masking::Config::TargetColumns::Column::ColumnNameIsNil }
end
end
describe '#table_name' do
subject { subject_object.table_name }
it { is_expected.to eq :sample_table }
end
describe '#==(other)' do
subject do
described_class.new(name, table_name: table_name, method_value: method_value) == # rubocop:disable Lint/BinaryOperatorWithIdenticalOperands
described_class.new(name, table_name: table_name, method_value: method_value)
end
it { is_expected.to be true }
end
describe '#ignore_null?' do
subject { subject_object.ignore_null? }
it { is_expected.to be false }
end
context "when column_name is end with '?'" do
let(:name) { 'sample_column?' }
describe '#name' do
subject { subject_object.name }
it { is_expected.to eq :sample_column }
end
describe '#ignore_null?' do
subject { subject_object.ignore_null? }
it { is_expected.to be true }
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/config/target_columns/table_spec.rb | spec/masking/config/target_columns/table_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/config/target_columns/table'
RSpec.describe Masking::Config::TargetColumns::Table do
let(:name) { 'sample_table' }
let(:columns) do
{
column_a: 'string',
column_b: 123,
column_c: nil
}
end
describe '#name' do
subject { described_class.new(name, columns: columns).name }
it { is_expected.to eq :sample_table }
end
describe '#columns' do
subject { described_class.new(name, columns: columns) }
it do
expect(subject.columns).to match_array [
Masking::Config::TargetColumns::Column.new('column_a', table_name: name, method_value: 'string'),
Masking::Config::TargetColumns::Column.new('column_b', table_name: name, method_value: 123),
Masking::Config::TargetColumns::Column.new('column_c', table_name: name, method_value: nil)
]
end
end
describe '#==(other)' do
subject { described_class.new(name, columns: columns) == described_class.new(name, columns: columns) } # rubocop:disable Lint/BinaryOperatorWithIdenticalOperands
it { is_expected.to be true }
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/config/target_columns/method_spec.rb | spec/masking/config/target_columns/method_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/config/target_columns/method'
require 'masking/config/target_columns/method/type/extension/ignore_null'
RSpec.describe Masking::Config::TargetColumns::Method do
shared_examples_for 'with argument `ignore_null: true`' do
context 'with argument `ignore_null: true`' do
subject { described_class.new(method, ignore_null: true) }
it {
expect(
subject.instance_variable_get(:@method_type)
.singleton_class
.ancestors
.include?(Masking::Config::TargetColumns::Method::Type::Extension::IgnoreNull)
).to be true
}
end
end
describe '.new' do
subject { described_class.new(method) }
context 'when String' do
let(:method) { 'string' }
it do
expect(Masking::Config::TargetColumns::Method::StringBinaryDistinctor).to receive(:new).with('string')
subject
end
include_examples 'with argument `ignore_null: true`'
end
context 'when Integer' do
let(:method) { 123 }
it do
expect(Masking::Config::TargetColumns::Method::Type::Integer).to receive(:new).with(123)
subject
end
include_examples 'with argument `ignore_null: true`'
end
context 'when Float' do
let(:method) { 123.456 }
it do
expect(Masking::Config::TargetColumns::Method::Type::Float).to receive(:new).with(123.456)
subject
end
include_examples 'with argument `ignore_null: true`'
end
context 'when date' do
let(:method) { Date.new(2018, 3, 14) }
it do
expect(Masking::Config::TargetColumns::Method::Type::Date).to receive(:new).with(Date.new(2018, 3, 14))
subject
end
include_examples 'with argument `ignore_null: true`'
end
context 'when time' do
let(:method) { Time.new(2018, 3, 14, 15, 31, 0) }
it do
expect(Masking::Config::TargetColumns::Method::Type::Time).to receive(:new).with(Time.new(2018, 3, 14, 15, 31,
0))
subject
end
include_examples 'with argument `ignore_null: true`'
end
context 'when true' do
let(:method) { true }
it do
expect(Masking::Config::TargetColumns::Method::Type::Boolean).to receive(:new).with(true)
subject
end
include_examples 'with argument `ignore_null: true`'
end
context 'when false' do
let(:method) { false }
it do
expect(Masking::Config::TargetColumns::Method::Type::Boolean).to receive(:new).with(false)
subject
end
include_examples 'with argument `ignore_null: true`'
end
context 'when nil' do
let(:method) { nil }
it do
expect(Masking::Config::TargetColumns::Method::Type::Null).to receive(:new).with(nil)
subject
end
include_examples 'with argument `ignore_null: true`'
end
context 'unhappy path: Unknown type' do
let(:method) { NotImplementedError }
it { expect { subject }.to raise_error(Masking::Config::TargetColumns::Method::UnknownType) }
end
end
describe '#call' do
subject { described_class.new(nil).call('_sql_value') }
it 'delegate to concreate object' do
expect(Masking::Config::TargetColumns::Method::Type::Null).to receive(:new).with(nil).and_return(
instance_double(Masking::Config::TargetColumns::Method::Type::Null).tap do |double|
expect(double).to receive(:call)
end
)
subject
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/config/target_columns/method/string_binary_distinctor_spec.rb | spec/masking/config/target_columns/method/string_binary_distinctor_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/config/target_columns/method/string_binary_distinctor'
RSpec.describe Masking::Config::TargetColumns::Method::StringBinaryDistinctor do
describe '.new' do
subject { described_class.new(arg) }
context 'with argument is string' do
let(:arg) { 'string' }
it { is_expected.to be_instance_of Masking::Config::TargetColumns::Method::Type::String }
end
context 'with binary string (only ascii)' do
let(:arg) { 'aiueo'.b }
it { is_expected.to be_instance_of Masking::Config::TargetColumns::Method::Type::Binary }
end
context 'with argument is binary (non ascii)' do
let(:arg) { "\x00\x92".b }
it { is_expected.to be_instance_of Masking::Config::TargetColumns::Method::Type::Binary }
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/config/target_columns/method/type/null_spec.rb | spec/masking/config/target_columns/method/type/null_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/config/target_columns/method/type/null'
RSpec.describe Masking::Config::TargetColumns::Method::Type::Null do
describe '#call' do
subject { described_class.new(value).call('sql_value') }
let(:value) { nil }
it { is_expected.to eq 'NULL' }
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/config/target_columns/method/type/string_spec.rb | spec/masking/config/target_columns/method/type/string_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/config/target_columns/method/type/string'
RSpec.describe Masking::Config::TargetColumns::Method::Type::String do
describe '#call' do
subject { described_class.new(value).call('sql_value') }
context 'with "hoge"' do
let(:value) { 'hoge' }
it { is_expected.to eq "'hoge'" }
end
context 'with "あああ"' do
let(:value) { 'あああ' }
it { is_expected.to eq "'あああ'".b }
end
# rubocop:disable Style/FormatStringToken
context 'with sequential number placeholder %{n}' do
subject(:subject_object) { described_class.new(value) }
let(:value) { 'number%{n}' }
it 'increment number each by call' do
expect(subject_object.call('sql_value')).to eq "'number1'"
expect(subject_object.call('sql_value')).to eq "'number2'"
expect(subject_object.call('sql_value')).to eq "'number3'"
end
end
# rubocop:enable Style/FormatStringToken
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/config/target_columns/method/type/binary_spec.rb | spec/masking/config/target_columns/method/type/binary_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/config/target_columns/method/type/binary'
RSpec.describe Masking::Config::TargetColumns::Method::Type::Binary do
describe '#call' do
context 'with binary string (only ascii)' do
let(:value) { 'only ascii binary' }
it { expect(described_class.new(value).call('sql_value')).to eq "_binary 'only ascii binary'" }
it('encoding in ascii 8bit') {
expect(described_class.new(value).call('sql_value').encoding).to eq Encoding::ASCII_8BIT
}
end
context 'with binary string (non ascii)' do
let(:value) { "\x92".b }
it { expect(described_class.new(value).call('sql_value')).to eq "_binary '\x92'".b }
it('encoding in ascii 8bit') {
expect(described_class.new(value).call('sql_value').encoding).to eq Encoding::ASCII_8BIT
}
end
context 'with empty binary' do
let(:value) { ''.b }
it { expect(described_class.new(value).call('sql_value')).to eq "_binary ''" }
it('encoding in ascii 8bit') {
expect(described_class.new(value).call('sql_value').encoding).to eq Encoding::ASCII_8BIT
}
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/config/target_columns/method/type/base_spec.rb | spec/masking/config/target_columns/method/type/base_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/config/target_columns/method/type/base'
RSpec.describe Masking::Config::TargetColumns::Method::Type::Base do
describe '#value' do
context 'when initialized with abc' do
let(:type) { described_class.new('abc') }
it 'returns abc' do
expect(type.instance_variable_get(:@value)).to eq('abc')
end
end
end
describe '#call' do
let(:type) { described_class.new('test') }
it 'raises NotImplementedError' do
expect { type.call('sql_value') }.to raise_error(NotImplementedError)
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/config/target_columns/method/type/time_spec.rb | spec/masking/config/target_columns/method/type/time_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/config/target_columns/method/type/time'
RSpec.describe Masking::Config::TargetColumns::Method::Type::Time do
describe '#call' do
subject { described_class.new(value).call('sql_value') }
context 'when 2018-03-20 18:15:30' do
let(:value) { Time.new(2018, 3, 20, 18, 15, 30) }
it { is_expected.to eq "'2018-03-20 18:15:30'" }
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/config/target_columns/method/type/float_spec.rb | spec/masking/config/target_columns/method/type/float_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/config/target_columns/method/type/float'
RSpec.describe Masking::Config::TargetColumns::Method::Type::Float do
describe '#call' do
subject { described_class.new(value).call('sql_value') }
context 'when 1.2345' do
let(:value) { 1.2345 }
it { is_expected.to eq '1.2345' }
end
context 'when 1234.500' do
let(:value) { 1234.500 }
it { is_expected.to eq '1234.5' }
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/config/target_columns/method/type/boolean_spec.rb | spec/masking/config/target_columns/method/type/boolean_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/config/target_columns/method/type/integer'
RSpec.describe Masking::Config::TargetColumns::Method::Type::Boolean do
describe '#call' do
subject { described_class.new(value).call('sql_value') }
context 'when false' do
let(:value) { false }
it { is_expected.to eq '0' }
end
context 'when true' do
let(:value) { true }
it { is_expected.to eq '1' }
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/config/target_columns/method/type/date_spec.rb | spec/masking/config/target_columns/method/type/date_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/config/target_columns/method/type/date'
RSpec.describe Masking::Config::TargetColumns::Method::Type::Date do
describe '#call' do
subject { described_class.new(value).call('sql_value') }
context 'when 2018-07-20' do
let(:value) { Date.new(2018, 7, 20) }
it { is_expected.to eq "'2018-07-20'" }
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/config/target_columns/method/type/integer_spec.rb | spec/masking/config/target_columns/method/type/integer_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/config/target_columns/method/type/integer'
RSpec.describe Masking::Config::TargetColumns::Method::Type::Integer do
describe '#call' do
subject { described_class.new(value).call('sql_value') }
context 'when 12345' do
let(:value) { 12_345 }
it { is_expected.to eq '12345' }
end
context 'when -12' do
let(:value) { -12 }
it { is_expected.to eq '-12' }
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/config/target_columns/method/type/extension/ignore_null_spec.rb | spec/masking/config/target_columns/method/type/extension/ignore_null_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/config/target_columns/method/type/base'
require 'masking/config/target_columns/method/type/extension/ignore_null'
RSpec.describe Masking::Config::TargetColumns::Method::Type::Extension::IgnoreNull do
let(:base_type_class) do
Class.new(Masking::Config::TargetColumns::Method::Type::Base) do
def call(_sql_value)
'original call'
end
end
end
let(:prepended_object) do
base_type_class.new('mask_value').tap { |obj| obj.singleton_class.prepend(described_class) }
end
let(:not_prepended_object) do
base_type_class.new('mask_value')
end
describe '#call' do
context 'when NULL' do
let(:sql_value) { 'NULL' }
it 'returns NULL' do
expect(prepended_object.call(sql_value)).to eq('NULL')
end
it 'does not affect another object' do
prepended_object.call(sql_value)
expect(not_prepended_object.call(sql_value)).to eq('original call')
end
context 'when sequence! method is defined' do
let(:base_type_class) do
Class.new(Masking::Config::TargetColumns::Method::Type::Base) do
def call(_sql_value)
'original call'
end
private
def sequence!; end
end
end
it 'call sequence! method' do
expect(prepended_object).to receive(:sequence!)
prepended_object.call(sql_value)
end
end
end
context 'when is not NULL' do
let(:sql_value) { 'abc' }
it 'returns the original call' do
expect(prepended_object.call(sql_value)).to eq('original call')
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/masking/cli/error_message_spec.rb | spec/masking/cli/error_message_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'masking/cli/error_message'
RSpec.describe Masking::Cli::ErrorMessage do
describe '#message' do
subject { described_class.new(error).message(**keyword_args) }
describe 'Masking::Error::ConfigFileDoesNotExist' do
let(:error) { Masking::Error::ConfigFileDoesNotExist }
let(:keyword_args) { { config_file_path: 'tmp/target_columns.yml' } }
it { is_expected.to eq 'ERROR: config file (tmp/target_columns.yml) does not exist' }
end
describe 'Masking::Error::ConfigFileIsNotFile' do
let(:error) { Masking::Error::ConfigFileIsNotFile }
let(:keyword_args) { { config_file_path: 'tmp/target_columns.yml' } }
it { is_expected.to eq 'ERROR: config file (tmp/target_columns.yml) is not file' }
end
describe 'Masking::Error::ConfigFileIsNotValidYaml' do
let(:error) { Masking::Error::ConfigFileIsNotValidYaml }
let(:keyword_args) { { config_file_path: 'tmp/target_columns.yml' } }
it { is_expected.to eq 'ERROR: config file (tmp/target_columns.yml) is not valid yaml format' }
end
describe 'Masking::Error::ConfigFileContainsNullAsColumnName' do
let(:error) { Masking::Error::ConfigFileContainsNullAsColumnName }
let(:keyword_args) { { config_file_path: 'tmp/target_columns.yml' } }
it {
expect(subject).to eq \
'ERROR: config file (tmp/target_columns.yml) is not valid, ' \
'column name contains `null`'
}
end
describe 'Masking::Error::InsertStatementParseError' do
let(:error) { Masking::Error::InsertStatementParseError }
let(:keyword_args) { {} }
it {
expect(subject).to eq \
'ERROR: cannot parse SQL dump file. you may forget to put `--complete-insert` option in mysqldump?'
}
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/integration/integration_spec_helper.rb | spec/integration/integration_spec_helper.rb | # frozen_string_literal: true
require 'spec_helper'
require 'open3'
def command_subject(command, stdin: '')
subject { Open3.capture3(command, stdin_data: stdin) }
let(:stdout) { subject[0] }
let(:stderr) { subject[1] }
let(:exitstatus) { subject[2].exitstatus }
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/spec/integration/commandline_spec.rb | spec/integration/commandline_spec.rb | # frozen_string_literal: true
require_relative 'integration_spec_helper'
RSpec.describe 'execute in command line' do
context 'with version option' do
command_subject('masking -v')
it 'puts version', :aggregate_failures do
expect(stdout).to eq("#{Masking::VERSION}\n")
expect(stderr).to be_empty
expect(exitstatus).to eq(0)
end
end
context 'with target_columns.yml' do
command_subject("masking -c #{config_fixture_path}", stdin: insert_statement_fixture)
it 'maskeds correctly', :aggregate_failures do
expect(stdout).to eq(insert_statement_fixture('sample_masked.sql'))
expect(stderr).to be_empty
expect(exitstatus).to eq(0)
end
end
context 'with various type of data' do
context 'config file with sequential_number_replace' do
context 'multiple insert statement lines for same table' do
command_subject(
"masking -c #{config_fixture_path('masking_with_sequential_number_replace.yml')}",
stdin: sql_dump_line_fixture('multiple_lines_of_users.sql')
)
it 'maskeds correctly', :aggregate_failures do
expect(stdout).to eq(sql_dump_line_fixture('masked_multiple_lines_of_users.sql'))
expect(stderr).to be_empty
expect(exitstatus).to eq(0)
end
end
end
end
context 'error handling(unhappy path)' do
context 'with not exists config' do
command_subject('masking -c not_exists.yml', stdin: insert_statement_fixture)
it 'faileds with error message', :aggregate_failures do
expect(stdout).to be_empty
expect(stderr).to eq "ERROR: config file (not_exists.yml) does not exist\n"
expect(exitstatus).to eq(1)
end
end
context 'with directory path (not file)' do
command_subject('masking -c tmp/', stdin: insert_statement_fixture)
it 'faileds with error message', :aggregate_failures do
expect(stdout).to be_empty
expect(stderr).to eq "ERROR: config file (tmp/) is not file\n"
expect(exitstatus).to eq(1)
end
end
context 'with invalid yaml file path' do
command_subject("masking -c #{config_fixture_path('invalid_yaml.yml')}", stdin: insert_statement_fixture)
it 'faileds with error message', :aggregate_failures do
expect(stdout).to be_empty
expect(stderr).to eq "ERROR: config file (spec/fixtures/config/invalid_yaml.yml) is not valid yaml format\n"
expect(exitstatus).to eq(1)
end
end
context 'with invalid yaml file path' do
command_subject(
"masking -c #{config_fixture_path('invalid_yaml_null_column.yml')}",
stdin: insert_statement_fixture
)
it 'faileds with error message', :aggregate_failures do
expect(stdout).to be_empty
expect(stderr).to eq \
'ERROR: config file (spec/fixtures/config/invalid_yaml_null_column.yml) is not valid, ' \
"column name contains `null`\n"
expect(exitstatus).to eq(1)
end
end
pending 'with invalid config structure'
shared_examples_for 'should fail with parse error message' do
it 'faileds with error message', :aggregate_failures do
expect(stdout).to be_empty
expect(stderr).to eq(
"ERROR: cannot parse SQL dump file. you may forget to put `--complete-insert` option in mysqldump?\n"
)
expect(exitstatus).to eq(1)
end
end
context 'with sqldump which is not specified `--complete-insert` option' do
command_subject(
"masking -c #{config_fixture_path}",
stdin: insert_statement_fixture('without_complete_insert_option.sql')
)
it_behaves_like 'should fail with parse error message'
end
context 'with sqldump which contains invalid insert statement' do
command_subject(
"masking -c #{config_fixture_path}",
stdin: insert_statement_fixture('invalid_insert_statement.sql')
)
it_behaves_like 'should fail with parse error message'
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking.rb | lib/masking.rb | # frozen_string_literal: true
require 'masking/cli'
require 'masking/config'
require 'masking/sql_dump_line'
module Masking
class << self
def run
Main.new.run
end
end
class Main
def initialize(input: $stdin, output: $stdout, line_processor: SQLDumpLine)
@input = input.set_encoding(Encoding::ASCII_8BIT, Encoding::ASCII_8BIT)
@output = output.set_encoding(Encoding::ASCII_8BIT, Encoding::ASCII_8BIT)
@line_processor = line_processor
end
def run
input.each_line do |line|
output.print line_processor.new(line).mask
end
end
private
attr_reader :input, :output, :line_processor
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/version.rb | lib/masking/version.rb | # frozen_string_literal: true
module Masking
VERSION = '1.1.3-alpha'
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/data_mask_processor.rb | lib/masking/data_mask_processor.rb | # frozen_string_literal: true
require 'masking/data_mask_processor/cache'
require 'masking/config/target_columns'
require 'masking/insert_statement'
module Masking
class DataMaskProcessor
def initialize(
insert_statement_line,
target_columns: ::Masking.config.target_columns,
insert_statement: InsertStatement.new(insert_statement_line),
cache_store: Cache
)
@raw_line = insert_statement_line
@target_columns = target_columns
@insert_statement = insert_statement
@cache_store = cache_store
end
def process
return raw_line unless target_table?
column_indexes_mask_methods.each do |column_index, mask_method|
next if column_index.nil?
insert_statement.mask_value(
column_index: column_index,
mask_method: mask_method
)
end
insert_statement.sql
end
private
attr_reader :raw_line, :target_columns, :insert_statement, :cache_store
def target_table?
target_columns.contains?(table_name: table_name)
end
def column_indexes_mask_methods
cache_store.fetch_or_store_if_no_cache(
table: table_name,
proc: proc {
target_columns.columns(table_name: table_name).map do |column|
[insert_statement.column_index(column.name), column.method]
end
}
)
end
def table_name
@table_name = insert_statement.table
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/insert_statement.rb | lib/masking/insert_statement.rb | # frozen_string_literal: true
require 'masking/errors'
require 'masking/insert_statement/sql_builder'
module Masking
class InsertStatement
attr_reader :raw_statement, :table
def initialize(raw_statement, sql_builder: SQLBuilder)
@raw_statement = raw_statement
@sql_builder = sql_builder
PARSE_REGEXP.match(raw_statement).tap do |match_data|
raise Error::InsertStatementParseError if match_data.nil?
@table = match_data[:table]
@columns_section = match_data[:columns_section]
@values_section = match_data[:values_section]
end
end
def columns
@columns ||= columns_section.scan(COLUMNS_REGEXP).flatten.map(&:to_sym)
end
def column_index(column_name)
columns.index(column_name)
end
def values
# NOTE: the reason to use `rows.each_with_index()`
# another simple implementations (e.g. `rows.count.time`) doesn't work.because during the block loop,
# the `rows` array object can be destructively changed by the #recursive_pattern_value_concat! method and
# it make different number of count to loop during the block loop, so it needs to be checked by the object size
@values ||= values_section.split(VALUE_ROW_SPLITTER)
.tap { |rows| rows.each_with_index { |_, i| recursive_pattern_value_concat!(rows, i) } }
.flat_map { |row| row.scan(values_regexp) }
end
def mask_value(column_index:, mask_method:)
values.each do |value|
value[column_index] = mask_method.call(value[column_index])
end
end
def sql
sql_builder.new(table: table, columns: columns, values: values).sql
end
private
attr_reader :columns_section, :values_section, :sql_builder
VALUE_ROW_SPLITTER = '),('
PARSE_REGEXP = /INSERT INTO `(?<table>.+)` \((?<columns_section>.+)\) VALUES (?<values_section>.+);/.freeze
COLUMNS_REGEXP = /`(.*?)`/.freeze
# NOTE: in mysqldump,
# integer/float/NULL type has dumped without single quote. e.g. -123 / 2.4 / NULL
# string/time type has dumped with single quote. e.g. 'string' / '2018-08-22 13:27:34'
# binary/blob type has dumped with _binary prefix. e.g. _binary 'binarydata'
# if there is single quote inside of value, it will dumped with escape. e.g. 'chikahiro\'s item'
# in number, there could be include Scientific notation e.g. 1.2E3 / -1.2E-3 / 1e+030 / 9.71726e-17
# refs: https://dev.mysql.com/doc/refman/5.7/en/precision-math-numbers.html
NUMBER_REGEXP = '[+eE0-9.-]+'
NULL_REGEXP = 'NULL'
STRING_TIME_REGEXP = "'.*?'"
BINARY_REGEXP = "_binary '.*?'"
VALUE_REGEXP = "(#{NUMBER_REGEXP}|#{NULL_REGEXP}|#{STRING_TIME_REGEXP}|#{BINARY_REGEXP})"
def values_regexp
@values_regexp ||= /^\(?#{([VALUE_REGEXP] * columns.count).join(?,)}\)?$/
end
# Check single quote count on each value, and just continue if it's even number.
# if it's odd, concat with next row (it means a value contains "),(" pattern)
# e.g. INSERT ... VALUES (123,'string ),( abc'),(456,'ab');
# refs: implementation of parsing CSV on ruby standard library FasterCSV (ja): https://www.clear-code.com/blog/2018/12/25.html
def recursive_pattern_value_concat!(value_rows, index)
return if value_rows[index].gsub('\\\\', '').gsub("\\'", '').count(?').even?
# make destructive change for values_rows
value_rows[index] += VALUE_ROW_SPLITTER + value_rows.delete_at(index + 1)
recursive_pattern_value_concat!(value_rows, index)
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/errors.rb | lib/masking/errors.rb | # frozen_string_literal: true
# Global Errors in Masking library
module Masking
class Error < StandardError
class ConfigFileDoesNotExist < Error; end
class ConfigFileIsNotFile < Error; end
class ConfigFileIsNotValidYaml < Error; end
class ConfigFileContainsNullAsColumnName < Error; end
class InsertStatementParseError < Error; end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/sql_dump_line.rb | lib/masking/sql_dump_line.rb | # frozen_string_literal: true
require 'masking/data_mask_processor'
module Masking
class SQLDumpLine
def initialize(line, mask_processor: DataMaskProcessor)
@line = line
@mask_processor = mask_processor
end
def mask
processor.new(line).process
end
def insert_statement?
line.match?(INSERT_STATEMENT_REGEXP)
end
private
attr_reader :line, :mask_processor
INSERT_STATEMENT_REGEXP = /^INSERT/.freeze
def processor
insert_statement? ? mask_processor : NoMaskProcessor
end
class NoMaskProcessor
def initialize(line)
@line = line
end
def process
@line # do nothing
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/cli.rb | lib/masking/cli.rb | # frozen_string_literal: true
require 'masking/config'
require 'masking/version'
require 'masking/errors'
require 'masking/cli/error_message'
require 'optparse'
module Masking
class Cli
def initialize(argv)
@argv = argv
end
def run
option_parser.parse(argv)
Masking.run
rescue Masking::Error => e
warn(Masking::Cli::ErrorMessage.new(e).message(config_file_path: Masking.config.target_columns_file_path))
exit(false)
end
private
attr_reader :argv
def option_parser
OptionParser.new do |parser|
parser.banner = 'Usage: masking [options]'
define_config_option(parser)
define_version_option(parser)
end
end
def define_config_option(parser)
parser.on('-cFILE_PATH', '--config=FILE_PATH', 'specify config file. default: masking.yml') do |file_path|
Masking.configure do |config|
config.target_columns_file_path = file_path
end
end
end
def define_version_option(parser)
parser.on('-v', '--version', 'version') do
puts Masking::VERSION
exit
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/config.rb | lib/masking/config.rb | # frozen_string_literal: true
require 'pathname'
require 'masking/config/target_columns'
module Masking
class << self
def config
@config ||= Config.new
end
def configure
yield config
end
end
class Config
DEFAULT_TARGET_COLUMNS_YAML_PATH = Pathname('masking.yml')
attr_reader :target_columns_file_path
def initialize
@target_columns_file_path = DEFAULT_TARGET_COLUMNS_YAML_PATH
end
def target_columns_file_path=(val)
@target_columns_file_path = Pathname(val)
@target_columns = TargetColumns.new(target_columns_file_path)
end
def target_columns
@target_columns ||= TargetColumns.new(target_columns_file_path)
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/data_mask_processor/cache.rb | lib/masking/data_mask_processor/cache.rb | # frozen_string_literal: true
module Masking
class DataMaskProcessor
class Cache
def self.fetch_or_store_if_no_cache(table:, proc:)
@cache ||= {}
if @cache.key?(table)
@cache[table]
else
@cache[table] = proc.call
end
end
# onlu for test
def self.clear
@cache = {}
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/insert_statement/sql_builder.rb | lib/masking/insert_statement/sql_builder.rb | # frozen_string_literal: true
module Masking
class InsertStatement
class SQLBuilder
def initialize(table:, columns:, values:)
@table = table
@columns = columns
@values = values
end
def sql
%(INSERT INTO `#{table}` #{columns_section} VALUES #{values_section};\n)
end
private
attr_reader :table, :columns, :values
def columns_section
'(' + columns.map { |column| "`#{column}`" }.join(', ') + ')' # rubocop:disable Style/StringConcatenation
end
def values_section
values.map { |value| "(#{value.join(',')})" }.join(',')
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/config/target_columns.rb | lib/masking/config/target_columns.rb | # frozen_string_literal: true
require 'yaml'
require 'masking/config/target_columns/table'
require 'masking/config/target_columns/column'
require 'masking/errors'
module Masking
class Config
# TODO: find better naming of TargetColumns
class TargetColumns
attr_reader :file_path
def initialize(file_path)
@file_path = file_path
raise Masking::Error::ConfigFileDoesNotExist unless file_path.exist?
raise Masking::Error::ConfigFileIsNotFile unless file_path.file?
end
def contains?(table_name:)
data.key?(table_name)
end
# TODO: refactoring
def columns(table_name:)
tables[table_name.to_sym]&.columns
end
def ==(other)
file_path == other.file_path
end
private
def data
@data ||= YAML.safe_load(file_path.read, permitted_classes: [Date, Time])
rescue Psych::SyntaxError
raise Masking::Error::ConfigFileIsNotValidYaml
end
# TODO: extract to other class
def tables
@tables ||= data.each_with_object({}) do |kv, r|
r[kv[0].to_sym] = Table.new(kv[0], columns: kv[1])
end
rescue Masking::Config::TargetColumns::Column::ColumnNameIsNil
raise Masking::Error::ConfigFileContainsNullAsColumnName
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/config/target_columns/table.rb | lib/masking/config/target_columns/table.rb | # frozen_string_literal: true
require 'masking/config/target_columns/column'
module Masking
class Config
class TargetColumns
class Table
attr_reader :name, :columns
def initialize(name, columns:)
@name = name.to_sym
@columns = columns.map do |column, method_value|
Masking::Config::TargetColumns::Column.new(column, table_name: self.name, method_value: method_value)
end
end
def ==(other)
name == other.name
end
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/config/target_columns/method.rb | lib/masking/config/target_columns/method.rb | # frozen_string_literal: true
require 'pathname'
require 'forwardable'
require 'masking/config/target_columns/method/type/extension/ignore_null'
require 'masking/config/target_columns/method/string_binary_distinctor'
Dir[Pathname(__FILE__).dirname.join('method/type/*.rb').to_s].sort.each(&method(:require))
module Masking
class Config
class TargetColumns
class Method
extend Forwardable
def initialize(method, ignore_null: false)
@method_type = mapping(method.class).new(method).tap do |obj|
obj.singleton_class.prepend(Type::Extension::IgnoreNull) if ignore_null
end
end
def_delegator :@method_type, :call
private
# rubocop:disable Layout/HashAlignment
MAPPING = {
::String => StringBinaryDistinctor,
::Integer => Type::Integer,
::Float => Type::Float,
::Date => Type::Date,
::Time => Type::Time,
::TrueClass => Type::Boolean,
::FalseClass => Type::Boolean,
::NilClass => Type::Null
}.freeze
# rubocop:enable Layout/HashAlignment
def mapping(klass)
MAPPING[klass] || raise(UnknownType)
end
class UnknownType < RuntimeError; end
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/config/target_columns/column.rb | lib/masking/config/target_columns/column.rb | # frozen_string_literal: true
require 'masking/config/target_columns/method'
module Masking
class Config
class TargetColumns
class Column
attr_reader :table_name, :method_value, :method
def initialize(name, table_name:, method_value:)
raise ColumnNameIsNil if name.nil?
@original_name = name.to_sym
@table_name = table_name.to_sym
@method_value = method_value
@method = Method.new(method_value, ignore_null: ignore_null?)
end
def ==(other)
name == other.name && table_name == other.table_name && method_value == other.method_value
end
def name
@name ||= ignore_null? ? original_name.to_s.chomp(IGNORE_NULL_SUFFIX).to_sym : original_name
end
def ignore_null?
@ignore_null ||= original_name.to_s.end_with?(IGNORE_NULL_SUFFIX)
end
class ColumnNameIsNil < StandardError; end
private
attr_reader :original_name
IGNORE_NULL_SUFFIX = '?'
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/config/target_columns/method/string_binary_distinctor.rb | lib/masking/config/target_columns/method/string_binary_distinctor.rb | # frozen_string_literal: true
require 'masking/config/target_columns/method/type/binary'
require 'masking/config/target_columns/method/type/string'
module Masking
class Config
class TargetColumns
class Method
module StringBinaryDistinctor
class << self
def new(value)
binary?(value) ? Type::Binary.new(value) : Type::String.new(value)
end
private
# NOTE: this is referenced code from standard library
# ruby/psych: Rely on encoding tags to determine if string should be dumped as binary
# https://github.com/ruby/psych/commit/8949a47b8cee31e03e21608406ba116adcf74054
# https://github.com/ruby/psych/issues/278
# https://github.com/ruby/psych/blob/e01839af57df559b26f74e906062be6c692c89c8/lib/psych/visitors/yaml_tree.rb#L419-L421
def binary?(string)
string.encoding == Encoding::ASCII_8BIT
end
end
end
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/config/target_columns/method/type/binary.rb | lib/masking/config/target_columns/method/type/binary.rb | # frozen_string_literal: true
require 'masking/config/target_columns/method/type/base'
module Masking
class Config
class TargetColumns
class Method
module Type
class Binary < Base
def call(_sql_value)
"_binary '#{value}'".b
end
end
end
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/config/target_columns/method/type/time.rb | lib/masking/config/target_columns/method/type/time.rb | # frozen_string_literal: true
require 'masking/config/target_columns/method/type/base'
module Masking
class Config
class TargetColumns
class Method
module Type
class Time < Base
def call(_sql_value)
"'#{time_format}'"
end
private
FORMAT = '%Y-%m-%d %H:%M:%S'
def time_format
value.strftime(FORMAT)
end
end
end
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/config/target_columns/method/type/float.rb | lib/masking/config/target_columns/method/type/float.rb | # frozen_string_literal: true
require 'masking/config/target_columns/method/type/base'
module Masking
class Config
class TargetColumns
class Method
module Type
class Float < Base
def call(_sql_value)
value.to_s
end
end
end
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/config/target_columns/method/type/boolean.rb | lib/masking/config/target_columns/method/type/boolean.rb | # frozen_string_literal: true
require 'masking/config/target_columns/method/type/base'
module Masking
class Config
class TargetColumns
class Method
module Type
class Boolean < Base
def call(_sql_value)
boolean_format.to_s
end
private
# NOTE: 11.1.1 Numeric Type Overview, chapter BOOL, BOOLEAN
# https://dev.mysql.com/doc/refman/8.0/en/numeric-type-overview.html
def boolean_format
value ? 1 : 0
end
end
end
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/config/target_columns/method/type/base.rb | lib/masking/config/target_columns/method/type/base.rb | # frozen_string_literal: true
module Masking
class Config
class TargetColumns
class Method
module Type
class Base
def initialize(value)
@value = value
end
def call(_sql_value)
raise NotImplementedError
end
private
attr_reader :value
end
end
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/config/target_columns/method/type/null.rb | lib/masking/config/target_columns/method/type/null.rb | # frozen_string_literal: true
module Masking
class Config
class TargetColumns
class Method
module Type
class Null < Base
def call(_sql_value)
'NULL'
end
end
end
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/config/target_columns/method/type/string.rb | lib/masking/config/target_columns/method/type/string.rb | # frozen_string_literal: true
require 'masking/config/target_columns/method/type/base'
module Masking
class Config
class TargetColumns
class Method
module Type
class String < Base
def initialize(value)
super(value)
@sequence = 0
end
def call(_sql_value)
sequence!
"'#{output}'".b
end
private
SEQUENTIAL_NUMBER_PLACEHOLDER = '%{n}' # rubocop:disable Style/FormatStringToken
def output
value.sub(SEQUENTIAL_NUMBER_PLACEHOLDER, @sequence.to_s)
end
def sequence!
@sequence += 1
end
end
end
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/config/target_columns/method/type/integer.rb | lib/masking/config/target_columns/method/type/integer.rb | # frozen_string_literal: true
require 'masking/config/target_columns/method/type/base'
module Masking
class Config
class TargetColumns
class Method
module Type
class Integer < Base
def call(_sql_value)
value.to_s
end
end
end
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/config/target_columns/method/type/date.rb | lib/masking/config/target_columns/method/type/date.rb | # frozen_string_literal: true
require 'masking/config/target_columns/method/type/base'
require 'date'
module Masking
class Config
class TargetColumns
class Method
module Type
class Date < Base
def call(_sql_value)
"'#{date_format}'"
end
private
FORMAT = '%Y-%m-%d'
def date_format
value.strftime(FORMAT)
end
end
end
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/config/target_columns/method/type/extension/ignore_null.rb | lib/masking/config/target_columns/method/type/extension/ignore_null.rb | # frozen_string_literal: true
module Masking
class Config
class TargetColumns
class Method
module Type
module Extension
module IgnoreNull
def call(sql_value)
if sql_value == 'NULL'
sequence! if respond_to?(:sequence!, true)
return 'NULL'
end
super
end
end
end
end
end
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
kibitan/masking | https://github.com/kibitan/masking/blob/ad72ffa4263c94de97b1749df8791d254e38017e/lib/masking/cli/error_message.rb | lib/masking/cli/error_message.rb | # frozen_string_literal: true
require 'erb'
require 'ostruct'
require 'masking/errors'
module Masking
class Cli
class ErrorMessage
def initialize(error_class)
@error_class = error_class
end
def message(**keyword_args)
error_message(keyword_args)
end
private
attr_reader :error_class
def error_message(keyword_args)
ERB.new(
ERROR_MESSAGES.fetch(error_class.to_s)
).result(
OpenStruct.new(keyword_args).instance_eval { binding } # rubocop:disable Style/OpenStructUse
)
end
ERROR_MESSAGES = {
'Masking::Error::ConfigFileDoesNotExist' =>
'ERROR: config file (<%= config_file_path %>) does not exist',
'Masking::Error::ConfigFileIsNotFile' =>
'ERROR: config file (<%= config_file_path %>) is not file',
'Masking::Error::ConfigFileIsNotValidYaml' =>
'ERROR: config file (<%= config_file_path %>) is not valid yaml format',
'Masking::Error::ConfigFileContainsNullAsColumnName' =>
'ERROR: config file (<%= config_file_path %>) is not valid, column name contains `null`',
'Masking::Error::InsertStatementParseError' =>
'ERROR: cannot parse SQL dump file. you may forget to put `--complete-insert` option in mysqldump?'
}.freeze
end
end
end
| ruby | MIT | ad72ffa4263c94de97b1749df8791d254e38017e | 2026-01-04T17:56:11.837143Z | false |
flyerhzm/eager_group | https://github.com/flyerhzm/eager_group/blob/7dc79e5705b24e6193e869ab8624c188399b438e/benchmark.rb | benchmark.rb | # frozen_string_literal: true
# Calculating -------------------------------------
# Without EagerGroup 2.000 i/100ms
# With EagerGroup 28.000 i/100ms
# -------------------------------------------------
# Without EagerGroup 28.883 (± 6.9%) i/s - 144.000
# With EagerGroup 281.755 (± 5.0%) i/s - 1.428k
#
# Comparison:
# With EagerGroup: 281.8 i/s
# Without EagerGroup: 28.9 i/s - 9.76x slower
$: << 'lib'
require 'benchmark/ips'
require 'active_record'
require 'activerecord-import'
require 'eager_group'
class Post < ActiveRecord::Base
has_many :comments
define_eager_group :comments_average_rating, :comments, :average, :rating
define_eager_group :approved_comments_count, :comments, :count, :*, -> { approved }
end
class Comment < ActiveRecord::Base
belongs_to :post
scope :approved, -> { where(status: 'approved') }
end
# create database eager_group_benchmark;
ActiveRecord::Base.establish_connection(
adapter: 'mysql2', database: 'eager_group_benchmark', server: '/tmp/mysql.socket', username: 'root'
)
ActiveRecord::Base.connection.tables.each { |table| ActiveRecord::Base.connection.drop_table(table) }
ActiveRecord::Schema.define do
self.verbose = false
create_table :posts, force: true do |t|
t.string :title
t.string :body
t.timestamps null: false
end
create_table :comments, force: true do |t|
t.string :body
t.string :status
t.integer :rating
t.integer :post_id
t.timestamps null: false
end
end
posts_size = 100
comments_size = 1_000
posts = []
posts_size.times { |i| posts << Post.new(title: "Title #{i}", body: "Body #{i}") }
Post.import posts
post_ids = Post.all.pluck(:id)
comments = []
comments_size.times do |i|
comments <<
Comment.new(
body: "Comment #{i}", post_id: post_ids[i % 100], status: %w[approved deleted][i % 2], rating: i % 5 + 1
)
end
Comment.import comments
Benchmark.ips do |x|
x.report('Without EagerGroup') do
Post.limit(20).each do |post|
post.comments.approved.count
post.comments.approved.average('rating')
end
end
x.report('With EagerGroup') do
Post.eager_group(:approved_comments_count, :comments_average_rating).limit(20).each do |post|
post.approved_comments_count
post.comments_average_rating
end
end
x.compare!
end
| ruby | MIT | 7dc79e5705b24e6193e869ab8624c188399b438e | 2026-01-04T17:56:14.651123Z | false |
flyerhzm/eager_group | https://github.com/flyerhzm/eager_group/blob/7dc79e5705b24e6193e869ab8624c188399b438e/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# The `.rspec` file also contains a few flags that are not defaults but that
# users commonly want.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
require 'eager_group'
require 'pry'
load 'support/schema.rb'
load 'support/models.rb'
load 'support/data.rb'
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions =
true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles =
true
end
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# These two settings work together to allow you to limit a spec run
# to individual examples or groups you care about by tagging them with
# `:focus` metadata. When nothing is tagged with `:focus`, all examples
# get run.
config.filter_run :focus
config.run_all_when_everything_filtered = true
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching
config.disable_monkey_patching!
# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = true
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = 'doc'
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end
| ruby | MIT | 7dc79e5705b24e6193e869ab8624c188399b438e | 2026-01-04T17:56:14.651123Z | false |
flyerhzm/eager_group | https://github.com/flyerhzm/eager_group/blob/7dc79e5705b24e6193e869ab8624c188399b438e/spec/support/data.rb | spec/support/data.rb | # frozen_string_literal: true
teacher1 = Teacher.create name: 'Teacher 1'
teacher2 = Teacher.create name: 'Teacher 2'
teacher3 = Teacher.create name: 'Teacher 3'
student1 = Student.create name: 'Student 1'
student2 = Student.create name: 'Student 2'
student3 = Student.create name: 'Student 3'
student4 = Student.create name: 'Student 4'
teacher1.students = [student1]
teacher2.students = [student2, student3, student4]
user1 = User.create(name: 'Alice')
user2 = User.create(name: 'Bob')
post1 = user1.posts.create(title: 'First post!')
post2 = user2.posts.create(title: 'Second post!')
post3 = user2.posts.create(title: 'Third post!')
post1.comments.create(status: 'created', rating: 4, author: student1)
post1.comments.create(status: 'approved', rating: 5, author: student1)
post1.comments.create(status: 'deleted', rating: 0, author: student2)
post2.comments.create(status: 'approved', rating: 3, author: student1)
post2.comments.create(status: 'approved', rating: 5, author: teacher1)
homework1 = Homework.create(student: student1, teacher: teacher1)
homework1 = Homework.create(student: student2, teacher: teacher1)
bus = SchoolBus.create(name: 'elementary bus')
sedan = Sedan.create(name: 'honda accord')
bus.passengers.create(name: 'Ruby', age: 7)
bus.passengers.create(name: 'Mike', age: 8)
bus.passengers.create(name: 'Zach', age: 9)
bus.passengers.create(name: 'Jacky', age: 10)
sedan.passengers.create(name: 'Ruby', age: 7)
sedan.passengers.create(name: 'Mike', age: 8)
sedan.passengers.create(name: 'Zach', age: 9)
sedan.passengers.create(name: 'Jacky', age: 10)
| ruby | MIT | 7dc79e5705b24e6193e869ab8624c188399b438e | 2026-01-04T17:56:14.651123Z | false |
flyerhzm/eager_group | https://github.com/flyerhzm/eager_group/blob/7dc79e5705b24e6193e869ab8624c188399b438e/spec/support/models.rb | spec/support/models.rb | # frozen_string_literal: true
class User < ActiveRecord::Base
has_many :posts
has_many :comments, through: :posts
define_eager_group :comments_count, :comments, :count, :*
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
define_eager_group :comments_average_rating, :comments, :average, :rating
define_eager_group :approved_comments_count, :comments, :count, :*, -> { approved }
define_eager_group :comments_average_rating_by_author,
:comments,
:average,
:rating,
->(author, ignore) { by_author(author, ignore) }
define_eager_group :first_comment, :comments, :first_object, :id
define_eager_group :last_comment, :comments, :last_object, :id
end
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :author, polymorphic: true
scope :approved, -> { where(status: 'approved') }
scope :by_author, ->(author, _ignore) { where(author: author) }
end
class Teacher < ActiveRecord::Base
has_and_belongs_to_many :students
has_many :homeworks
define_eager_group :students_count, :students, :count, :*
end
class Student < ActiveRecord::Base
has_and_belongs_to_many :teachers
has_many :comments, as: :author
has_many :posts, through: :comments
has_many :homeworks
define_eager_group :posts_count, :posts, :count, 'distinct post_id'
end
class Homework < ActiveRecord::Base
belongs_to :teacher
belongs_to :student
has_many :comments, through: :student
define_eager_group :students_count, :students, :count, '*'
define_eager_group :student_comments_count, :comments, :count, '*'
end
class Vehicle < ActiveRecord::Base
has_many :passengers
has_many :users, through: :passengers
define_eager_group :passengers_count, :passengers, :count, '*'
end
class SchoolBus < Vehicle
define_eager_group :credited_passengers_count, :passengers, :count, '*', -> { where('age < 10') }
define_eager_group :young_passengers_count, :passengers, :count, '*', -> { where('age < 8') }
end
class Sedan < Vehicle
define_eager_group :credited_passengers_count, :passengers, :count, '*', -> { where('age < 8') }
end
class Passenger < ActiveRecord::Base
belongs_to :vehicle
end
ActiveRecord::Base.logger = Logger.new(STDOUT)
| ruby | MIT | 7dc79e5705b24e6193e869ab8624c188399b438e | 2026-01-04T17:56:14.651123Z | false |
flyerhzm/eager_group | https://github.com/flyerhzm/eager_group/blob/7dc79e5705b24e6193e869ab8624c188399b438e/spec/support/schema.rb | spec/support/schema.rb | # frozen_string_literal: true
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Schema.define do
self.verbose = false
create_table :users, force: true do |t|
t.string :name
t.timestamps null: false
end
create_table :posts, force: true do |t|
t.string :title
t.string :body
t.integer :user_id
t.timestamps null: false
end
create_table :comments, force: true do |t|
t.string :body
t.string :status
t.string :author_type
t.integer :author_id
t.integer :rating
t.integer :post_id
t.timestamps null: false
end
create_table :teachers, force: true do |t|
t.string :name
t.timestamps null: false
end
create_table :students, force: true do |t|
t.string :name
t.timestamps null: false
end
create_table :students_teachers, force: true do |t|
t.integer :student_id
t.integer :teacher_id
end
create_table :homeworks, force: true do |t|
t.integer :teacher_id
t.integer :student_id
end
create_table :vehicles, force: true do |t|
t.string :type
t.string :name
t.timestamps null: false
end
create_table :passengers, force: true do |t|
t.integer :vehicle_id
t.string :name
t.integer :age
t.timestamps null: false
end
end
| ruby | MIT | 7dc79e5705b24e6193e869ab8624c188399b438e | 2026-01-04T17:56:14.651123Z | false |
flyerhzm/eager_group | https://github.com/flyerhzm/eager_group/blob/7dc79e5705b24e6193e869ab8624c188399b438e/spec/integration/eager_group_spec.rb | spec/integration/eager_group_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe EagerGroup, type: :model do
describe '.eager_group' do
context 'has_many' do
it 'gets Post#approved_comments_count' do
posts = Post.eager_group(:approved_comments_count)
expect(posts[0].approved_comments_count).to eq 1
expect(posts[1].approved_comments_count).to eq 2
expect(posts[2].approved_comments_count).to eq 0
end
it 'gets Post#comments_average_rating' do
posts = Post.eager_group(:comments_average_rating)
expect(posts[0].comments_average_rating).to eq 3
expect(posts[1].comments_average_rating).to eq 4
expect(posts[2].comments_average_rating).to eq 0
end
it 'gets both Post#approved_comments_count and Post#comments_average_rating' do
posts = Post.eager_group(:approved_comments_count, :comments_average_rating)
expect(posts[0].approved_comments_count).to eq 1
expect(posts[0].comments_average_rating).to eq 3
expect(posts[1].approved_comments_count).to eq 2
expect(posts[1].comments_average_rating).to eq 4
expect(posts[2].approved_comments_count).to eq 0
expect(posts[2].comments_average_rating).to eq 0
end
it 'gets Post#comments_average_rating_by_author' do
students = Student.all
posts = Post.eager_group([:comments_average_rating_by_author, students[0], true])
expect(posts[0].comments_average_rating_by_author).to eq 4.5
expect(posts[1].comments_average_rating_by_author).to eq 3
end
it 'eager_group multiple different type of aggregate definitions' do
students = Student.all
posts = Post.eager_group(:approved_comments_count, [:comments_average_rating_by_author, students[0], true])
#comments_average_rating_by_author
expect(posts[0].comments_average_rating_by_author).to eq 4.5
expect(posts[1].comments_average_rating_by_author).to eq 3
# approved_comments_count
expect(posts[0].approved_comments_count).to eq 1
expect(posts[1].approved_comments_count).to eq 2
expect(posts[2].approved_comments_count).to eq 0
end
it 'gets Post#comments_average_rating from users' do
users = User.includes(:posts).eager_group(posts: :comments_average_rating)
expect(users[0].posts[0].comments_average_rating).to eq 3
expect(users[1].posts[0].comments_average_rating).to eq 4
end
it 'gets Post#comments_average_rating from users' do
users = User.includes(:posts).eager_group(posts: :comments_average_rating)
expect(users[0].posts[0].comments_average_rating).to eq 3
expect(users[1].posts[0].comments_average_rating).to eq 4
end
it 'gets Post#first_comment and Post#last_comment' do
posts = Post.eager_group(:first_comment, :last_comment)
expect(posts[0].first_comment).to eq posts[0].comments.first
expect(posts[1].first_comment).to eq posts[1].comments.first
expect(posts[2].first_comment).to be_nil
expect(posts[0].last_comment).to eq posts[0].comments.last
expect(posts[1].last_comment).to eq posts[1].comments.last
expect(posts[2].last_comment).to be_nil
end
it 'gets Post#comments_average_rating and Post#comments_average_rating from users' do
users = User.includes(:posts).eager_group(posts: %i[approved_comments_count comments_average_rating])
expect(users[0].posts[0].approved_comments_count).to eq 1
expect(users[0].posts[0].comments_average_rating).to eq 3
expect(users[1].posts[0].approved_comments_count).to eq 2
expect(users[1].posts[0].comments_average_rating).to eq 4
end
it 'does not raise error when association is empty' do
Teacher.includes(:homeworks).eager_group(homeworks: :students_count).to_a
end
end
context 'has_and_belongs_to_many' do
it 'gets Teacher#students_count' do
teachers = Teacher.eager_group(:students_count)
expect(teachers[0].students_count).to eq 1
expect(teachers[1].students_count).to eq 3
expect(teachers[2].students_count).to eq 0
end
end
context 'has_many :through many' do
it 'gets Student#posts_count' do
students = Student.eager_group(:posts_count)
expect(students[0].posts_count).to eq 2
expect(students[1].posts_count).to eq 1
expect(students[2].posts_count).to eq 0
end
it 'gets User#comments_count' do
users = User.eager_group(:comments_count)
expect(users[0].comments_count).to eq 3
expect(users[1].comments_count).to eq 2
end
end
context 'has_many :through belongs to' do
it 'gets Homework#student_comments_count' do
homeworks = Homework.eager_group(:student_comments_count)
expect(homeworks[0].student_comments_count).to eq(3)
expect(homeworks[1].student_comments_count).to eq(1)
end
end
context 'support STI' do
it 'gets SchoolBus#credited_passengers_count' do
buses = SchoolBus.eager_group(:credited_passengers_count, :passengers_count)
expect(buses[0].credited_passengers_count).to eq(3)
expect(buses[0].passengers_count).to eq(4)
end
it 'gets Sedan#credited_passengers_count' do
sedans = Sedan.eager_group(:credited_passengers_count, :passengers_count)
expect(sedans[0].credited_passengers_count).to eq(1)
expect(sedans[0].passengers_count).to eq(4)
end
it 'gets Vehicle#passengers_count' do
vehicles = Vehicle.eager_group(:passengers_count)
expect(vehicles[0].passengers_count).to eq(4)
expect(vehicles[1].passengers_count).to eq(4)
end
end
context 'check arguments' do
context 'definition not exists' do
it 'should raise ArgumentError' do
expect{ Sedan.eager_group(:young_passengers_count) }.to raise_error(ArgumentError)
end
it 'should raise ArgumentError from association' do
expect{ User.includes(:posts).eager_group(posts: %i[unknown_eager_group_definition]) }.to raise_error(ArgumentError)
end
it "should raise ArgumentError when parent class call a non-exist definition" do
expect { Vehicle.eager_group(:credited_passengers_count) }.to raise_error(ArgumentError)
end
end
end
end
describe '.preload_eager_group' do
context 'Cache query result' do
it 'eager_group result cached' do
posts = Post.eager_group(:approved_comments_count)
post = posts[0]
object_id1 = post.instance_variable_get('@approved_comments_count').object_id
object_id2 = post.approved_comments_count.object_id
object_id3 = post.approved_comments_count.object_id
expect(object_id1).to eq object_id2
expect(object_id1).to eq object_id3
end
it 'eager_group result cached if arguments given' do
students = Student.all
posts = Post.eager_group([:comments_average_rating_by_author, students[0], true])
post = posts[0]
object_id1 = post.instance_variable_get('@comments_average_rating_by_author').object_id
object_id2 = post.comments_average_rating_by_author.object_id
object_id3 = post.comments_average_rating_by_author.object_id
expect(object_id1).to eq object_id2
expect(object_id1).to eq object_id3
end
it 'magic method result cached' do
post = Post.first
object_id1 = post.approved_comments_count.object_id
object_id2 = post.approved_comments_count.object_id
expect(object_id1).to eq object_id2
end
it 'magic method not cache if arguments given' do
students = Student.all
posts = Post.all
object_id1 = posts[0].comments_average_rating_by_author(students[0], true).object_id
object_id2 = posts[0].comments_average_rating_by_author(students[0], true).object_id
expect(object_id1).not_to eq object_id2
end
end
context 'has_many' do
it 'gets Post#approved_comments_count' do
posts = Post.all
expect(posts[0].approved_comments_count).to eq 1
expect(posts[1].approved_comments_count).to eq 2
end
it 'gets Post#comments_average_rating' do
posts = Post.all
expect(posts[0].comments_average_rating).to eq 3
expect(posts[1].comments_average_rating).to eq 4
end
it 'gets both Post#approved_comments_count and Post#comments_average_rating' do
posts = Post.all
expect(posts[0].approved_comments_count).to eq 1
expect(posts[0].comments_average_rating).to eq 3
expect(posts[1].approved_comments_count).to eq 2
expect(posts[1].comments_average_rating).to eq 4
expect(posts[2].approved_comments_count).to eq 0
end
it 'gets Post#comments_average_rating_by_author' do
students = Student.all
posts = Post.all
expect(posts[0].comments_average_rating_by_author(students[0], true)).to eq 4.5
expect(posts[1].comments_average_rating_by_author(students[0], true)).to eq 3
end
end
context 'has_and_belongs_to_many' do
it 'gets Teacher#students_count' do
teachers = Teacher.all
expect(teachers[0].students_count).to eq 1
expect(teachers[1].students_count).to eq 3
expect(teachers[2].students_count).to eq 0
end
end
context 'has_many :as, has_many :through' do
it 'gets Student#posts_count' do
students = Student.all
expect(students[0].posts_count).to eq 2
expect(students[1].posts_count).to eq 1
expect(students[2].posts_count).to eq 0
end
end
end
end
| ruby | MIT | 7dc79e5705b24e6193e869ab8624c188399b438e | 2026-01-04T17:56:14.651123Z | false |
flyerhzm/eager_group | https://github.com/flyerhzm/eager_group/blob/7dc79e5705b24e6193e869ab8624c188399b438e/lib/eager_group.rb | lib/eager_group.rb | # frozen_string_literal: true
require 'active_support/core_ext/module/attribute_accessors'
require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/hash'
require 'eager_group/version'
module EagerGroup
autoload :Preloader, 'eager_group/preloader'
autoload :Definition, 'eager_group/definition'
def self.included(base)
base.extend ClassMethods
base.class_eval do
class_attribute :eager_group_definitions, instance_writer: false, default: {}.with_indifferent_access
end
end
module ClassMethods
#mattr_accessor :eager_group_definitions, default: {}
def add_eager_group_definition(ar, definition_name, definition)
ar.eager_group_definitions = self.eager_group_definitions.except(definition_name).merge!(definition_name => definition)
end
# class Post
# define_eager_group :comments_avergage_rating, :comments, :average, :rating
# define_eager_group :approved_comments_count, :comments, :count, :*, -> { approved }
# end
def define_eager_group(attr, association, aggregate_function, column_name, scope = nil)
add_eager_group_definition(self, attr, Definition.new(association, aggregate_function, column_name, scope))
define_definition_accessor(attr)
end
def define_definition_accessor(definition_name)
define_method definition_name,
lambda { |*args|
query_result_cache = instance_variable_get("@#{definition_name}")
return query_result_cache if args.blank? && query_result_cache.present?
preload_eager_group(definition_name, *args)
instance_variable_get("@#{definition_name}")
}
define_method "#{definition_name}=" do |val|
instance_variable_set("@#{definition_name}", val)
end
end
end
private
def preload_eager_group(*eager_group_value)
EagerGroup::Preloader.new(self.class, [self], [eager_group_value]).run
end
end
require 'active_record'
ActiveRecord::Base.class_eval do
include EagerGroup
class << self
delegate :eager_group, to: :all
end
end
require 'active_record/with_eager_group'
ActiveRecord::Relation.prepend ActiveRecord::WithEagerGroup
| ruby | MIT | 7dc79e5705b24e6193e869ab8624c188399b438e | 2026-01-04T17:56:14.651123Z | false |
flyerhzm/eager_group | https://github.com/flyerhzm/eager_group/blob/7dc79e5705b24e6193e869ab8624c188399b438e/lib/active_record/with_eager_group.rb | lib/active_record/with_eager_group.rb | # frozen_string_literal: true
module ActiveRecord
module WithEagerGroup
def exec_queries
records = super
EagerGroup::Preloader.new(klass, records, eager_group_values).run if eager_group_values.present?
records
end
def eager_group(*args)
# we does not use the `check_if_method_has_arguments!` here because it would flatten all the arguments,
# which would cause `[:eager_group_definition, scope_arg1, scope_arg2]` not able to preload together with other `eager_group_definitions`.
# e.g. `Post.eager_group(:approved_comments_count, [:comments_average_rating_by_author, students[0], true])`
check_argument_not_blank!(args)
check_argument_valid!(args)
spawn.eager_group!(*args)
end
def eager_group!(*args)
self.eager_group_values |= args
self
end
def eager_group_values
@values[:eager_group] || []
end
def eager_group_values=(values)
raise ImmutableRelation if @loaded
@values[:eager_group] = values
end
private
def check_argument_not_blank!(args)
raise ArgumentError, "The method .eager_group() must contain arguments." if args.blank?
args.compact_blank!
end
def check_argument_valid!(args)
args.each do |eager_group_value|
check_eager_group_definitions_exists!(klass, eager_group_value)
end
end
def check_eager_group_definitions_exists!(klass, eager_group_value)
case eager_group_value
when Symbol, String
raise ArgumentError, "Unknown eager group definition :#{eager_group_value}" unless klass.eager_group_definitions.has_key?(eager_group_value)
when Array
definition_name = eager_group_value.first
raise ArgumentError, "Unknown eager group definition :#{definition_name}" unless klass.eager_group_definitions.has_key?(definition_name)
when Hash
eager_group_value.each do |association_name, association_eager_group_values|
association_klass = klass.reflect_on_association(association_name).klass
Array.wrap(association_eager_group_values).each do |association_eager_group_value|
check_eager_group_definitions_exists!(association_klass, association_eager_group_value)
end
end
else
raise ArgumentError, "Unknown eager_group argument :#{eager_group_value.inspect}"
end
end
end
end
| ruby | MIT | 7dc79e5705b24e6193e869ab8624c188399b438e | 2026-01-04T17:56:14.651123Z | false |
flyerhzm/eager_group | https://github.com/flyerhzm/eager_group/blob/7dc79e5705b24e6193e869ab8624c188399b438e/lib/eager_group/preloader.rb | lib/eager_group/preloader.rb | # frozen_string_literal: true
module EagerGroup
class Preloader
autoload :AggregationFinder, 'eager_group/preloader/aggregation_finder'
autoload :HasMany, 'eager_group/preloader/has_many'
autoload :HasManyThroughBelongsTo, 'eager_group/preloader/has_many_through_belongs_to'
autoload :HasManyThroughMany, 'eager_group/preloader/has_many_through_many'
autoload :ManyToMany, 'eager_group/preloader/many_to_many'
def initialize(klass, records, eager_group_values)
@klass = klass
@records = Array.wrap(records).compact.uniq
@eager_group_values = eager_group_values
end
# Preload aggregate functions
def run
@eager_group_values.each do |eager_group_value|
definition_key, arguments =
eager_group_value.is_a?(Array) ? [eager_group_value.shift, eager_group_value] : [eager_group_value, nil]
if definition_key.is_a?(Hash)
association_name, definition_key = *definition_key.first
next if @records.empty?
@klass = @records.first.class.reflect_on_association(association_name).klass
@records = @records.flat_map { |record| record.send(association_name) }
next if @records.empty?
self.class.new(@klass, @records, Array.wrap(definition_key)).run
end
find_aggregate_values_per_definition!(definition_key, arguments)
end
end
def find_aggregate_values_per_definition!(definition_key, arguments)
unless definition = @klass.eager_group_definitions[definition_key]
return
end
reflection = @klass.reflect_on_association(definition.association)
return if reflection.blank?
aggregation_finder_class = if reflection.is_a?(ActiveRecord::Reflection::HasAndBelongsToManyReflection)
ManyToMany
elsif reflection.through_reflection
if reflection.through_reflection.is_a?(ActiveRecord::Reflection::BelongsToReflection)
HasManyThroughBelongsTo
else
HasManyThroughMany
end
else
HasMany
end
aggregation_finder = aggregation_finder_class.new(@klass, definition, arguments, @records)
aggregate_hash = aggregation_finder.aggregate_hash
if definition.need_load_object
aggregate_objects = reflection.klass.find(aggregate_hash.values).each_with_object({}) { |o, h| h[o.id] = o }
aggregate_hash.keys.each { |key| aggregate_hash[key] = aggregate_objects[aggregate_hash[key]] }
end
@records.each do |record|
id = record.send(aggregation_finder.group_by_key)
record.send("#{definition_key}=", aggregate_hash[id] || definition.default_value)
end
end
private
def polymophic_as_condition(reflection)
reflection.type ? { reflection.name => { reflection.type => @klass.base_class.name } } : []
end
end
end
| ruby | MIT | 7dc79e5705b24e6193e869ab8624c188399b438e | 2026-01-04T17:56:14.651123Z | false |
flyerhzm/eager_group | https://github.com/flyerhzm/eager_group/blob/7dc79e5705b24e6193e869ab8624c188399b438e/lib/eager_group/version.rb | lib/eager_group/version.rb | # frozen_string_literal: true
module EagerGroup
VERSION = '0.10.0'
end
| ruby | MIT | 7dc79e5705b24e6193e869ab8624c188399b438e | 2026-01-04T17:56:14.651123Z | false |
flyerhzm/eager_group | https://github.com/flyerhzm/eager_group/blob/7dc79e5705b24e6193e869ab8624c188399b438e/lib/eager_group/definition.rb | lib/eager_group/definition.rb | # frozen_string_literal: true
module EagerGroup
class Definition
attr_reader :association, :column_name, :scope
def initialize(association, aggregate_function, column_name, scope)
@association = association
@aggregate_function = aggregate_function
@column_name = column_name
@scope = scope
end
def aggregation_function
return :maximum if @aggregate_function.to_sym == :last_object
return :minimum if @aggregate_function.to_sym == :first_object
@aggregate_function
end
def need_load_object
%i[first_object last_object].include?(@aggregate_function.to_sym)
end
def default_value
%i[first_object last_object].include?(@aggregate_function.to_sym) ? nil : 0
end
end
end
| ruby | MIT | 7dc79e5705b24e6193e869ab8624c188399b438e | 2026-01-04T17:56:14.651123Z | false |
flyerhzm/eager_group | https://github.com/flyerhzm/eager_group/blob/7dc79e5705b24e6193e869ab8624c188399b438e/lib/eager_group/preloader/has_many_through_belongs_to.rb | lib/eager_group/preloader/has_many_through_belongs_to.rb | # frozen_string_literal: true
module EagerGroup
class Preloader
class HasManyThroughBelongsTo < AggregationFinder
def group_by_foreign_key
"#{reflection.table_name}.#{reflection.through_reflection.klass.reflect_on_association(reflection.name).foreign_key}"
end
def aggregate_hash
scope = reflection.klass.all.tap{|query| query.merge!(definition_scope) if definition_scope }
scope.where(group_by_foreign_key => record_ids).
where(polymophic_as_condition).
group(group_by_foreign_key).
send(definition.aggregation_function, definition.column_name)
end
def group_by_key
reflection.through_reflection.foreign_key
end
def polymophic_as_condition
reflection.type ? { reflection.name => { reflection.type => reflection.through_reflection.klass.base_class.name } } : []
end
end
end
end
| ruby | MIT | 7dc79e5705b24e6193e869ab8624c188399b438e | 2026-01-04T17:56:14.651123Z | false |
flyerhzm/eager_group | https://github.com/flyerhzm/eager_group/blob/7dc79e5705b24e6193e869ab8624c188399b438e/lib/eager_group/preloader/aggregation_finder.rb | lib/eager_group/preloader/aggregation_finder.rb | # frozen_string_literal: true
module EagerGroup
class Preloader
class AggregationFinder
attr_reader :klass, :reflection, :definition, :arguments, :record_ids
def initialize(klass, definition, arguments, records)
@klass = klass
@definition = definition
@reflection = @klass.reflect_on_association(definition.association)
@arguments = arguments
@records = records
end
def definition_scope
reflection.klass.instance_exec(*arguments, &definition.scope) if definition.scope
end
def record_ids
@record_ids ||= @records.map { |record| record.send(group_by_key) }
end
def group_by_key
@klass.primary_key
end
def aggregate_hash
raise NotImplementedError, 'Method "aggregate_hash" must be implemented in subclass'
end
private
def polymophic_as_condition
reflection.type ? { reflection.name => { reflection.type => @klass.base_class.name } } : []
end
end
end
end
| ruby | MIT | 7dc79e5705b24e6193e869ab8624c188399b438e | 2026-01-04T17:56:14.651123Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.